From be0116460e44ac310fdb8d334cead3021196a423 Mon Sep 17 00:00:00 2001 From: wess Date: Tue, 11 Apr 2023 07:47:39 -0400 Subject: [PATCH] Ran the oh-mighty-pint --- app/cli.php | 4 +- app/config/avatars/browsers.php | 28 +- app/config/avatars/credit-cards.php | 32 +- app/config/avatars/flags.php | 388 +++--- app/config/avatars/os.php | 6 +- app/config/collections.php | 49 +- app/config/errors.php | 6 +- app/config/events.php | 62 +- app/config/locale/languages.php | 1106 ++++++++--------- app/config/platforms.php | 44 +- app/config/providers.php | 14 +- app/config/regions.php | 2 +- app/config/runtimes.php | 2 +- app/config/scopes.php | 2 +- app/config/services.php | 4 +- app/config/variables.php | 152 +-- app/controllers/api/account.php | 422 +++---- app/controllers/api/avatars.php | 75 +- app/controllers/api/databases.php | 485 ++++---- app/controllers/api/domains.php | 495 ++++---- app/controllers/api/functions.php | 158 ++- app/controllers/api/graphql.php | 23 +- app/controllers/api/health.php | 58 +- app/controllers/api/locale.php | 27 +- app/controllers/api/projects.php | 104 +- app/controllers/api/storage.php | 303 +++-- app/controllers/api/teams.php | 145 +-- app/controllers/api/users.php | 76 +- app/controllers/general.php | 153 ++- app/controllers/mock.php | 64 +- app/controllers/shared/api.php | 107 +- app/controllers/web/console.php | 2 +- app/controllers/web/home.php | 4 +- app/executor.php | 156 ++- app/http.php | 72 +- app/init.php | 344 ++--- app/preload.php | 38 +- app/realtime.php | 131 +- app/tasks/doctor.php | 69 +- app/tasks/install.php | 64 +- app/tasks/maintenance.php | 21 +- app/tasks/migrate.php | 19 +- app/tasks/sdks.php | 78 +- app/tasks/specs.php | 48 +- app/tasks/ssl.php | 4 +- app/tasks/usage.php | 14 +- app/tasks/vars.php | 2 +- app/workers/audits.php | 6 +- app/workers/builds.php | 33 +- app/workers/certificates.php | 145 +-- app/workers/databases.php | 75 +- app/workers/deletes.php | 234 ++-- app/workers/functions.php | 34 +- app/workers/mails.php | 12 +- app/workers/messaging.php | 11 +- app/workers/webhooks.php | 30 +- src/Appwrite/Auth/Auth.php | 116 +- src/Appwrite/Auth/Hash.php | 25 +- src/Appwrite/Auth/Hash/Argon2.php | 10 +- src/Appwrite/Auth/Hash/Bcrypt.php | 12 +- src/Appwrite/Auth/Hash/Md5.php | 10 +- src/Appwrite/Auth/Hash/Phpass.php | 61 +- src/Appwrite/Auth/Hash/Scrypt.php | 12 +- src/Appwrite/Auth/Hash/Scryptmodified.php | 14 +- src/Appwrite/Auth/Hash/Sha.php | 12 +- src/Appwrite/Auth/OAuth2.php | 53 +- src/Appwrite/Auth/OAuth2/Amazon.php | 40 +- src/Appwrite/Auth/OAuth2/Apple.php | 47 +- src/Appwrite/Auth/OAuth2/Auth0.php | 41 +- src/Appwrite/Auth/OAuth2/Authentik.php | 47 +- src/Appwrite/Auth/OAuth2/Autodesk.php | 29 +- src/Appwrite/Auth/OAuth2/Bitbucket.php | 32 +- src/Appwrite/Auth/OAuth2/Bitly.php | 57 +- src/Appwrite/Auth/OAuth2/Box.php | 53 +- src/Appwrite/Auth/OAuth2/Dailymotion.php | 50 +- src/Appwrite/Auth/OAuth2/Discord.php | 39 +- src/Appwrite/Auth/OAuth2/Disqus.php | 36 +- src/Appwrite/Auth/OAuth2/Dropbox.php | 31 +- src/Appwrite/Auth/OAuth2/Etsy.php | 33 +- src/Appwrite/Auth/OAuth2/Facebook.php | 39 +- src/Appwrite/Auth/OAuth2/Github.php | 33 +- src/Appwrite/Auth/OAuth2/Gitlab.php | 40 +- src/Appwrite/Auth/OAuth2/Google.php | 37 +- src/Appwrite/Auth/OAuth2/Linkedin.php | 33 +- src/Appwrite/Auth/OAuth2/Microsoft.php | 40 +- src/Appwrite/Auth/OAuth2/Mock.php | 38 +- src/Appwrite/Auth/OAuth2/Notion.php | 43 +- src/Appwrite/Auth/OAuth2/Okta.php | 41 +- src/Appwrite/Auth/OAuth2/Paypal.php | 41 +- src/Appwrite/Auth/OAuth2/PaypalSandbox.php | 2 - src/Appwrite/Auth/OAuth2/Podio.php | 41 +- src/Appwrite/Auth/OAuth2/Salesforce.php | 42 +- src/Appwrite/Auth/OAuth2/Slack.php | 39 +- src/Appwrite/Auth/OAuth2/Spotify.php | 47 +- src/Appwrite/Auth/OAuth2/Stripe.php | 37 +- src/Appwrite/Auth/OAuth2/Tradeshift.php | 52 +- src/Appwrite/Auth/OAuth2/TradeshiftBox.php | 2 - src/Appwrite/Auth/OAuth2/Twitch.php | 53 +- src/Appwrite/Auth/OAuth2/WordPress.php | 31 +- src/Appwrite/Auth/OAuth2/Yahoo.php | 49 +- src/Appwrite/Auth/OAuth2/Yammer.php | 37 +- src/Appwrite/Auth/OAuth2/Yandex.php | 43 +- src/Appwrite/Auth/OAuth2/Zoom.php | 39 +- src/Appwrite/Auth/Validator/Password.php | 5 +- src/Appwrite/Auth/Validator/Phone.php | 5 +- src/Appwrite/DSN/DSN.php | 4 +- src/Appwrite/Detector/Detector.php | 8 +- src/Appwrite/Docker/Compose.php | 4 +- src/Appwrite/Docker/Compose/Service.php | 5 +- src/Appwrite/Docker/Env.php | 14 +- src/Appwrite/Event/Audit.php | 12 +- src/Appwrite/Event/Build.php | 11 +- src/Appwrite/Event/Certificate.php | 8 +- src/Appwrite/Event/Database.php | 17 +- src/Appwrite/Event/Delete.php | 25 +- src/Appwrite/Event/Event.php | 77 +- src/Appwrite/Event/Func.php | 22 +- src/Appwrite/Event/Mail.php | 18 +- src/Appwrite/Event/Phone.php | 8 +- src/Appwrite/Event/Validator/Event.php | 23 +- src/Appwrite/Extend/Exception.php | 294 +++-- src/Appwrite/Extend/PDO.php | 3 +- src/Appwrite/Extend/PDOStatement.php | 5 +- src/Appwrite/GraphQL/Promises/Adapter.php | 21 +- src/Appwrite/GraphQL/Resolvers.php | 129 +- src/Appwrite/GraphQL/Schema.php | 68 +- src/Appwrite/GraphQL/Types.php | 3 + src/Appwrite/GraphQL/Types/Assoc.php | 8 +- src/Appwrite/GraphQL/Types/InputFile.php | 3 +- src/Appwrite/GraphQL/Types/Json.php | 4 +- src/Appwrite/GraphQL/Types/Mapper.php | 47 +- src/Appwrite/GraphQL/Types/Registry.php | 8 +- src/Appwrite/Messaging/Adapter.php | 2 + src/Appwrite/Messaging/Adapter/Realtime.php | 84 +- src/Appwrite/Migration/Migration.php | 74 +- src/Appwrite/Migration/Version/V15.php | 49 +- src/Appwrite/Migration/Version/V16.php | 14 +- src/Appwrite/Migration/Version/V17.php | 12 +- src/Appwrite/Network/Validator/CNAME.php | 9 +- src/Appwrite/Network/Validator/Email.php | 6 +- src/Appwrite/Network/Validator/Origin.php | 39 +- src/Appwrite/OpenSSL/OpenSSL.php | 26 +- src/Appwrite/Promises/Promise.php | 35 +- src/Appwrite/Promises/Swoole.php | 4 +- src/Appwrite/Resque/Worker.php | 84 +- src/Appwrite/Specification/Format.php | 15 +- .../Specification/Format/OpenAPI3.php | 86 +- .../Specification/Format/Swagger2.php | 81 +- src/Appwrite/Task/Validator/Cron.php | 5 +- src/Appwrite/Template/Template.php | 37 +- src/Appwrite/URL/URL.php | 34 +- src/Appwrite/Usage/Calculators/TimeSeries.php | 72 +- src/Appwrite/Usage/Stats.php | 58 +- .../Utopia/Database/Validator/CustomId.php | 2 - .../Database/Validator/IndexedQueries.php | 40 +- .../Database/Validator/OrderAttributes.php | 6 +- .../Utopia/Database/Validator/Queries.php | 19 +- .../Database/Validator/Queries/Base.php | 10 +- .../Database/Validator/Queries/Buckets.php | 3 +- .../Validator/Queries/Collections.php | 3 +- .../Database/Validator/Queries/Databases.php | 3 +- .../Validator/Queries/Deployments.php | 1 - .../Database/Validator/Queries/Documents.php | 8 +- .../Database/Validator/Queries/Executions.php | 3 +- .../Database/Validator/Queries/Files.php | 3 +- .../Database/Validator/Queries/Functions.php | 3 +- .../Validator/Queries/Memberships.php | 3 +- .../Database/Validator/Queries/Projects.php | 5 +- .../Database/Validator/Queries/Teams.php | 3 +- .../Database/Validator/Queries/Users.php | 3 +- .../Database/Validator/Queries/Variables.php | 5 +- .../Utopia/Database/Validator/Query/Base.php | 6 +- .../Database/Validator/Query/Cursor.php | 7 +- .../Database/Validator/Query/Filter.php | 22 +- .../Utopia/Database/Validator/Query/Limit.php | 13 +- .../Database/Validator/Query/Offset.php | 13 +- .../Utopia/Database/Validator/Query/Order.php | 12 +- src/Appwrite/Utopia/Request.php | 11 +- src/Appwrite/Utopia/Request/Filter.php | 5 +- src/Appwrite/Utopia/Request/Filters/V12.php | 45 +- src/Appwrite/Utopia/Request/Filters/V13.php | 16 +- src/Appwrite/Utopia/Request/Filters/V14.php | 12 +- src/Appwrite/Utopia/Request/Filters/V15.php | 25 +- src/Appwrite/Utopia/Response.php | 219 +++- src/Appwrite/Utopia/Response/Filter.php | 5 +- src/Appwrite/Utopia/Response/Filters/V11.php | 35 +- src/Appwrite/Utopia/Response/Filters/V12.php | 12 + src/Appwrite/Utopia/Response/Filters/V13.php | 3 + src/Appwrite/Utopia/Response/Filters/V15.php | 18 +- src/Appwrite/Utopia/Response/Model.php | 17 +- .../Utopia/Response/Model/AlgoArgon2.php | 3 +- .../Utopia/Response/Model/AlgoScrypt.php | 3 +- .../Response/Model/AlgoScryptModified.php | 3 +- .../Utopia/Response/Model/Attribute.php | 3 +- .../Response/Model/AttributeBoolean.php | 8 +- .../Response/Model/AttributeDatetime.php | 5 +- .../Utopia/Response/Model/AttributeEmail.php | 6 +- .../Utopia/Response/Model/AttributeEnum.php | 6 +- .../Utopia/Response/Model/AttributeFloat.php | 4 +- .../Utopia/Response/Model/AttributeIP.php | 6 +- .../Response/Model/AttributeInteger.php | 5 +- .../Utopia/Response/Model/AttributeList.php | 8 +- .../Utopia/Response/Model/AttributeString.php | 4 +- .../Utopia/Response/Model/AttributeURL.php | 6 +- .../Utopia/Response/Model/BaseList.php | 20 +- src/Appwrite/Utopia/Response/Model/Bucket.php | 9 +- src/Appwrite/Utopia/Response/Model/Build.php | 3 +- .../Utopia/Response/Model/Collection.php | 7 +- .../Utopia/Response/Model/Continent.php | 3 +- .../Utopia/Response/Model/Country.php | 3 +- .../Utopia/Response/Model/Currency.php | 3 +- .../Utopia/Response/Model/Database.php | 3 +- .../Utopia/Response/Model/Deployment.php | 3 +- src/Appwrite/Utopia/Response/Model/Domain.php | 3 +- src/Appwrite/Utopia/Response/Model/Error.php | 3 +- .../Utopia/Response/Model/ErrorDev.php | 3 +- .../Utopia/Response/Model/Execution.php | 3 +- src/Appwrite/Utopia/Response/Model/File.php | 3 +- src/Appwrite/Utopia/Response/Model/Func.php | 7 +- .../Utopia/Response/Model/HealthAntivirus.php | 3 +- .../Utopia/Response/Model/HealthQueue.php | 3 +- .../Utopia/Response/Model/HealthStatus.php | 3 +- .../Utopia/Response/Model/HealthTime.php | 3 +- .../Utopia/Response/Model/HealthVersion.php | 3 +- src/Appwrite/Utopia/Response/Model/Index.php | 3 +- src/Appwrite/Utopia/Response/Model/JWT.php | 3 +- src/Appwrite/Utopia/Response/Model/Key.php | 7 +- .../Utopia/Response/Model/Language.php | 3 +- src/Appwrite/Utopia/Response/Model/Locale.php | 3 +- src/Appwrite/Utopia/Response/Model/Log.php | 3 +- .../Utopia/Response/Model/Membership.php | 3 +- src/Appwrite/Utopia/Response/Model/Metric.php | 2 +- src/Appwrite/Utopia/Response/Model/Mock.php | 3 +- src/Appwrite/Utopia/Response/Model/Phone.php | 3 +- .../Utopia/Response/Model/Platform.php | 3 +- .../Utopia/Response/Model/Project.php | 35 +- .../Utopia/Response/Model/Provider.php | 3 +- .../Utopia/Response/Model/Runtime.php | 5 +- .../Utopia/Response/Model/Session.php | 3 +- src/Appwrite/Utopia/Response/Model/Team.php | 3 +- src/Appwrite/Utopia/Response/Model/Token.php | 3 +- .../Utopia/Response/Model/UsageBuckets.php | 15 +- .../Utopia/Response/Model/UsageCollection.php | 13 +- .../Utopia/Response/Model/UsageDatabase.php | 23 +- .../Utopia/Response/Model/UsageDatabases.php | 33 +- .../Utopia/Response/Model/UsageFunction.php | 19 +- .../Utopia/Response/Model/UsageFunctions.php | 19 +- .../Utopia/Response/Model/UsageProject.php | 19 +- .../Utopia/Response/Model/UsageStorage.php | 25 +- .../Utopia/Response/Model/UsageUsers.php | 19 +- src/Appwrite/Utopia/Response/Model/User.php | 4 +- .../Utopia/Response/Model/Variable.php | 3 +- .../Utopia/Response/Model/Webhook.php | 3 +- src/Appwrite/Utopia/View.php | 3 +- src/Executor/Executor.php | 119 +- tests/e2e/Client.php | 74 +- tests/e2e/General/AbuseTest.php | 42 +- tests/e2e/General/HTTPTest.php | 8 +- tests/e2e/General/UsageTest.php | 117 +- tests/e2e/Scopes/ProjectCustom.php | 23 +- tests/e2e/Scopes/Scope.php | 14 +- tests/e2e/Scopes/SideClient.php | 2 +- tests/e2e/Scopes/SideConsole.php | 4 +- tests/e2e/Scopes/SideServer.php | 2 +- tests/e2e/Services/Account/AccountBase.php | 193 ++- .../Account/AccountConsoleClientTest.php | 2 +- .../Account/AccountCustomClientTest.php | 128 +- .../Account/AccountCustomServerTest.php | 2 +- tests/e2e/Services/Avatars/AvatarsBase.php | 17 +- .../Avatars/AvatarsConsoleClientTest.php | 2 +- .../Avatars/AvatarsCustomClientTest.php | 2 +- .../e2e/Services/Databases/DatabasesBase.php | 648 +++++----- .../Databases/DatabasesConsoleClientTest.php | 42 +- .../Databases/DatabasesCustomClientTest.php | 56 +- .../Databases/DatabasesCustomServerTest.php | 299 ++--- .../DatabasesPermissionsGuestTest.php | 48 +- .../DatabasesPermissionsMemberTest.php | 40 +- .../Databases/DatabasesPermissionsScope.php | 15 +- .../DatabasesPermissionsTeamTest.php | 27 +- tests/e2e/Services/Domains/DomainsBase.php | 2 - .../Domains/DomainsRegistrarClientTest.php | 524 ++++---- .../e2e/Services/Functions/FunctionsBase.php | 3 +- .../Functions/FunctionsConsoleClientTest.php | 125 +- .../Functions/FunctionsCustomClientTest.php | 99 +- .../Functions/FunctionsCustomServerTest.php | 245 ++-- tests/e2e/Services/GraphQL/AbuseTest.php | 8 +- tests/e2e/Services/GraphQL/AccountTest.php | 36 +- tests/e2e/Services/GraphQL/AuthTest.php | 49 +- tests/e2e/Services/GraphQL/Base.php | 145 ++- tests/e2e/Services/GraphQL/BatchTest.php | 39 +- .../e2e/Services/GraphQL/ContentTypeTest.php | 8 +- .../Services/GraphQL/DatabaseClientTest.php | 22 +- .../Services/GraphQL/DatabaseServerTest.php | 85 +- .../Services/GraphQL/FunctionsClientTest.php | 26 +- .../Services/GraphQL/FunctionsServerTest.php | 54 +- .../e2e/Services/GraphQL/LocalizationTest.php | 2 +- tests/e2e/Services/GraphQL/ScopeTest.php | 5 +- .../Services/GraphQL/StorageClientTest.php | 36 +- .../Services/GraphQL/StorageServerTest.php | 49 +- tests/e2e/Services/GraphQL/UsersTest.php | 39 +- tests/e2e/Services/Health/HealthBase.php | 2 - .../Health/HealthCustomServerTest.php | 3 +- tests/e2e/Services/Locale/LocaleBase.php | 16 +- .../Locale/LocaleConsoleClientTest.php | 2 +- .../Locale/LocaleCustomClientTest.php | 2 +- .../Locale/LocaleCustomServerTest.php | 1 - tests/e2e/Services/Projects/ProjectsBase.php | 2 - .../Projects/ProjectsConsoleClientTest.php | 404 +++--- .../Projects/ProjectsCustomClientTest.php | 3 +- .../Projects/ProjectsCustomServerTest.php | 1 - tests/e2e/Services/Realtime/RealtimeBase.php | 12 +- .../Realtime/RealtimeConsoleClientTest.php | 49 +- .../Realtime/RealtimeCustomClientTest.php | 321 +++-- tests/e2e/Services/Storage/StorageBase.php | 154 ++- .../Storage/StorageConsoleClientTest.php | 29 +- .../Storage/StorageCustomClientTest.php | 418 ++++--- .../Storage/StorageCustomServerTest.php | 46 +- .../Storage/StoragePermissionsScope.php | 16 +- tests/e2e/Services/Teams/TeamsBase.php | 36 +- tests/e2e/Services/Teams/TeamsBaseClient.php | 138 +- tests/e2e/Services/Teams/TeamsBaseServer.php | 53 +- .../Services/Teams/TeamsConsoleClientTest.php | 34 +- .../Services/Teams/TeamsCustomClientTest.php | 2 +- .../Services/Teams/TeamsCustomServerTest.php | 1 - tests/e2e/Services/Users/UsersBase.php | 152 ++- .../Services/Users/UsersConsoleClientTest.php | 21 +- .../Services/Users/UsersCustomServerTest.php | 1 - tests/e2e/Services/Webhooks/WebhooksBase.php | 127 +- .../Webhooks/WebhooksCustomClientTest.php | 101 +- .../Webhooks/WebhooksCustomServerTest.php | 80 +- tests/extensions/Retryable.php | 13 +- tests/extensions/TestHook.php | 2 +- tests/resources/functions/php-fn/index.php | 2 +- tests/resources/functions/php-large/index.php | 2 +- tests/resources/functions/php/index.php | 2 +- tests/unit/Auth/AuthTest.php | 62 +- tests/unit/DSN/DSNTest.php | 76 +- tests/unit/Docker/ComposeTest.php | 2 +- tests/unit/Docker/EnvTest.php | 6 +- tests/unit/Event/EventTest.php | 12 +- tests/unit/General/CollectionsTest.php | 2 +- .../unit/Messaging/MessagingChannelsTest.php | 53 +- tests/unit/Messaging/MessagingGuestTest.php | 4 +- tests/unit/Messaging/MessagingTest.php | 28 +- tests/unit/Migration/MigrationTest.php | 50 +- tests/unit/Network/Validators/EmailTest.php | 5 +- tests/unit/Template/TemplateTest.php | 5 +- tests/unit/Usage/StatsTest.php | 6 +- .../Database/Validator/IndexedQueriesTest.php | 2 +- .../Utopia/Database/Validator/QueriesTest.php | 4 +- .../Database/Validator/Query/CursorTest.php | 2 +- .../Database/Validator/Query/FilterTest.php | 2 +- .../Database/Validator/Query/LimitTest.php | 2 +- .../Database/Validator/Query/OffsetTest.php | 2 +- .../Database/Validator/Query/OrderTest.php | 2 +- tests/unit/Utopia/Lists.php | 2 +- tests/unit/Utopia/Nested.php | 2 +- tests/unit/Utopia/Request/Filters/V15Test.php | 26 +- .../unit/Utopia/Response/Filters/V15Test.php | 55 +- tests/unit/Utopia/ResponseTest.php | 13 +- tests/unit/Utopia/Single.php | 4 +- 361 files changed, 8395 insertions(+), 8561 deletions(-) diff --git a/app/cli.php b/app/cli.php index 09b3dc9413..e98f0d76a5 100644 --- a/app/cli.php +++ b/app/cli.php @@ -1,7 +1,7 @@ __DIR__ . '/browsers/avant.png', - 'an' => __DIR__ . '/browsers/android-webview-beta.png', - 'ch' => __DIR__ . '/browsers/chrome.png', - 'ci' => __DIR__ . '/browsers/chrome.png', //Chrome Mobile iOS - 'cm' => __DIR__ . '/browsers/chrome.png', //Chrome Mobile - 'cr' => __DIR__ . '/browsers/chromium.png', - 'ff' => __DIR__ . '/browsers/firefox.png', - 'sf' => __DIR__ . '/browsers/safari.png', - 'mf' => __DIR__ . '/browsers/safari.png', - 'ps' => __DIR__ . '/browsers/edge.png', - 'oi' => __DIR__ . '/browsers/edge.png', - 'om' => __DIR__ . '/browsers/opera-mini.png', - 'op' => __DIR__ . '/browsers/opera.png', - 'on' => __DIR__ . '/browsers/opera.png', + 'aa' => __DIR__.'/browsers/avant.png', + 'an' => __DIR__.'/browsers/android-webview-beta.png', + 'ch' => __DIR__.'/browsers/chrome.png', + 'ci' => __DIR__.'/browsers/chrome.png', //Chrome Mobile iOS + 'cm' => __DIR__.'/browsers/chrome.png', //Chrome Mobile + 'cr' => __DIR__.'/browsers/chromium.png', + 'ff' => __DIR__.'/browsers/firefox.png', + 'sf' => __DIR__.'/browsers/safari.png', + 'mf' => __DIR__.'/browsers/safari.png', + 'ps' => __DIR__.'/browsers/edge.png', + 'oi' => __DIR__.'/browsers/edge.png', + 'om' => __DIR__.'/browsers/opera-mini.png', + 'op' => __DIR__.'/browsers/opera.png', + 'on' => __DIR__.'/browsers/opera.png', /* '36' => '360 Phone Browser', diff --git a/app/config/avatars/credit-cards.php b/app/config/avatars/credit-cards.php index 67829537a1..daa53a9056 100644 --- a/app/config/avatars/credit-cards.php +++ b/app/config/avatars/credit-cards.php @@ -1,20 +1,20 @@ __DIR__ . '/credit-cards/amex.png', - 'argencard' => __DIR__ . '/credit-cards/argencard.png', - 'cabal' => __DIR__ . '/credit-cards/cabal.png', - 'censosud' => __DIR__ . '/credit-cards/consosud.png', - 'diners' => __DIR__ . '/credit-cards/diners.png', - 'discover' => __DIR__ . '/credit-cards/discover.png', - 'elo' => __DIR__ . '/credit-cards/elo.png', - 'hipercard' => __DIR__ . '/credit-cards/hipercard.png', - 'jcb' => __DIR__ . '/credit-cards/jcb.png', - 'mastercard' => __DIR__ . '/credit-cards/mastercard.png', - 'naranja' => __DIR__ . '/credit-cards/naranja.png', - 'targeta-shopping' => __DIR__ . '/credit-cards/tarjeta-shopping.png', - 'union-china-pay' => __DIR__ . '/credit-cards/union-china-pay.png', - 'visa' => __DIR__ . '/credit-cards/visa.png', - 'mir' => __DIR__ . '/credit-cards/mir.png', - 'maestro' => __DIR__ . '/credit-cards/maestro.png', + 'amex' => __DIR__.'/credit-cards/amex.png', + 'argencard' => __DIR__.'/credit-cards/argencard.png', + 'cabal' => __DIR__.'/credit-cards/cabal.png', + 'censosud' => __DIR__.'/credit-cards/consosud.png', + 'diners' => __DIR__.'/credit-cards/diners.png', + 'discover' => __DIR__.'/credit-cards/discover.png', + 'elo' => __DIR__.'/credit-cards/elo.png', + 'hipercard' => __DIR__.'/credit-cards/hipercard.png', + 'jcb' => __DIR__.'/credit-cards/jcb.png', + 'mastercard' => __DIR__.'/credit-cards/mastercard.png', + 'naranja' => __DIR__.'/credit-cards/naranja.png', + 'targeta-shopping' => __DIR__.'/credit-cards/tarjeta-shopping.png', + 'union-china-pay' => __DIR__.'/credit-cards/union-china-pay.png', + 'visa' => __DIR__.'/credit-cards/visa.png', + 'mir' => __DIR__.'/credit-cards/mir.png', + 'maestro' => __DIR__.'/credit-cards/maestro.png', ]; diff --git a/app/config/avatars/flags.php b/app/config/avatars/flags.php index 20f7e3701f..7939e5ccf7 100644 --- a/app/config/avatars/flags.php +++ b/app/config/avatars/flags.php @@ -1,198 +1,198 @@ __DIR__ . '/flags/af.png', - 'ao' => __DIR__ . '/flags/ao.png', - 'al' => __DIR__ . '/flags/al.png', - 'ad' => __DIR__ . '/flags/ad.png', - 'ae' => __DIR__ . '/flags/ae.png', - 'ar' => __DIR__ . '/flags/ar.png', - 'am' => __DIR__ . '/flags/am.png', - 'ag' => __DIR__ . '/flags/ag.png', - 'au' => __DIR__ . '/flags/au.png', - 'at' => __DIR__ . '/flags/at.png', - 'az' => __DIR__ . '/flags/az.png', - 'bi' => __DIR__ . '/flags/bi.png', - 'be' => __DIR__ . '/flags/be.png', - 'bj' => __DIR__ . '/flags/bj.png', - 'bf' => __DIR__ . '/flags/bf.png', - 'bd' => __DIR__ . '/flags/bd.png', - 'bg' => __DIR__ . '/flags/bg.png', - 'bh' => __DIR__ . '/flags/bh.png', - 'bs' => __DIR__ . '/flags/bs.png', - 'ba' => __DIR__ . '/flags/ba.png', - 'by' => __DIR__ . '/flags/by.png', - 'bz' => __DIR__ . '/flags/bz.png', - 'bo' => __DIR__ . '/flags/bo.png', - 'br' => __DIR__ . '/flags/br.png', - 'bb' => __DIR__ . '/flags/bb.png', - 'bn' => __DIR__ . '/flags/bn.png', - 'bt' => __DIR__ . '/flags/bt.png', - 'bw' => __DIR__ . '/flags/bw.png', - 'cf' => __DIR__ . '/flags/cf.png', - 'ca' => __DIR__ . '/flags/ca.png', - 'ch' => __DIR__ . '/flags/ch.png', - 'cl' => __DIR__ . '/flags/cl.png', - 'cn' => __DIR__ . '/flags/cn.png', - 'ci' => __DIR__ . '/flags/ci.png', - 'cm' => __DIR__ . '/flags/cm.png', - 'cd' => __DIR__ . '/flags/cd.png', - 'cg' => __DIR__ . '/flags/cg.png', - 'co' => __DIR__ . '/flags/co.png', - 'km' => __DIR__ . '/flags/km.png', - 'cv' => __DIR__ . '/flags/cv.png', - 'cr' => __DIR__ . '/flags/cr.png', - 'cu' => __DIR__ . '/flags/cu.png', - 'cy' => __DIR__ . '/flags/cy.png', - 'cz' => __DIR__ . '/flags/cz.png', - 'de' => __DIR__ . '/flags/de.png', - 'dj' => __DIR__ . '/flags/dj.png', - 'dm' => __DIR__ . '/flags/dm.png', - 'dk' => __DIR__ . '/flags/dk.png', - 'do' => __DIR__ . '/flags/do.png', - 'dz' => __DIR__ . '/flags/dz.png', - 'ec' => __DIR__ . '/flags/ec.png', - 'eg' => __DIR__ . '/flags/eg.png', - 'er' => __DIR__ . '/flags/er.png', - 'es' => __DIR__ . '/flags/es.png', - 'ee' => __DIR__ . '/flags/ee.png', - 'et' => __DIR__ . '/flags/et.png', - 'fi' => __DIR__ . '/flags/fi.png', - 'fj' => __DIR__ . '/flags/fj.png', - 'fr' => __DIR__ . '/flags/fr.png', - 'fm' => __DIR__ . '/flags/fm.png', - 'ga' => __DIR__ . '/flags/ga.png', - 'gb' => __DIR__ . '/flags/gb.png', - 'ge' => __DIR__ . '/flags/ge.png', - 'gh' => __DIR__ . '/flags/gh.png', - 'gn' => __DIR__ . '/flags/gn.png', - 'gm' => __DIR__ . '/flags/gm.png', - 'gw' => __DIR__ . '/flags/gw.png', - 'gq' => __DIR__ . '/flags/gq.png', - 'gr' => __DIR__ . '/flags/gr.png', - 'gd' => __DIR__ . '/flags/gd.png', - 'gt' => __DIR__ . '/flags/gt.png', - 'gy' => __DIR__ . '/flags/gy.png', - 'hn' => __DIR__ . '/flags/hn.png', - 'hr' => __DIR__ . '/flags/hr.png', - 'ht' => __DIR__ . '/flags/ht.png', - 'hu' => __DIR__ . '/flags/hu.png', - 'id' => __DIR__ . '/flags/id.png', - 'in' => __DIR__ . '/flags/in.png', - 'ie' => __DIR__ . '/flags/ie.png', - 'ir' => __DIR__ . '/flags/ir.png', - 'iq' => __DIR__ . '/flags/iq.png', - 'is' => __DIR__ . '/flags/is.png', - 'il' => __DIR__ . '/flags/il.png', - 'it' => __DIR__ . '/flags/it.png', - 'jm' => __DIR__ . '/flags/jm.png', - 'jo' => __DIR__ . '/flags/jo.png', - 'jp' => __DIR__ . '/flags/jp.png', - 'kz' => __DIR__ . '/flags/kz.png', - 'ke' => __DIR__ . '/flags/ke.png', - 'kg' => __DIR__ . '/flags/kg.png', - 'kh' => __DIR__ . '/flags/kh.png', - 'ki' => __DIR__ . '/flags/ki.png', - 'kn' => __DIR__ . '/flags/kn.png', - 'kr' => __DIR__ . '/flags/kr.png', - 'kw' => __DIR__ . '/flags/kw.png', - 'la' => __DIR__ . '/flags/la.png', - 'lb' => __DIR__ . '/flags/lb.png', - 'lr' => __DIR__ . '/flags/lr.png', - 'ly' => __DIR__ . '/flags/ly.png', - 'lc' => __DIR__ . '/flags/lc.png', - 'li' => __DIR__ . '/flags/li.png', - 'lk' => __DIR__ . '/flags/lk.png', - 'ls' => __DIR__ . '/flags/ls.png', - 'lt' => __DIR__ . '/flags/ls.png', - 'lu' => __DIR__ . '/flags/lu.png', - 'lv' => __DIR__ . '/flags/lv.png', - 'ma' => __DIR__ . '/flags/ma.png', - 'mc' => __DIR__ . '/flags/mc.png', - 'md' => __DIR__ . '/flags/md.png', - 'mg' => __DIR__ . '/flags/mg.png', - 'mv' => __DIR__ . '/flags/mv.png', - 'mx' => __DIR__ . '/flags/mx.png', - 'mh' => __DIR__ . '/flags/mh.png', - 'mk' => __DIR__ . '/flags/mk.png', - 'ml' => __DIR__ . '/flags/ml.png', - 'mt' => __DIR__ . '/flags/mt.png', - 'mm' => __DIR__ . '/flags/mm.png', - 'me' => __DIR__ . '/flags/me.png', - 'mn' => __DIR__ . '/flags/mn.png', - 'mz' => __DIR__ . '/flags/mz.png', - 'mr' => __DIR__ . '/flags/mr.png', - 'mu' => __DIR__ . '/flags/mu.png', - 'mw' => __DIR__ . '/flags/mw.png', - 'my' => __DIR__ . '/flags/my.png', - 'na' => __DIR__ . '/flags/na.png', - 'ne' => __DIR__ . '/flags/ne.png', - 'ng' => __DIR__ . '/flags/ng.png', - 'ni' => __DIR__ . '/flags/ni.png', - 'nl' => __DIR__ . '/flags/nl.png', - 'no' => __DIR__ . '/flags/no.png', - 'np' => __DIR__ . '/flags/np.png', - 'nr' => __DIR__ . '/flags/nr.png', - 'nz' => __DIR__ . '/flags/nz.png', - 'om' => __DIR__ . '/flags/om.png', - 'pk' => __DIR__ . '/flags/pk.png', - 'pa' => __DIR__ . '/flags/pa.png', - 'pe' => __DIR__ . '/flags/pe.png', - 'ph' => __DIR__ . '/flags/ph.png', - 'pw' => __DIR__ . '/flags/pw.png', - 'pg' => __DIR__ . '/flags/pg.png', - 'pl' => __DIR__ . '/flags/pl.png', - 'kp' => __DIR__ . '/flags/kp.png', - 'pt' => __DIR__ . '/flags/pt.png', - 'py' => __DIR__ . '/flags/py.png', - 'qa' => __DIR__ . '/flags/qa.png', - 'ro' => __DIR__ . '/flags/ro.png', - 'ru' => __DIR__ . '/flags/ru.png', - 'rw' => __DIR__ . '/flags/rw.png', - 'sa' => __DIR__ . '/flags/sa.png', - 'sd' => __DIR__ . '/flags/sd.png', - 'sn' => __DIR__ . '/flags/sn.png', - 'sg' => __DIR__ . '/flags/sg.png', - 'sb' => __DIR__ . '/flags/sb.png', - 'sl' => __DIR__ . '/flags/sl.png', - 'sv' => __DIR__ . '/flags/sv.png', - 'sm' => __DIR__ . '/flags/sm.png', - 'so' => __DIR__ . '/flags/so.png', - 'rs' => __DIR__ . '/flags/rs.png', - 'ss' => __DIR__ . '/flags/ss.png', - 'st' => __DIR__ . '/flags/st.png', - 'sr' => __DIR__ . '/flags/sr.png', - 'sk' => __DIR__ . '/flags/sk.png', - 'si' => __DIR__ . '/flags/si.png', - 'se' => __DIR__ . '/flags/se.png', - 'sz' => __DIR__ . '/flags/sz.png', - 'sc' => __DIR__ . '/flags/sc.png', - 'sy' => __DIR__ . '/flags/sy.png', - 'td' => __DIR__ . '/flags/td.png', - 'tg' => __DIR__ . '/flags/tg.png', - 'th' => __DIR__ . '/flags/th.png', - 'tj' => __DIR__ . '/flags/tj.png', - 'tm' => __DIR__ . '/flags/tm.png', - 'tl' => __DIR__ . '/flags/tl.png', - 'to' => __DIR__ . '/flags/to.png', - 'tt' => __DIR__ . '/flags/tt.png', - 'tn' => __DIR__ . '/flags/tn.png', - 'tr' => __DIR__ . '/flags/tr.png', - 'tv' => __DIR__ . '/flags/tv.png', - 'tz' => __DIR__ . '/flags/tz.png', - 'ug' => __DIR__ . '/flags/ug.png', - 'ua' => __DIR__ . '/flags/ua.png', - 'uy' => __DIR__ . '/flags/uy.png', - 'us' => __DIR__ . '/flags/us.png', - 'uz' => __DIR__ . '/flags/uz.png', - 'va' => __DIR__ . '/flags/va.png', - 'vc' => __DIR__ . '/flags/vc.png', - 've' => __DIR__ . '/flags/ve.png', - 'vn' => __DIR__ . '/flags/vn.png', - 'vu' => __DIR__ . '/flags/vu.png', - 'ws' => __DIR__ . '/flags/ws.png', - 'ye' => __DIR__ . '/flags/ye.png', - 'za' => __DIR__ . '/flags/za.png', - 'zm' => __DIR__ . '/flags/zm.png', - 'zw' => __DIR__ . '/flags/zw.png', + 'af' => __DIR__.'/flags/af.png', + 'ao' => __DIR__.'/flags/ao.png', + 'al' => __DIR__.'/flags/al.png', + 'ad' => __DIR__.'/flags/ad.png', + 'ae' => __DIR__.'/flags/ae.png', + 'ar' => __DIR__.'/flags/ar.png', + 'am' => __DIR__.'/flags/am.png', + 'ag' => __DIR__.'/flags/ag.png', + 'au' => __DIR__.'/flags/au.png', + 'at' => __DIR__.'/flags/at.png', + 'az' => __DIR__.'/flags/az.png', + 'bi' => __DIR__.'/flags/bi.png', + 'be' => __DIR__.'/flags/be.png', + 'bj' => __DIR__.'/flags/bj.png', + 'bf' => __DIR__.'/flags/bf.png', + 'bd' => __DIR__.'/flags/bd.png', + 'bg' => __DIR__.'/flags/bg.png', + 'bh' => __DIR__.'/flags/bh.png', + 'bs' => __DIR__.'/flags/bs.png', + 'ba' => __DIR__.'/flags/ba.png', + 'by' => __DIR__.'/flags/by.png', + 'bz' => __DIR__.'/flags/bz.png', + 'bo' => __DIR__.'/flags/bo.png', + 'br' => __DIR__.'/flags/br.png', + 'bb' => __DIR__.'/flags/bb.png', + 'bn' => __DIR__.'/flags/bn.png', + 'bt' => __DIR__.'/flags/bt.png', + 'bw' => __DIR__.'/flags/bw.png', + 'cf' => __DIR__.'/flags/cf.png', + 'ca' => __DIR__.'/flags/ca.png', + 'ch' => __DIR__.'/flags/ch.png', + 'cl' => __DIR__.'/flags/cl.png', + 'cn' => __DIR__.'/flags/cn.png', + 'ci' => __DIR__.'/flags/ci.png', + 'cm' => __DIR__.'/flags/cm.png', + 'cd' => __DIR__.'/flags/cd.png', + 'cg' => __DIR__.'/flags/cg.png', + 'co' => __DIR__.'/flags/co.png', + 'km' => __DIR__.'/flags/km.png', + 'cv' => __DIR__.'/flags/cv.png', + 'cr' => __DIR__.'/flags/cr.png', + 'cu' => __DIR__.'/flags/cu.png', + 'cy' => __DIR__.'/flags/cy.png', + 'cz' => __DIR__.'/flags/cz.png', + 'de' => __DIR__.'/flags/de.png', + 'dj' => __DIR__.'/flags/dj.png', + 'dm' => __DIR__.'/flags/dm.png', + 'dk' => __DIR__.'/flags/dk.png', + 'do' => __DIR__.'/flags/do.png', + 'dz' => __DIR__.'/flags/dz.png', + 'ec' => __DIR__.'/flags/ec.png', + 'eg' => __DIR__.'/flags/eg.png', + 'er' => __DIR__.'/flags/er.png', + 'es' => __DIR__.'/flags/es.png', + 'ee' => __DIR__.'/flags/ee.png', + 'et' => __DIR__.'/flags/et.png', + 'fi' => __DIR__.'/flags/fi.png', + 'fj' => __DIR__.'/flags/fj.png', + 'fr' => __DIR__.'/flags/fr.png', + 'fm' => __DIR__.'/flags/fm.png', + 'ga' => __DIR__.'/flags/ga.png', + 'gb' => __DIR__.'/flags/gb.png', + 'ge' => __DIR__.'/flags/ge.png', + 'gh' => __DIR__.'/flags/gh.png', + 'gn' => __DIR__.'/flags/gn.png', + 'gm' => __DIR__.'/flags/gm.png', + 'gw' => __DIR__.'/flags/gw.png', + 'gq' => __DIR__.'/flags/gq.png', + 'gr' => __DIR__.'/flags/gr.png', + 'gd' => __DIR__.'/flags/gd.png', + 'gt' => __DIR__.'/flags/gt.png', + 'gy' => __DIR__.'/flags/gy.png', + 'hn' => __DIR__.'/flags/hn.png', + 'hr' => __DIR__.'/flags/hr.png', + 'ht' => __DIR__.'/flags/ht.png', + 'hu' => __DIR__.'/flags/hu.png', + 'id' => __DIR__.'/flags/id.png', + 'in' => __DIR__.'/flags/in.png', + 'ie' => __DIR__.'/flags/ie.png', + 'ir' => __DIR__.'/flags/ir.png', + 'iq' => __DIR__.'/flags/iq.png', + 'is' => __DIR__.'/flags/is.png', + 'il' => __DIR__.'/flags/il.png', + 'it' => __DIR__.'/flags/it.png', + 'jm' => __DIR__.'/flags/jm.png', + 'jo' => __DIR__.'/flags/jo.png', + 'jp' => __DIR__.'/flags/jp.png', + 'kz' => __DIR__.'/flags/kz.png', + 'ke' => __DIR__.'/flags/ke.png', + 'kg' => __DIR__.'/flags/kg.png', + 'kh' => __DIR__.'/flags/kh.png', + 'ki' => __DIR__.'/flags/ki.png', + 'kn' => __DIR__.'/flags/kn.png', + 'kr' => __DIR__.'/flags/kr.png', + 'kw' => __DIR__.'/flags/kw.png', + 'la' => __DIR__.'/flags/la.png', + 'lb' => __DIR__.'/flags/lb.png', + 'lr' => __DIR__.'/flags/lr.png', + 'ly' => __DIR__.'/flags/ly.png', + 'lc' => __DIR__.'/flags/lc.png', + 'li' => __DIR__.'/flags/li.png', + 'lk' => __DIR__.'/flags/lk.png', + 'ls' => __DIR__.'/flags/ls.png', + 'lt' => __DIR__.'/flags/ls.png', + 'lu' => __DIR__.'/flags/lu.png', + 'lv' => __DIR__.'/flags/lv.png', + 'ma' => __DIR__.'/flags/ma.png', + 'mc' => __DIR__.'/flags/mc.png', + 'md' => __DIR__.'/flags/md.png', + 'mg' => __DIR__.'/flags/mg.png', + 'mv' => __DIR__.'/flags/mv.png', + 'mx' => __DIR__.'/flags/mx.png', + 'mh' => __DIR__.'/flags/mh.png', + 'mk' => __DIR__.'/flags/mk.png', + 'ml' => __DIR__.'/flags/ml.png', + 'mt' => __DIR__.'/flags/mt.png', + 'mm' => __DIR__.'/flags/mm.png', + 'me' => __DIR__.'/flags/me.png', + 'mn' => __DIR__.'/flags/mn.png', + 'mz' => __DIR__.'/flags/mz.png', + 'mr' => __DIR__.'/flags/mr.png', + 'mu' => __DIR__.'/flags/mu.png', + 'mw' => __DIR__.'/flags/mw.png', + 'my' => __DIR__.'/flags/my.png', + 'na' => __DIR__.'/flags/na.png', + 'ne' => __DIR__.'/flags/ne.png', + 'ng' => __DIR__.'/flags/ng.png', + 'ni' => __DIR__.'/flags/ni.png', + 'nl' => __DIR__.'/flags/nl.png', + 'no' => __DIR__.'/flags/no.png', + 'np' => __DIR__.'/flags/np.png', + 'nr' => __DIR__.'/flags/nr.png', + 'nz' => __DIR__.'/flags/nz.png', + 'om' => __DIR__.'/flags/om.png', + 'pk' => __DIR__.'/flags/pk.png', + 'pa' => __DIR__.'/flags/pa.png', + 'pe' => __DIR__.'/flags/pe.png', + 'ph' => __DIR__.'/flags/ph.png', + 'pw' => __DIR__.'/flags/pw.png', + 'pg' => __DIR__.'/flags/pg.png', + 'pl' => __DIR__.'/flags/pl.png', + 'kp' => __DIR__.'/flags/kp.png', + 'pt' => __DIR__.'/flags/pt.png', + 'py' => __DIR__.'/flags/py.png', + 'qa' => __DIR__.'/flags/qa.png', + 'ro' => __DIR__.'/flags/ro.png', + 'ru' => __DIR__.'/flags/ru.png', + 'rw' => __DIR__.'/flags/rw.png', + 'sa' => __DIR__.'/flags/sa.png', + 'sd' => __DIR__.'/flags/sd.png', + 'sn' => __DIR__.'/flags/sn.png', + 'sg' => __DIR__.'/flags/sg.png', + 'sb' => __DIR__.'/flags/sb.png', + 'sl' => __DIR__.'/flags/sl.png', + 'sv' => __DIR__.'/flags/sv.png', + 'sm' => __DIR__.'/flags/sm.png', + 'so' => __DIR__.'/flags/so.png', + 'rs' => __DIR__.'/flags/rs.png', + 'ss' => __DIR__.'/flags/ss.png', + 'st' => __DIR__.'/flags/st.png', + 'sr' => __DIR__.'/flags/sr.png', + 'sk' => __DIR__.'/flags/sk.png', + 'si' => __DIR__.'/flags/si.png', + 'se' => __DIR__.'/flags/se.png', + 'sz' => __DIR__.'/flags/sz.png', + 'sc' => __DIR__.'/flags/sc.png', + 'sy' => __DIR__.'/flags/sy.png', + 'td' => __DIR__.'/flags/td.png', + 'tg' => __DIR__.'/flags/tg.png', + 'th' => __DIR__.'/flags/th.png', + 'tj' => __DIR__.'/flags/tj.png', + 'tm' => __DIR__.'/flags/tm.png', + 'tl' => __DIR__.'/flags/tl.png', + 'to' => __DIR__.'/flags/to.png', + 'tt' => __DIR__.'/flags/tt.png', + 'tn' => __DIR__.'/flags/tn.png', + 'tr' => __DIR__.'/flags/tr.png', + 'tv' => __DIR__.'/flags/tv.png', + 'tz' => __DIR__.'/flags/tz.png', + 'ug' => __DIR__.'/flags/ug.png', + 'ua' => __DIR__.'/flags/ua.png', + 'uy' => __DIR__.'/flags/uy.png', + 'us' => __DIR__.'/flags/us.png', + 'uz' => __DIR__.'/flags/uz.png', + 'va' => __DIR__.'/flags/va.png', + 'vc' => __DIR__.'/flags/vc.png', + 've' => __DIR__.'/flags/ve.png', + 'vn' => __DIR__.'/flags/vn.png', + 'vu' => __DIR__.'/flags/vu.png', + 'ws' => __DIR__.'/flags/ws.png', + 'ye' => __DIR__.'/flags/ye.png', + 'za' => __DIR__.'/flags/za.png', + 'zm' => __DIR__.'/flags/zm.png', + 'zw' => __DIR__.'/flags/zw.png', ]; diff --git a/app/config/avatars/os.php b/app/config/avatars/os.php index f500eed759..ba5ee0e1fc 100644 --- a/app/config/avatars/os.php +++ b/app/config/avatars/os.php @@ -2,9 +2,9 @@ return [ // Codes based on: https://github.com/matomo-org/device-detector/blob/master/Parser/Client/Browser.php - 'AND' => __DIR__ . '/os/android.png', - 'ATV' => __DIR__ . '/os/apple-tv.png', - 'COS' => __DIR__ . '/os/chrome-os.png', + 'AND' => __DIR__.'/os/android.png', + 'ATV' => __DIR__.'/os/apple-tv.png', + 'COS' => __DIR__.'/os/chrome-os.png', /* 'AIX' => 'AIX', diff --git a/app/config/collections.php b/app/config/collections.php index c2daf999d6..fa2e4c07d7 100644 --- a/app/config/collections.php +++ b/app/config/collections.php @@ -16,7 +16,6 @@ $auth = Config::getParam('auth', []); * attributes => list of attributes * indexes => list of indexes */ - $collections = [ 'databases' => [ '$collection' => ID::custom(Database::METADATA), @@ -839,7 +838,7 @@ $collections = [ 'default' => null, 'array' => false, 'filters' => [], - ] + ], ], 'indexes' => [ [ @@ -946,16 +945,16 @@ $collections = [ 'filters' => [], ], [ - '$id' => ID::custom('registered'), - 'type' => Database::VAR_BOOLEAN, - 'format' => '', - 'size' => 0, - 'signed' => true, - 'required' => false, - 'default' => null, - 'array' => false, - 'filters' => [], - ], + '$id' => ID::custom('registered'), + 'type' => Database::VAR_BOOLEAN, + 'format' => '', + 'size' => 0, + 'signed' => true, + 'required' => false, + 'default' => null, + 'array' => false, + 'filters' => [], + ], ], 'indexes' => [ @@ -1193,7 +1192,7 @@ $collections = [ 'attributes' => ['projectInternalId'], 'lengths' => [Database::LENGTH_KEY], 'orders' => [Database::ORDER_ASC], - ] + ], ], ], @@ -1388,7 +1387,7 @@ $collections = [ 'default' => null, 'array' => false, 'filters' => [], - ] + ], ], 'indexes' => [ [ @@ -1453,7 +1452,7 @@ $collections = [ 'attributes' => ['search'], 'lengths' => [], 'orders' => [], - ] + ], ], ], @@ -1538,7 +1537,7 @@ $collections = [ 'default' => null, 'array' => false, 'filters' => [], - ] + ], ], 'indexes' => [ [ @@ -2415,7 +2414,7 @@ $collections = [ 'default' => false, 'array' => false, 'filters' => [], - ] + ], ], 'indexes' => [ [ @@ -2595,7 +2594,7 @@ $collections = [ 'default' => '', 'array' => false, 'filters' => [], - ] + ], ], 'indexes' => [ [ @@ -2604,7 +2603,7 @@ $collections = [ 'attributes' => ['deploymentId'], 'lengths' => [Database::LENGTH_KEY], 'orders' => [Database::ORDER_ASC], - ] + ], ], ], @@ -3010,7 +3009,7 @@ $collections = [ 'lengths' => [], 'orders' => [Database::ORDER_ASC], ], - ] + ], ], 'stats' => [ @@ -3147,7 +3146,7 @@ $collections = [ 'default' => null, 'array' => false, 'filters' => [], //TODO: use json filter - ] + ], ], 'indexes' => [ [ @@ -3157,7 +3156,7 @@ $collections = [ 'lengths' => [], 'orders' => [Database::ORDER_DESC], ], - ] + ], ], 'cache' => [ '$collection' => Database::METADATA, @@ -3197,7 +3196,7 @@ $collections = [ 'array' => false, 'filters' => [], ], - ], + ], 'indexes' => [ [ '$id' => '_key_accessedAt', @@ -3465,7 +3464,7 @@ $collections = [ 'lengths' => [], 'orders' => [Database::ORDER_ASC], ], - ] + ], ], 'variables' => [ @@ -3515,7 +3514,7 @@ $collections = [ 'required' => true, 'default' => null, 'array' => false, - 'filters' => [ 'encrypt' ] + 'filters' => ['encrypt'], ], [ '$id' => ID::custom('search'), diff --git a/app/config/errors.php b/app/config/errors.php index 0c1524772d..e58f92f33f 100644 --- a/app/config/errors.php +++ b/app/config/errors.php @@ -239,7 +239,7 @@ return [ Exception::AVATAR_SET_NOT_FOUND => [ 'name' => Exception::AVATAR_SET_NOT_FOUND, 'description' => 'The requested avatar set could not be found.', - 'code' => 404 + 'code' => 404, ], Exception::AVATAR_NOT_FOUND => [ 'name' => Exception::AVATAR_NOT_FOUND, @@ -361,13 +361,13 @@ return [ Exception::DATABASE_NOT_FOUND => [ 'name' => Exception::DATABASE_NOT_FOUND, 'description' => 'Database not found', - 'code' => 404 + 'code' => 404, ], Exception::DATABASE_ALREADY_EXISTS => [ 'name' => Exception::DATABASE_ALREADY_EXISTS, 'description' => 'Database already exists', - 'code' => 409 + 'code' => 409, ], /** Collections */ diff --git a/app/config/events.php b/app/config/events.php index 6fe030d4bf..aab75afd32 100644 --- a/app/config/events.php +++ b/app/config/events.php @@ -19,7 +19,7 @@ return [ '$description' => 'This event triggers when a session for a user is created.', ], 'delete' => [ - '$description' => 'This event triggers when a session for a user is deleted.' + '$description' => 'This event triggers when a session for a user is deleted.', ], ], 'recovery' => [ @@ -30,7 +30,7 @@ return [ '$description' => 'This event triggers when a recovery token for a user is created.', ], 'update' => [ - '$description' => 'This event triggers when a recovery token for a user is validated.' + '$description' => 'This event triggers when a recovery token for a user is validated.', ], ], 'verification' => [ @@ -41,11 +41,11 @@ return [ '$description' => 'This event triggers when a verification token for a user is created.', ], 'update' => [ - '$description' => 'This event triggers when a verification token for a user is validated.' + '$description' => 'This event triggers when a verification token for a user is validated.', ], ], 'create' => [ - '$description' => 'This event triggers when a user is created.' + '$description' => 'This event triggers when a user is created.', ], 'delete' => [ '$description' => 'This event triggers when a user is deleted.', @@ -67,7 +67,7 @@ return [ 'prefs' => [ '$description' => 'This event triggers when a user\'s preferences is updated.', ], - ] + ], ], 'databases' => [ '$model' => Response::MODEL_DATABASE, @@ -85,10 +85,10 @@ return [ '$description' => 'This event triggers when a document is created.', ], 'delete' => [ - '$description' => 'This event triggers when a document is deleted.' + '$description' => 'This event triggers when a document is deleted.', ], 'update' => [ - '$description' => 'This event triggers when a document is updated.' + '$description' => 'This event triggers when a document is updated.', ], ], 'indexes' => [ @@ -99,8 +99,8 @@ return [ '$description' => 'This event triggers when an index is created.', ], 'delete' => [ - '$description' => 'This event triggers when an index is deleted.' - ] + '$description' => 'This event triggers when an index is deleted.', + ], ], 'attributes' => [ '$model' => Response::MODEL_ATTRIBUTE, @@ -110,28 +110,28 @@ return [ '$description' => 'This event triggers when an attribute is created.', ], 'delete' => [ - '$description' => 'This event triggers when an attribute is deleted.' - ] + '$description' => 'This event triggers when an attribute is deleted.', + ], ], 'create' => [ - '$description' => 'This event triggers when a collection is created.' + '$description' => 'This event triggers when a collection is created.', ], 'delete' => [ '$description' => 'This event triggers when a collection is deleted.', ], 'update' => [ '$description' => 'This event triggers when a collection is updated.', - ] + ], ], 'create' => [ - '$description' => 'This event triggers when a database is created.' + '$description' => 'This event triggers when a database is created.', ], 'delete' => [ '$description' => 'This event triggers when a database is deleted.', ], 'update' => [ '$description' => 'This event triggers when a database is updated.', - ] + ], ], 'buckets' => [ '$model' => Response::MODEL_BUCKET, @@ -145,21 +145,21 @@ return [ '$description' => 'This event triggers when a file is created.', ], 'delete' => [ - '$description' => 'This event triggers when a file is deleted.' + '$description' => 'This event triggers when a file is deleted.', ], 'update' => [ - '$description' => 'This event triggers when a file is updated.' + '$description' => 'This event triggers when a file is updated.', ], ], 'create' => [ - '$description' => 'This event triggers when a bucket is created.' + '$description' => 'This event triggers when a bucket is created.', ], 'delete' => [ '$description' => 'This event triggers when a bucket is deleted.', ], 'update' => [ '$description' => 'This event triggers when a bucket is updated.', - ] + ], ], 'teams' => [ '$model' => Response::MODEL_TEAM, @@ -173,24 +173,24 @@ return [ '$description' => 'This event triggers when a membership is created.', ], 'delete' => [ - '$description' => 'This event triggers when a membership is deleted.' + '$description' => 'This event triggers when a membership is deleted.', ], 'update' => [ '$description' => 'This event triggers when a membership is updated.', 'status' => [ - '$description' => 'This event triggers when a team memberships status is updated.' - ] + '$description' => 'This event triggers when a team memberships status is updated.', + ], ], ], 'create' => [ - '$description' => 'This event triggers when a bucket is created.' + '$description' => 'This event triggers when a bucket is created.', ], 'delete' => [ '$description' => 'This event triggers when a bucket is deleted.', ], 'update' => [ '$description' => 'This event triggers when a bucket is updated.', - ] + ], ], 'functions' => [ '$model' => Response::MODEL_FUNCTION, @@ -204,10 +204,10 @@ return [ '$description' => 'This event triggers when a deployment is created.', ], 'delete' => [ - '$description' => 'This event triggers when a deployment is deleted.' + '$description' => 'This event triggers when a deployment is deleted.', ], 'update' => [ - '$description' => 'This event triggers when a deployment is updated.' + '$description' => 'This event triggers when a deployment is updated.', ], ], 'executions' => [ @@ -218,20 +218,20 @@ return [ '$description' => 'This event triggers when an execution is created.', ], 'delete' => [ - '$description' => 'This event triggers when an execution is deleted.' + '$description' => 'This event triggers when an execution is deleted.', ], 'update' => [ - '$description' => 'This event triggers when an execution is updated.' + '$description' => 'This event triggers when an execution is updated.', ], ], 'create' => [ - '$description' => 'This event triggers when a function is created.' + '$description' => 'This event triggers when a function is created.', ], 'delete' => [ '$description' => 'This event triggers when a function is deleted.', ], 'update' => [ '$description' => 'This event triggers when a function is updated.', - ] - ] + ], + ], ]; diff --git a/app/config/locale/languages.php b/app/config/locale/languages.php index 6272bd02a6..318ec27492 100644 --- a/app/config/locale/languages.php +++ b/app/config/locale/languages.php @@ -9,923 +9,923 @@ return [ [ - "code" => "aa", - "name" => "Afar", - "nativeName" => "Afar" + 'code' => 'aa', + 'name' => 'Afar', + 'nativeName' => 'Afar', ], [ - "code" => "ab", - "name" => "Abkhazian", - "nativeName" => "Аҧсуа" + 'code' => 'ab', + 'name' => 'Abkhazian', + 'nativeName' => 'Аҧсуа', ], [ - "code" => "af", - "name" => "Afrikaans", - "nativeName" => "Afrikaans" + 'code' => 'af', + 'name' => 'Afrikaans', + 'nativeName' => 'Afrikaans', ], [ - "code" => "ak", - "name" => "Akan", - "nativeName" => "Akana" + 'code' => 'ak', + 'name' => 'Akan', + 'nativeName' => 'Akana', ], [ - "code" => "am", - "name" => "Amharic", - "nativeName" => "አማርኛ" + 'code' => 'am', + 'name' => 'Amharic', + 'nativeName' => 'አማርኛ', ], [ - "code" => "an", - "name" => "Aragonese", - "nativeName" => "Aragonés" + 'code' => 'an', + 'name' => 'Aragonese', + 'nativeName' => 'Aragonés', ], [ - "code" => "ar", - "name" => "Arabic", - "nativeName" => "العربية" + 'code' => 'ar', + 'name' => 'Arabic', + 'nativeName' => 'العربية', ], [ - "code" => "as", - "name" => "Assamese", - "nativeName" => "অসমীয়া" + 'code' => 'as', + 'name' => 'Assamese', + 'nativeName' => 'অসমীয়া', ], [ - "code" => "av", - "name" => "Avar", - "nativeName" => "Авар" + 'code' => 'av', + 'name' => 'Avar', + 'nativeName' => 'Авар', ], [ - "code" => "ay", - "name" => "Aymara", - "nativeName" => "Aymar" + 'code' => 'ay', + 'name' => 'Aymara', + 'nativeName' => 'Aymar', ], [ - "code" => "az", - "name" => "Azerbaijani", - "nativeName" => "Azərbaycanca / آذربايجان" + 'code' => 'az', + 'name' => 'Azerbaijani', + 'nativeName' => 'Azərbaycanca / آذربايجان', ], [ - "code" => "ba", - "name" => "Bashkir", - "nativeName" => "Башҡорт" + 'code' => 'ba', + 'name' => 'Bashkir', + 'nativeName' => 'Башҡорт', ], [ - "code" => "be", - "name" => "Belarusian", - "nativeName" => "Беларуская" + 'code' => 'be', + 'name' => 'Belarusian', + 'nativeName' => 'Беларуская', ], [ - "code" => "bg", - "name" => "Bulgarian", - "nativeName" => "Български" + 'code' => 'bg', + 'name' => 'Bulgarian', + 'nativeName' => 'Български', ], [ - "code" => "bh", - "name" => "Bihari", - "nativeName" => "भोजपुरी" + 'code' => 'bh', + 'name' => 'Bihari', + 'nativeName' => 'भोजपुरी', ], [ - "code" => "bi", - "name" => "Bislama", - "nativeName" => "Bislama" + 'code' => 'bi', + 'name' => 'Bislama', + 'nativeName' => 'Bislama', ], [ - "code" => "bm", - "name" => "Bambara", - "nativeName" => "Bamanankan" + 'code' => 'bm', + 'name' => 'Bambara', + 'nativeName' => 'Bamanankan', ], [ - "code" => "bn", - "name" => "Bengali", - "nativeName" => "বাংলা" + 'code' => 'bn', + 'name' => 'Bengali', + 'nativeName' => 'বাংলা', ], [ - "code" => "bo", - "name" => "Tibetan", - "nativeName" => "བོད་ཡིག / Bod skad" + 'code' => 'bo', + 'name' => 'Tibetan', + 'nativeName' => 'བོད་ཡིག / Bod skad', ], [ - "code" => "br", - "name" => "Breton", - "nativeName" => "Brezhoneg" + 'code' => 'br', + 'name' => 'Breton', + 'nativeName' => 'Brezhoneg', ], [ - "code" => "bs", - "name" => "Bosnian", - "nativeName" => "Bosanski" + 'code' => 'bs', + 'name' => 'Bosnian', + 'nativeName' => 'Bosanski', ], [ - "code" => "ca", - "name" => "Catalan", - "nativeName" => "Català" + 'code' => 'ca', + 'name' => 'Catalan', + 'nativeName' => 'Català', ], [ - "code" => "ce", - "name" => "Chechen", - "nativeName" => "Нохчийн" + 'code' => 'ce', + 'name' => 'Chechen', + 'nativeName' => 'Нохчийн', ], [ - "code" => "ch", - "name" => "Chamorro", - "nativeName" => "Chamoru" + 'code' => 'ch', + 'name' => 'Chamorro', + 'nativeName' => 'Chamoru', ], [ - "code" => "co", - "name" => "Corsican", - "nativeName" => "Corsu" + 'code' => 'co', + 'name' => 'Corsican', + 'nativeName' => 'Corsu', ], [ - "code" => "cr", - "name" => "Cree", - "nativeName" => "Nehiyaw" + 'code' => 'cr', + 'name' => 'Cree', + 'nativeName' => 'Nehiyaw', ], [ - "code" => "cs", - "name" => "Czech", - "nativeName" => "Česky" + 'code' => 'cs', + 'name' => 'Czech', + 'nativeName' => 'Česky', ], [ - "code" => "cu", - "name" => "Old Church Slavonic / Old Bulgarian", - "nativeName" => "словѣньскъ / slověnĭskŭ" + 'code' => 'cu', + 'name' => 'Old Church Slavonic / Old Bulgarian', + 'nativeName' => 'словѣньскъ / slověnĭskŭ', ], [ - "code" => "cv", - "name" => "Chuvash", - "nativeName" => "Чăваш" + 'code' => 'cv', + 'name' => 'Chuvash', + 'nativeName' => 'Чăваш', ], [ - "code" => "cy", - "name" => "Welsh", - "nativeName" => "Cymraeg" + 'code' => 'cy', + 'name' => 'Welsh', + 'nativeName' => 'Cymraeg', ], [ - "code" => "da", - "name" => "Danish", - "nativeName" => "Dansk" + 'code' => 'da', + 'name' => 'Danish', + 'nativeName' => 'Dansk', ], [ - "code" => "de", - "name" => "German", - "nativeName" => "Deutsch" + 'code' => 'de', + 'name' => 'German', + 'nativeName' => 'Deutsch', ], [ - "code" => "dv", - "name" => "Divehi", - "nativeName" => "ދިވެހިބަސް" + 'code' => 'dv', + 'name' => 'Divehi', + 'nativeName' => 'ދިވެހިބަސް', ], [ - "code" => "dz", - "name" => "Dzongkha", - "nativeName" => "ཇོང་ཁ" + 'code' => 'dz', + 'name' => 'Dzongkha', + 'nativeName' => 'ཇོང་ཁ', ], [ - "code" => "ee", - "name" => "Ewe", - "nativeName" => "Ɛʋɛ" + 'code' => 'ee', + 'name' => 'Ewe', + 'nativeName' => 'Ɛʋɛ', ], [ - "code" => "el", - "name" => "Greek", - "nativeName" => "Ελληνικά" + 'code' => 'el', + 'name' => 'Greek', + 'nativeName' => 'Ελληνικά', ], [ - "code" => "en", - "name" => "English", - "nativeName" => "English" + 'code' => 'en', + 'name' => 'English', + 'nativeName' => 'English', ], [ - "code" => "eo", - "name" => "Esperanto", - "nativeName" => "Esperanto" + 'code' => 'eo', + 'name' => 'Esperanto', + 'nativeName' => 'Esperanto', ], [ - "code" => "es", - "name" => "Spanish", - "nativeName" => "Español" + 'code' => 'es', + 'name' => 'Spanish', + 'nativeName' => 'Español', ], [ - "code" => "et", - "name" => "Estonian", - "nativeName" => "Eesti" + 'code' => 'et', + 'name' => 'Estonian', + 'nativeName' => 'Eesti', ], [ - "code" => "eu", - "name" => "Basque", - "nativeName" => "Euskara" + 'code' => 'eu', + 'name' => 'Basque', + 'nativeName' => 'Euskara', ], [ - "code" => "fa", - "name" => "Persian", - "nativeName" => "فارسی" + 'code' => 'fa', + 'name' => 'Persian', + 'nativeName' => 'فارسی', ], [ - "code" => "ff", - "name" => "Peul", - "nativeName" => "Fulfulde" + 'code' => 'ff', + 'name' => 'Peul', + 'nativeName' => 'Fulfulde', ], [ - "code" => "fi", - "name" => "Finnish", - "nativeName" => "Suomi" + 'code' => 'fi', + 'name' => 'Finnish', + 'nativeName' => 'Suomi', ], [ - "code" => "fj", - "name" => "Fijian", - "nativeName" => "Na Vosa Vakaviti" + 'code' => 'fj', + 'name' => 'Fijian', + 'nativeName' => 'Na Vosa Vakaviti', ], [ - "code" => "fo", - "name" => "Faroese", - "nativeName" => "Føroyskt" + 'code' => 'fo', + 'name' => 'Faroese', + 'nativeName' => 'Føroyskt', ], [ - "code" => "fr", - "name" => "French", - "nativeName" => "Français" + 'code' => 'fr', + 'name' => 'French', + 'nativeName' => 'Français', ], [ - "code" => "fy", - "name" => "West Frisian", - "nativeName" => "Frysk" + 'code' => 'fy', + 'name' => 'West Frisian', + 'nativeName' => 'Frysk', ], [ - "code" => "ga", - "name" => "Irish", - "nativeName" => "Gaeilge" + 'code' => 'ga', + 'name' => 'Irish', + 'nativeName' => 'Gaeilge', ], [ - "code" => "gd", - "name" => "Scottish Gaelic", - "nativeName" => "Gàidhlig" + 'code' => 'gd', + 'name' => 'Scottish Gaelic', + 'nativeName' => 'Gàidhlig', ], [ - "code" => "gl", - "name" => "Galician", - "nativeName" => "Galego" + 'code' => 'gl', + 'name' => 'Galician', + 'nativeName' => 'Galego', ], [ - "code" => "gn", - "name" => "Guarani", - "nativeName" => "Avañe'ẽ" + 'code' => 'gn', + 'name' => 'Guarani', + 'nativeName' => "Avañe'ẽ", ], [ - "code" => "gu", - "name" => "Gujarati", - "nativeName" => "ગુજરાતી" + 'code' => 'gu', + 'name' => 'Gujarati', + 'nativeName' => 'ગુજરાતી', ], [ - "code" => "gv", - "name" => "Manx", - "nativeName" => "Gaelg" + 'code' => 'gv', + 'name' => 'Manx', + 'nativeName' => 'Gaelg', ], [ - "code" => "ha", - "name" => "Hausa", - "nativeName" => "هَوُسَ" + 'code' => 'ha', + 'name' => 'Hausa', + 'nativeName' => 'هَوُسَ', ], [ - "code" => "he", - "name" => "Hebrew", - "nativeName" => "עברית" + 'code' => 'he', + 'name' => 'Hebrew', + 'nativeName' => 'עברית', ], [ - "code" => "hi", - "name" => "Hindi", - "nativeName" => "हिन्दी / हिंदी " + 'code' => 'hi', + 'name' => 'Hindi', + 'nativeName' => 'हिन्दी / हिंदी ', ], [ - "code" => "ho", - "name" => "Hiri Motu", - "nativeName" => "Hiri Motu" + 'code' => 'ho', + 'name' => 'Hiri Motu', + 'nativeName' => 'Hiri Motu', ], [ - "code" => "hr", - "name" => "Croatian", - "nativeName" => "Hrvatski" + 'code' => 'hr', + 'name' => 'Croatian', + 'nativeName' => 'Hrvatski', ], [ - "code" => "ht", - "name" => "Haitian", - "nativeName" => "Krèyol ayisyen" + 'code' => 'ht', + 'name' => 'Haitian', + 'nativeName' => 'Krèyol ayisyen', ], [ - "code" => "hu", - "name" => "Hungarian", - "nativeName" => "Magyar" + 'code' => 'hu', + 'name' => 'Hungarian', + 'nativeName' => 'Magyar', ], [ - "code" => "hy", - "name" => "Armenian", - "nativeName" => "Հայերեն" + 'code' => 'hy', + 'name' => 'Armenian', + 'nativeName' => 'Հայերեն', ], [ - "code" => "hz", - "name" => "Herero", - "nativeName" => "Otsiherero" + 'code' => 'hz', + 'name' => 'Herero', + 'nativeName' => 'Otsiherero', ], [ - "code" => "ia", - "name" => "Interlingua", - "nativeName" => "Interlingua" + 'code' => 'ia', + 'name' => 'Interlingua', + 'nativeName' => 'Interlingua', ], [ - "code" => "id", - "name" => "Indonesian", - "nativeName" => "Bahasa Indonesia" + 'code' => 'id', + 'name' => 'Indonesian', + 'nativeName' => 'Bahasa Indonesia', ], [ - "code" => "ie", - "name" => "Interlingue", - "nativeName" => "Interlingue" + 'code' => 'ie', + 'name' => 'Interlingue', + 'nativeName' => 'Interlingue', ], [ - "code" => "ig", - "name" => "Igbo", - "nativeName" => "Igbo" + 'code' => 'ig', + 'name' => 'Igbo', + 'nativeName' => 'Igbo', ], [ - "code" => "ii", - "name" => "Sichuan Yi", - "nativeName" => "ꆇꉙ / 四川彝语" + 'code' => 'ii', + 'name' => 'Sichuan Yi', + 'nativeName' => 'ꆇꉙ / 四川彝语', ], [ - "code" => "ik", - "name" => "Inupiak", - "nativeName" => "Iñupiak" + 'code' => 'ik', + 'name' => 'Inupiak', + 'nativeName' => 'Iñupiak', ], [ - "code" => "io", - "name" => "Ido", - "nativeName" => "Ido" + 'code' => 'io', + 'name' => 'Ido', + 'nativeName' => 'Ido', ], [ - "code" => "is", - "name" => "Icelandic", - "nativeName" => "Íslenska" + 'code' => 'is', + 'name' => 'Icelandic', + 'nativeName' => 'Íslenska', ], [ - "code" => "it", - "name" => "Italian", - "nativeName" => "Italiano" + 'code' => 'it', + 'name' => 'Italian', + 'nativeName' => 'Italiano', ], [ - "code" => "iu", - "name" => "Inuktitut", - "nativeName" => "ᐃᓄᒃᑎᑐᑦ" + 'code' => 'iu', + 'name' => 'Inuktitut', + 'nativeName' => 'ᐃᓄᒃᑎᑐᑦ', ], [ - "code" => "ja", - "name" => "Japanese", - "nativeName" => "日本語" + 'code' => 'ja', + 'name' => 'Japanese', + 'nativeName' => '日本語', ], [ - "code" => "jv", - "name" => "Javanese", - "nativeName" => "Basa Jawa" + 'code' => 'jv', + 'name' => 'Javanese', + 'nativeName' => 'Basa Jawa', ], [ - "code" => "ka", - "name" => "Georgian", - "nativeName" => "ქართული" + 'code' => 'ka', + 'name' => 'Georgian', + 'nativeName' => 'ქართული', ], [ - "code" => "kg", - "name" => "Kongo", - "nativeName" => "KiKongo" + 'code' => 'kg', + 'name' => 'Kongo', + 'nativeName' => 'KiKongo', ], [ - "code" => "ki", - "name" => "Kikuyu", - "nativeName" => "Gĩkũyũ" + 'code' => 'ki', + 'name' => 'Kikuyu', + 'nativeName' => 'Gĩkũyũ', ], [ - "code" => "kj", - "name" => "Kuanyama", - "nativeName" => "Kuanyama" + 'code' => 'kj', + 'name' => 'Kuanyama', + 'nativeName' => 'Kuanyama', ], [ - "code" => "kk", - "name" => "Kazakh", - "nativeName" => "Қазақша" + 'code' => 'kk', + 'name' => 'Kazakh', + 'nativeName' => 'Қазақша', ], [ - "code" => "kl", - "name" => "Greenlandic", - "nativeName" => "Kalaallisut" + 'code' => 'kl', + 'name' => 'Greenlandic', + 'nativeName' => 'Kalaallisut', ], [ - "code" => "km", - "name" => "Khmer", - "nativeName" => "ភាសាខ្មែរ" + 'code' => 'km', + 'name' => 'Khmer', + 'nativeName' => 'ភាសាខ្មែរ', ], [ - "code" => "kn", - "name" => "Kannada", - "nativeName" => "ಕನ್ನಡ" + 'code' => 'kn', + 'name' => 'Kannada', + 'nativeName' => 'ಕನ್ನಡ', ], [ - "code" => "ko", - "name" => "Korean", - "nativeName" => "한국어" + 'code' => 'ko', + 'name' => 'Korean', + 'nativeName' => '한국어', ], [ - "code" => "kr", - "name" => "Kanuri", - "nativeName" => "Kanuri" + 'code' => 'kr', + 'name' => 'Kanuri', + 'nativeName' => 'Kanuri', ], [ - "code" => "ks", - "name" => "Kashmiri", - "nativeName" => "कश्मीरी / كشميري" + 'code' => 'ks', + 'name' => 'Kashmiri', + 'nativeName' => 'कश्मीरी / كشميري', ], [ - "code" => "ku", - "name" => "Kurdish", - "nativeName" => "Kurdî / كوردی" + 'code' => 'ku', + 'name' => 'Kurdish', + 'nativeName' => 'Kurdî / كوردی', ], [ - "code" => "kv", - "name" => "Komi", - "nativeName" => "Коми" + 'code' => 'kv', + 'name' => 'Komi', + 'nativeName' => 'Коми', ], [ - "code" => "kw", - "name" => "Cornish", - "nativeName" => "Kernewek" + 'code' => 'kw', + 'name' => 'Cornish', + 'nativeName' => 'Kernewek', ], [ - "code" => "ky", - "name" => "Kirghiz", - "nativeName" => "Kırgızca / Кыргызча" + 'code' => 'ky', + 'name' => 'Kirghiz', + 'nativeName' => 'Kırgızca / Кыргызча', ], [ - "code" => "la", - "name" => "Latin", - "nativeName" => "Latina" + 'code' => 'la', + 'name' => 'Latin', + 'nativeName' => 'Latina', ], [ - "code" => "lb", - "name" => "Luxembourgish", - "nativeName" => "Lëtzebuergesch" + 'code' => 'lb', + 'name' => 'Luxembourgish', + 'nativeName' => 'Lëtzebuergesch', ], [ - "code" => "lg", - "name" => "Ganda", - "nativeName" => "Luganda" + 'code' => 'lg', + 'name' => 'Ganda', + 'nativeName' => 'Luganda', ], [ - "code" => "li", - "name" => "Limburgian", - "nativeName" => "Limburgs" + 'code' => 'li', + 'name' => 'Limburgian', + 'nativeName' => 'Limburgs', ], [ - "code" => "ln", - "name" => "Lingala", - "nativeName" => "Lingála" + 'code' => 'ln', + 'name' => 'Lingala', + 'nativeName' => 'Lingála', ], [ - "code" => "lo", - "name" => "Laotian", - "nativeName" => "ລາວ / Pha xa lao" + 'code' => 'lo', + 'name' => 'Laotian', + 'nativeName' => 'ລາວ / Pha xa lao', ], [ - "code" => "lt", - "name" => "Lithuanian", - "nativeName" => "Lietuvių" + 'code' => 'lt', + 'name' => 'Lithuanian', + 'nativeName' => 'Lietuvių', ], [ - "code" => "lu", - "name" => "Luba-Katanga", - "nativeName" => "Tshiluba" + 'code' => 'lu', + 'name' => 'Luba-Katanga', + 'nativeName' => 'Tshiluba', ], [ - "code" => "lv", - "name" => "Latvian", - "nativeName" => "Latviešu" + 'code' => 'lv', + 'name' => 'Latvian', + 'nativeName' => 'Latviešu', ], [ - "code" => "mg", - "name" => "Malagasy", - "nativeName" => "Malagasy" + 'code' => 'mg', + 'name' => 'Malagasy', + 'nativeName' => 'Malagasy', ], [ - "code" => "mh", - "name" => "Marshallese", - "nativeName" => "Kajin Majel / Ebon" + 'code' => 'mh', + 'name' => 'Marshallese', + 'nativeName' => 'Kajin Majel / Ebon', ], [ - "code" => "mi", - "name" => "Maori", - "nativeName" => "Māori" + 'code' => 'mi', + 'name' => 'Maori', + 'nativeName' => 'Māori', ], [ - "code" => "mk", - "name" => "Macedonian", - "nativeName" => "Македонски" + 'code' => 'mk', + 'name' => 'Macedonian', + 'nativeName' => 'Македонски', ], [ - "code" => "ml", - "name" => "Malayalam", - "nativeName" => "മലയാളം" + 'code' => 'ml', + 'name' => 'Malayalam', + 'nativeName' => 'മലയാളം', ], [ - "code" => "mn", - "name" => "Mongolian", - "nativeName" => "Монгол" + 'code' => 'mn', + 'name' => 'Mongolian', + 'nativeName' => 'Монгол', ], [ - "code" => "mo", - "name" => "Moldovan", - "nativeName" => "Moldovenească" + 'code' => 'mo', + 'name' => 'Moldovan', + 'nativeName' => 'Moldovenească', ], [ - "code" => "mr", - "name" => "Marathi", - "nativeName" => "मराठी" + 'code' => 'mr', + 'name' => 'Marathi', + 'nativeName' => 'मराठी', ], [ - "code" => "ms", - "name" => "Malay", - "nativeName" => "Bahasa Melayu" + 'code' => 'ms', + 'name' => 'Malay', + 'nativeName' => 'Bahasa Melayu', ], [ - "code" => "mt", - "name" => "Maltese", - "nativeName" => "bil-Malti" + 'code' => 'mt', + 'name' => 'Maltese', + 'nativeName' => 'bil-Malti', ], [ - "code" => "my", - "name" => "Burmese", - "nativeName" => "မြန်မာစာ" + 'code' => 'my', + 'name' => 'Burmese', + 'nativeName' => 'မြန်မာစာ', ], [ - "code" => "na", - "name" => "Nauruan", - "nativeName" => "Dorerin Naoero" + 'code' => 'na', + 'name' => 'Nauruan', + 'nativeName' => 'Dorerin Naoero', ], [ - "code" => "nb", - "name" => "Norwegian Bokmål", - "nativeName" => "Norsk bokmål" + 'code' => 'nb', + 'name' => 'Norwegian Bokmål', + 'nativeName' => 'Norsk bokmål', ], [ - "code" => "nd", - "name" => "North Ndebele", - "nativeName" => "Sindebele" + 'code' => 'nd', + 'name' => 'North Ndebele', + 'nativeName' => 'Sindebele', ], [ - "code" => "ne", - "name" => "Nepali", - "nativeName" => "नेपाली" + 'code' => 'ne', + 'name' => 'Nepali', + 'nativeName' => 'नेपाली', ], [ - "code" => "ng", - "name" => "Ndonga", - "nativeName" => "Oshiwambo" + 'code' => 'ng', + 'name' => 'Ndonga', + 'nativeName' => 'Oshiwambo', ], [ - "code" => "nl", - "name" => "Dutch", - "nativeName" => "Nederlands" + 'code' => 'nl', + 'name' => 'Dutch', + 'nativeName' => 'Nederlands', ], [ - "code" => "nn", - "name" => "Norwegian Nynorsk", - "nativeName" => "Norsk nynorsk" + 'code' => 'nn', + 'name' => 'Norwegian Nynorsk', + 'nativeName' => 'Norsk nynorsk', ], [ - "code" => "nr", - "name" => "South Ndebele", - "nativeName" => "isiNdebele" + 'code' => 'nr', + 'name' => 'South Ndebele', + 'nativeName' => 'isiNdebele', ], [ - "code" => "nv", - "name" => "Navajo", - "nativeName" => "Diné bizaad" + 'code' => 'nv', + 'name' => 'Navajo', + 'nativeName' => 'Diné bizaad', ], [ - "code" => "ny", - "name" => "Chichewa", - "nativeName" => "Chi-Chewa" + 'code' => 'ny', + 'name' => 'Chichewa', + 'nativeName' => 'Chi-Chewa', ], [ - "code" => "oc", - "name" => "Occitan", - "nativeName" => "Occitan" + 'code' => 'oc', + 'name' => 'Occitan', + 'nativeName' => 'Occitan', ], [ - "code" => "oj", - "name" => "Ojibwa", - "nativeName" => "ᐊᓂᔑᓈᐯᒧᐎᓐ / Anishinaabemowin" + 'code' => 'oj', + 'name' => 'Ojibwa', + 'nativeName' => 'ᐊᓂᔑᓈᐯᒧᐎᓐ / Anishinaabemowin', ], [ - "code" => "om", - "name" => "Oromo", - "nativeName" => "Oromoo" + 'code' => 'om', + 'name' => 'Oromo', + 'nativeName' => 'Oromoo', ], [ - "code" => "or", - "name" => "Oriya", - "nativeName" => "ଓଡ଼ିଆ" + 'code' => 'or', + 'name' => 'Oriya', + 'nativeName' => 'ଓଡ଼ିଆ', ], [ - "code" => "os", - "name" => "Ossetian / Ossetic", - "nativeName" => "Иронау" + 'code' => 'os', + 'name' => 'Ossetian / Ossetic', + 'nativeName' => 'Иронау', ], [ - "code" => "pa", - "name" => "Panjabi / Punjabi", - "nativeName" => "ਪੰਜਾਬੀ / पंजाबी / پنجابي" + 'code' => 'pa', + 'name' => 'Panjabi / Punjabi', + 'nativeName' => 'ਪੰਜਾਬੀ / पंजाबी / پنجابي', ], [ - "code" => "pi", - "name" => "Pali", - "nativeName" => "Pāli / पाऴि" + 'code' => 'pi', + 'name' => 'Pali', + 'nativeName' => 'Pāli / पाऴि', ], [ - "code" => "pl", - "name" => "Polish", - "nativeName" => "Polski" + 'code' => 'pl', + 'name' => 'Polish', + 'nativeName' => 'Polski', ], [ - "code" => "ps", - "name" => "Pashto", - "nativeName" => "پښتو" + 'code' => 'ps', + 'name' => 'Pashto', + 'nativeName' => 'پښتو', ], [ - "code" => "pt", - "name" => "Portuguese", - "nativeName" => "Português" + 'code' => 'pt', + 'name' => 'Portuguese', + 'nativeName' => 'Português', ], [ - "code" => "qu", - "name" => "Quechua", - "nativeName" => "Runa Simi" + 'code' => 'qu', + 'name' => 'Quechua', + 'nativeName' => 'Runa Simi', ], [ - "code" => "rm", - "name" => "Raeto Romance", - "nativeName" => "Rumantsch" + 'code' => 'rm', + 'name' => 'Raeto Romance', + 'nativeName' => 'Rumantsch', ], [ - "code" => "rn", - "name" => "Kirundi", - "nativeName" => "Kirundi" + 'code' => 'rn', + 'name' => 'Kirundi', + 'nativeName' => 'Kirundi', ], [ - "code" => "ro", - "name" => "Romanian", - "nativeName" => "Română" + 'code' => 'ro', + 'name' => 'Romanian', + 'nativeName' => 'Română', ], [ - "code" => "ru", - "name" => "Russian", - "nativeName" => "Русский" + 'code' => 'ru', + 'name' => 'Russian', + 'nativeName' => 'Русский', ], [ - "code" => "rw", - "name" => "Rwandi", - "nativeName" => "Kinyarwandi" + 'code' => 'rw', + 'name' => 'Rwandi', + 'nativeName' => 'Kinyarwandi', ], [ - "code" => "sa", - "name" => "Sanskrit", - "nativeName" => "संस्कृतम्" + 'code' => 'sa', + 'name' => 'Sanskrit', + 'nativeName' => 'संस्कृतम्', ], [ - "code" => "sc", - "name" => "Sardinian", - "nativeName" => "Sardu" + 'code' => 'sc', + 'name' => 'Sardinian', + 'nativeName' => 'Sardu', ], [ - "code" => "sd", - "name" => "Sindhi", - "nativeName" => "सिन्धी / सिंधी " + 'code' => 'sd', + 'name' => 'Sindhi', + 'nativeName' => 'सिन्धी / सिंधी ', ], [ - "code" => "se", - "name" => "Northern Sami", - "nativeName" => "Sámegiella" + 'code' => 'se', + 'name' => 'Northern Sami', + 'nativeName' => 'Sámegiella', ], [ - "code" => "sg", - "name" => "Sango", - "nativeName" => "Sängö" + 'code' => 'sg', + 'name' => 'Sango', + 'nativeName' => 'Sängö', ], [ - "code" => "sh", - "name" => "Serbo-Croatian", - "nativeName" => "Srpskohrvatski / Српскохрватски" + 'code' => 'sh', + 'name' => 'Serbo-Croatian', + 'nativeName' => 'Srpskohrvatski / Српскохрватски', ], [ - "code" => "si", - "name" => "Sinhalese", - "nativeName" => "සිංහල" + 'code' => 'si', + 'name' => 'Sinhalese', + 'nativeName' => 'සිංහල', ], [ - "code" => "sk", - "name" => "Slovak", - "nativeName" => "Slovenčina" + 'code' => 'sk', + 'name' => 'Slovak', + 'nativeName' => 'Slovenčina', ], [ - "code" => "sl", - "name" => "Slovenian", - "nativeName" => "Slovenščina" + 'code' => 'sl', + 'name' => 'Slovenian', + 'nativeName' => 'Slovenščina', ], [ - "code" => "sm", - "name" => "Samoan", - "nativeName" => "Gagana Samoa" + 'code' => 'sm', + 'name' => 'Samoan', + 'nativeName' => 'Gagana Samoa', ], [ - "code" => "sn", - "name" => "Shona", - "nativeName" => "chiShona" + 'code' => 'sn', + 'name' => 'Shona', + 'nativeName' => 'chiShona', ], [ - "code" => "so", - "name" => "Somalia", - "nativeName" => "Soomaaliga" + 'code' => 'so', + 'name' => 'Somalia', + 'nativeName' => 'Soomaaliga', ], [ - "code" => "sq", - "name" => "Albanian", - "nativeName" => "Shqip" + 'code' => 'sq', + 'name' => 'Albanian', + 'nativeName' => 'Shqip', ], [ - "code" => "sr", - "name" => "Serbian", - "nativeName" => "Српски" + 'code' => 'sr', + 'name' => 'Serbian', + 'nativeName' => 'Српски', ], [ - "code" => "ss", - "name" => "Swati", - "nativeName" => "SiSwati" + 'code' => 'ss', + 'name' => 'Swati', + 'nativeName' => 'SiSwati', ], [ - "code" => "st", - "name" => "Southern Sotho", - "nativeName" => "Sesotho" + 'code' => 'st', + 'name' => 'Southern Sotho', + 'nativeName' => 'Sesotho', ], [ - "code" => "su", - "name" => "Sundanese", - "nativeName" => "Basa Sunda" + 'code' => 'su', + 'name' => 'Sundanese', + 'nativeName' => 'Basa Sunda', ], [ - "code" => "sv", - "name" => "Swedish", - "nativeName" => "Svenska" + 'code' => 'sv', + 'name' => 'Swedish', + 'nativeName' => 'Svenska', ], [ - "code" => "sw", - "name" => "Swahili", - "nativeName" => "Kiswahili" + 'code' => 'sw', + 'name' => 'Swahili', + 'nativeName' => 'Kiswahili', ], [ - "code" => "ta", - "name" => "Tamil", - "nativeName" => "தமிழ்" + 'code' => 'ta', + 'name' => 'Tamil', + 'nativeName' => 'தமிழ்', ], [ - "code" => "te", - "name" => "Telugu", - "nativeName" => "తెలుగు" + 'code' => 'te', + 'name' => 'Telugu', + 'nativeName' => 'తెలుగు', ], [ - "code" => "tg", - "name" => "Tajik", - "nativeName" => "Тоҷикӣ" + 'code' => 'tg', + 'name' => 'Tajik', + 'nativeName' => 'Тоҷикӣ', ], [ - "code" => "th", - "name" => "Thai", - "nativeName" => "ไทย / Phasa Thai" + 'code' => 'th', + 'name' => 'Thai', + 'nativeName' => 'ไทย / Phasa Thai', ], [ - "code" => "ti", - "name" => "Tigrinya", - "nativeName" => "ትግርኛ" + 'code' => 'ti', + 'name' => 'Tigrinya', + 'nativeName' => 'ትግርኛ', ], [ - "code" => "tk", - "name" => "Turkmen", - "nativeName" => "Туркмен / تركمن" + 'code' => 'tk', + 'name' => 'Turkmen', + 'nativeName' => 'Туркмен / تركمن', ], [ - "code" => "tl", - "name" => "Tagalog / Filipino", - "nativeName" => "Tagalog" + 'code' => 'tl', + 'name' => 'Tagalog / Filipino', + 'nativeName' => 'Tagalog', ], [ - "code" => "tn", - "name" => "Tswana", - "nativeName" => "Setswana" + 'code' => 'tn', + 'name' => 'Tswana', + 'nativeName' => 'Setswana', ], [ - "code" => "to", - "name" => "Tonga", - "nativeName" => "Lea Faka-Tonga" + 'code' => 'to', + 'name' => 'Tonga', + 'nativeName' => 'Lea Faka-Tonga', ], [ - "code" => "tr", - "name" => "Turkish", - "nativeName" => "Türkçe" + 'code' => 'tr', + 'name' => 'Turkish', + 'nativeName' => 'Türkçe', ], [ - "code" => "ts", - "name" => "Tsonga", - "nativeName" => "Xitsonga" + 'code' => 'ts', + 'name' => 'Tsonga', + 'nativeName' => 'Xitsonga', ], [ - "code" => "tt", - "name" => "Tatar", - "nativeName" => "Tatarça" + 'code' => 'tt', + 'name' => 'Tatar', + 'nativeName' => 'Tatarça', ], [ - "code" => "tw", - "name" => "Twi", - "nativeName" => "Twi" + 'code' => 'tw', + 'name' => 'Twi', + 'nativeName' => 'Twi', ], [ - "code" => "ty", - "name" => "Tahitian", - "nativeName" => "Reo Mā`ohi" + 'code' => 'ty', + 'name' => 'Tahitian', + 'nativeName' => 'Reo Mā`ohi', ], [ - "code" => "ug", - "name" => "Uyghur", - "nativeName" => "Uyƣurqə / ئۇيغۇرچە" + 'code' => 'ug', + 'name' => 'Uyghur', + 'nativeName' => 'Uyƣurqə / ئۇيغۇرچە', ], [ - "code" => "uk", - "name" => "Ukrainian", - "nativeName" => "Українська" + 'code' => 'uk', + 'name' => 'Ukrainian', + 'nativeName' => 'Українська', ], [ - "code" => "ur", - "name" => "Urdu", - "nativeName" => "اردو" + 'code' => 'ur', + 'name' => 'Urdu', + 'nativeName' => 'اردو', ], [ - "code" => "uz", - "name" => "Uzbek", - "nativeName" => "Ўзбек" + 'code' => 'uz', + 'name' => 'Uzbek', + 'nativeName' => 'Ўзбек', ], [ - "code" => "ve", - "name" => "Venda", - "nativeName" => "Tshivenḓa" + 'code' => 've', + 'name' => 'Venda', + 'nativeName' => 'Tshivenḓa', ], [ - "code" => "vi", - "name" => "Vietnamese", - "nativeName" => "Tiếng Việt" + 'code' => 'vi', + 'name' => 'Vietnamese', + 'nativeName' => 'Tiếng Việt', ], [ - "code" => "vo", - "name" => "Volapük", - "nativeName" => "Volapük" + 'code' => 'vo', + 'name' => 'Volapük', + 'nativeName' => 'Volapük', ], [ - "code" => "wa", - "name" => "Walloon", - "nativeName" => "Walon" + 'code' => 'wa', + 'name' => 'Walloon', + 'nativeName' => 'Walon', ], [ - "code" => "wo", - "name" => "Wolof", - "nativeName" => "Wollof" + 'code' => 'wo', + 'name' => 'Wolof', + 'nativeName' => 'Wollof', ], [ - "code" => "xh", - "name" => "Xhosa", - "nativeName" => "isiXhosa" + 'code' => 'xh', + 'name' => 'Xhosa', + 'nativeName' => 'isiXhosa', ], [ - "code" => "yi", - "name" => "Yiddish", - "nativeName" => "ייִדיש" + 'code' => 'yi', + 'name' => 'Yiddish', + 'nativeName' => 'ייִדיש', ], [ - "code" => "yo", - "name" => "Yoruba", - "nativeName" => "Yorùbá" + 'code' => 'yo', + 'name' => 'Yoruba', + 'nativeName' => 'Yorùbá', ], [ - "code" => "za", - "name" => "Zhuang", - "nativeName" => "Cuengh / Tôô / 壮语" + 'code' => 'za', + 'name' => 'Zhuang', + 'nativeName' => 'Cuengh / Tôô / 壮语', ], [ - "code" => "zh", - "name" => "Chinese", - "nativeName" => "中文" + 'code' => 'zh', + 'name' => 'Chinese', + 'nativeName' => '中文', ], [ - "code" => "zu", - "name" => "Zulu", - "nativeName" => "isiZulu" - ] + 'code' => 'zu', + 'name' => 'Zulu', + 'nativeName' => 'isiZulu', + ], ]; diff --git a/app/config/platforms.php b/app/config/platforms.php index 7f5c2fccd7..8ea08f01d7 100644 --- a/app/config/platforms.php +++ b/app/config/platforms.php @@ -24,7 +24,7 @@ return [ 'hidden' => false, 'family' => APP_PLATFORM_CLIENT, 'prism' => 'javascript', - 'source' => \realpath(__DIR__ . '/../sdks/client-web'), + 'source' => \realpath(__DIR__.'/../sdks/client-web'), 'gitUrl' => 'git@github.com:appwrite/sdk-for-web.git', 'gitRepoName' => 'sdk-for-web', 'gitUserName' => 'appwrite', @@ -58,7 +58,7 @@ return [ 'source' => 'https://github.com/appwrite/todo-with-svelte', 'url' => 'https://appwrite-todo-with-svelte.vercel.app/', ], - ] + ], ], [ 'key' => 'flutter', @@ -72,7 +72,7 @@ return [ 'hidden' => false, 'family' => APP_PLATFORM_CLIENT, 'prism' => 'dart', - 'source' => \realpath(__DIR__ . '/../sdks/client-flutter'), + 'source' => \realpath(__DIR__.'/../sdks/client-flutter'), 'gitUrl' => 'git@github.com:appwrite/sdk-for-flutter.git', 'gitRepoName' => 'sdk-for-flutter', 'gitUserName' => 'appwrite', @@ -90,7 +90,7 @@ return [ 'hidden' => false, 'family' => APP_PLATFORM_CLIENT, 'prism' => 'swift', - 'source' => \realpath(__DIR__ . '/../sdks/client-apple'), + 'source' => \realpath(__DIR__.'/../sdks/client-apple'), 'gitUrl' => 'git@github.com:appwrite/sdk-for-apple.git', 'gitRepoName' => 'sdk-for-apple', 'gitUserName' => 'appwrite', @@ -125,7 +125,7 @@ return [ 'hidden' => false, 'family' => APP_PLATFORM_CLIENT, 'prism' => 'kotlin', - 'source' => \realpath(__DIR__ . '/../sdks/client-android'), + 'source' => \realpath(__DIR__.'/../sdks/client-android'), 'gitUrl' => 'git@github.com:appwrite/sdk-for-android.git', 'gitRepoName' => 'sdk-for-android', 'gitUserName' => 'appwrite', @@ -147,7 +147,7 @@ return [ 'hidden' => true, 'family' => APP_PLATFORM_CLIENT, 'prism' => 'graphql', - 'source' => \realpath(__DIR__ . '/../sdks/client-graphql'), + 'source' => \realpath(__DIR__.'/../sdks/client-graphql'), 'gitUrl' => '', 'gitRepoName' => '', 'gitUserName' => '', @@ -166,7 +166,7 @@ return [ 'hidden' => true, 'family' => APP_PLATFORM_CLIENT, 'prism' => 'http', - 'source' => \realpath(__DIR__ . '/../sdks/client-rest'), + 'source' => \realpath(__DIR__.'/../sdks/client-rest'), 'gitUrl' => '', 'gitRepoName' => '', 'gitUserName' => '', @@ -194,7 +194,7 @@ return [ 'hidden' => true, 'family' => APP_PLATFORM_CONSOLE, 'prism' => 'javascript', - 'source' => \realpath(__DIR__ . '/../sdks/console-web'), + 'source' => \realpath(__DIR__.'/../sdks/console-web'), 'gitUrl' => 'git@github.com:appwrite/sdk-for-console.git', 'gitBranch' => 'main', 'gitRepoName' => 'sdk-for-console', @@ -212,7 +212,7 @@ return [ 'hidden' => false, 'family' => APP_PLATFORM_CONSOLE, 'prism' => 'bash', - 'source' => \realpath(__DIR__ . '/../sdks/console-cli'), + 'source' => \realpath(__DIR__.'/../sdks/console-cli'), 'gitUrl' => 'git@github.com:appwrite/sdk-for-cli.git', 'gitRepoName' => 'sdk-for-cli', 'gitUserName' => 'appwrite', @@ -240,7 +240,7 @@ return [ 'hidden' => false, 'family' => APP_PLATFORM_SERVER, 'prism' => 'javascript', - 'source' => \realpath(__DIR__ . '/../sdks/server-nodejs'), + 'source' => \realpath(__DIR__.'/../sdks/server-nodejs'), 'gitUrl' => 'git@github.com:appwrite/sdk-for-node.git', 'gitRepoName' => 'sdk-for-node', 'gitUserName' => 'appwrite', @@ -258,7 +258,7 @@ return [ 'hidden' => false, 'family' => APP_PLATFORM_SERVER, 'prism' => 'typescript', - 'source' => \realpath(__DIR__ . '/../sdks/server-deno'), + 'source' => \realpath(__DIR__.'/../sdks/server-deno'), 'gitUrl' => 'git@github.com:appwrite/sdk-for-deno.git', 'gitRepoName' => 'sdk-for-deno', 'gitUserName' => 'appwrite', @@ -276,7 +276,7 @@ return [ 'hidden' => false, 'family' => APP_PLATFORM_SERVER, 'prism' => 'php', - 'source' => \realpath(__DIR__ . '/../sdks/server-php'), + 'source' => \realpath(__DIR__.'/../sdks/server-php'), 'gitUrl' => 'git@github.com:appwrite/sdk-for-php.git', 'gitRepoName' => 'sdk-for-php', 'gitUserName' => 'appwrite', @@ -294,7 +294,7 @@ return [ 'hidden' => false, 'family' => APP_PLATFORM_SERVER, 'prism' => 'python', - 'source' => \realpath(__DIR__ . '/../sdks/server-python'), + 'source' => \realpath(__DIR__.'/../sdks/server-python'), 'gitUrl' => 'git@github.com:appwrite/sdk-for-python.git', 'gitRepoName' => 'sdk-for-python', 'gitUserName' => 'appwrite', @@ -312,7 +312,7 @@ return [ 'hidden' => false, 'family' => APP_PLATFORM_SERVER, 'prism' => 'ruby', - 'source' => \realpath(__DIR__ . '/../sdks/server-ruby'), + 'source' => \realpath(__DIR__.'/../sdks/server-ruby'), 'gitUrl' => 'git@github.com:appwrite/sdk-for-ruby.git', 'gitRepoName' => 'sdk-for-ruby', 'gitUserName' => 'appwrite', @@ -330,7 +330,7 @@ return [ 'hidden' => false, 'family' => APP_PLATFORM_SERVER, 'prism' => 'go', - 'source' => \realpath(__DIR__ . '/../sdks/server-go'), + 'source' => \realpath(__DIR__.'/../sdks/server-go'), 'gitUrl' => 'git@github.com:appwrite/sdk-for-go.git', 'gitRepoName' => 'sdk-for-go', 'gitUserName' => 'appwrite', @@ -348,7 +348,7 @@ return [ 'hidden' => false, 'family' => APP_PLATFORM_SERVER, 'prism' => 'java', - 'source' => \realpath(__DIR__ . '/../sdks/server-java'), + 'source' => \realpath(__DIR__.'/../sdks/server-java'), 'gitUrl' => 'git@github.com:appwrite/sdk-for-java.git', 'gitRepoName' => 'sdk-for-java', 'gitUserName' => 'appwrite', @@ -366,7 +366,7 @@ return [ 'hidden' => false, 'family' => APP_PLATFORM_SERVER, 'prism' => 'csharp', - 'source' => \realpath(__DIR__ . '/../sdks/server-dotnet'), + 'source' => \realpath(__DIR__.'/../sdks/server-dotnet'), 'gitUrl' => 'git@github.com:appwrite/sdk-for-dotnet.git', 'gitRepoName' => 'sdk-for-dotnet', 'gitUserName' => 'appwrite', @@ -384,7 +384,7 @@ return [ 'hidden' => false, 'family' => APP_PLATFORM_SERVER, 'prism' => 'dart', - 'source' => \realpath(__DIR__ . '/../sdks/server-dart'), + 'source' => \realpath(__DIR__.'/../sdks/server-dart'), 'gitUrl' => 'git@github.com:appwrite/sdk-for-dart.git', 'gitRepoName' => 'sdk-for-dart', 'gitUserName' => 'appwrite', @@ -402,7 +402,7 @@ return [ 'hidden' => false, 'family' => APP_PLATFORM_SERVER, 'prism' => 'kotlin', - 'source' => \realpath(__DIR__ . '/../sdks/server-kotlin'), + 'source' => \realpath(__DIR__.'/../sdks/server-kotlin'), 'gitUrl' => 'git@github.com:appwrite/sdk-for-kotlin.git', 'gitRepoName' => 'sdk-for-kotlin', 'gitUserName' => 'appwrite', @@ -424,7 +424,7 @@ return [ 'hidden' => false, 'family' => APP_PLATFORM_SERVER, 'prism' => 'swift', - 'source' => \realpath(__DIR__ . '/../sdks/server-swift'), + 'source' => \realpath(__DIR__.'/../sdks/server-swift'), 'gitUrl' => 'git@github.com:appwrite/sdk-for-swift.git', 'gitRepoName' => 'sdk-for-swift', 'gitUserName' => 'appwrite', @@ -442,7 +442,7 @@ return [ 'hidden' => true, 'family' => APP_PLATFORM_SERVER, 'prism' => 'graphql', - 'source' => \realpath(__DIR__ . '/../sdks/server-graphql'), + 'source' => \realpath(__DIR__.'/../sdks/server-graphql'), 'gitUrl' => '', 'gitRepoName' => '', 'gitUserName' => '', @@ -461,7 +461,7 @@ return [ 'hidden' => true, 'family' => APP_PLATFORM_SERVER, 'prism' => 'http', - 'source' => \realpath(__DIR__ . '/../sdks/server-rest'), + 'source' => \realpath(__DIR__.'/../sdks/server-rest'), 'gitUrl' => '', 'gitRepoName' => '', 'gitUserName' => '', diff --git a/app/config/providers.php b/app/config/providers.php index 62430faae1..41b3e8643a 100644 --- a/app/config/providers.php +++ b/app/config/providers.php @@ -69,7 +69,7 @@ return [ // Ordered by ABC. 'sandbox' => false, 'form' => false, 'beta' => false, - 'mock' => false + 'mock' => false, ], 'box' => [ 'name' => 'Box', @@ -79,7 +79,7 @@ return [ // Ordered by ABC. 'sandbox' => false, 'form' => false, 'beta' => false, - 'mock' => false + 'mock' => false, ], 'dailymotion' => [ 'name' => 'Dailymotion', @@ -89,7 +89,7 @@ return [ // Ordered by ABC. 'sandbox' => false, 'form' => false, 'beta' => false, - 'mock' => false + 'mock' => false, ], 'discord' => [ 'name' => 'Discord', @@ -219,7 +219,7 @@ return [ // Ordered by ABC. 'sandbox' => false, 'form' => false, 'beta' => false, - 'mock' => false + 'mock' => false, ], 'paypalSandbox' => [ 'name' => 'PayPal', @@ -229,7 +229,7 @@ return [ // Ordered by ABC. 'sandbox' => true, 'form' => false, 'beta' => false, - 'mock' => false + 'mock' => false, ], 'podio' => [ 'name' => 'Podio', @@ -279,7 +279,7 @@ return [ // Ordered by ABC. 'sandbox' => false, 'form' => false, 'beta' => false, - 'mock' => false + 'mock' => false, ], 'tradeshift' => [ 'name' => 'Tradeshift', @@ -319,7 +319,7 @@ return [ // Ordered by ABC. 'sandbox' => false, 'form' => false, 'beta' => false, - 'mock' => false + 'mock' => false, ], 'yahoo' => [ 'name' => 'Yahoo', diff --git a/app/config/regions.php b/app/config/regions.php index 0dc5fab1ed..cc920bee82 100644 --- a/app/config/regions.php +++ b/app/config/regions.php @@ -5,5 +5,5 @@ return [ 'name' => 'Default', 'default' => true, 'disabled' => false, - ] + ], ]; diff --git a/app/config/runtimes.php b/app/config/runtimes.php index c24aaa109e..d249946d05 100644 --- a/app/config/runtimes.php +++ b/app/config/runtimes.php @@ -4,8 +4,8 @@ * List of Appwrite Cloud Functions supported runtimes */ -use Utopia\App; use Appwrite\Runtimes\Runtimes; +use Utopia\App; $runtimes = new Runtimes('v2'); diff --git a/app/config/scopes.php b/app/config/scopes.php index e058454917..b513ec0951 100644 --- a/app/config/scopes.php +++ b/app/config/scopes.php @@ -37,7 +37,7 @@ return [ // List of publicly visible scopes 'indexes.write' => [ 'description' => 'Access to create, update, and delete your project\'s database collection\'s indexes', ], - 'documents.read' => [ + 'documents.read' => [ 'description' => 'Access to read your project\'s database documents', ], 'documents.write' => [ diff --git a/app/config/services.php b/app/config/services.php index e8bc3372e2..b121182f37 100644 --- a/app/config/services.php +++ b/app/config/services.php @@ -66,8 +66,8 @@ return [ 'optional' => true, 'icon' => '/images/services/databases.png', 'globalAttributes' => [ - 'databaseId' - ] + 'databaseId', + ], ], 'locale' => [ 'key' => 'locale', diff --git a/app/config/variables.php b/app/config/variables.php index 193e167b8f..cd3381dfd4 100644 --- a/app/config/variables.php +++ b/app/config/variables.php @@ -14,7 +14,7 @@ return [ 'default' => 'production', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_LOCALE', @@ -23,7 +23,7 @@ return [ 'default' => 'en', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_OPTIONS_ABUSE', @@ -32,7 +32,7 @@ return [ 'default' => 'enabled', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_OPTIONS_FORCE_HTTPS', @@ -41,7 +41,7 @@ return [ 'default' => 'disabled', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_OPENSSL_KEY_V1', @@ -50,7 +50,7 @@ return [ 'default' => 'your-secret-key', 'required' => true, 'question' => 'Choose a secret API key, make sure to make a backup of your key in a secure location', - 'filter' => 'token' + 'filter' => 'token', ], [ 'name' => '_APP_DOMAIN', @@ -59,7 +59,7 @@ return [ 'default' => 'localhost', 'required' => true, 'question' => 'Enter your Appwrite hostname', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_DOMAIN_TARGET', @@ -67,8 +67,8 @@ return [ 'introduction' => '', 'default' => 'localhost', 'required' => true, - 'question' => 'Enter a DNS A record hostname to serve as a CNAME for your custom domains.' . PHP_EOL . 'You can use the same value as used for the Appwrite hostname.', - 'filter' => 'domainTarget' + 'question' => 'Enter a DNS A record hostname to serve as a CNAME for your custom domains.'.PHP_EOL.'You can use the same value as used for the Appwrite hostname.', + 'filter' => 'domainTarget', ], [ 'name' => '_APP_CONSOLE_WHITELIST_ROOT', @@ -77,7 +77,7 @@ return [ 'default' => 'enabled', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_CONSOLE_WHITELIST_EMAILS', @@ -86,7 +86,7 @@ return [ 'default' => '', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], // [ // 'name' => '_APP_CONSOLE_WHITELIST_DOMAINS', @@ -103,7 +103,7 @@ return [ 'default' => '', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_SYSTEM_EMAIL_NAME', @@ -112,7 +112,7 @@ return [ 'default' => 'Appwrite', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_SYSTEM_EMAIL_ADDRESS', @@ -121,7 +121,7 @@ return [ 'default' => 'team@appwrite.io', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_SYSTEM_RESPONSE_FORMAT', @@ -130,7 +130,7 @@ return [ 'default' => '', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_SYSTEM_SECURITY_EMAIL_ADDRESS', @@ -139,7 +139,7 @@ return [ 'default' => 'certs@appwrite.io', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_USAGE_STATS', @@ -148,7 +148,7 @@ return [ 'default' => 'enabled', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_LOGGING_PROVIDER', @@ -157,7 +157,7 @@ return [ 'default' => '', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_LOGGING_CONFIG', @@ -166,7 +166,7 @@ return [ 'default' => '', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_USAGE_AGGREGATION_INTERVAL', @@ -175,7 +175,7 @@ return [ 'default' => '30', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_USAGE_TIMESERIES_INTERVAL', @@ -184,7 +184,7 @@ return [ 'default' => '30', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_USAGE_DATABASE_INTERVAL', @@ -193,7 +193,7 @@ return [ 'default' => '900', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_WORKER_PER_CORE', @@ -202,8 +202,8 @@ return [ 'default' => 6, 'required' => false, 'question' => '', - 'filter' => '' - ] + 'filter' => '', + ], ], ], [ @@ -217,7 +217,7 @@ return [ 'default' => 'redis', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_REDIS_PORT', @@ -226,7 +226,7 @@ return [ 'default' => '6379', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_REDIS_USER', @@ -235,7 +235,7 @@ return [ 'default' => '', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_REDIS_PASS', @@ -244,7 +244,7 @@ return [ 'default' => '', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], ], ], @@ -259,7 +259,7 @@ return [ 'default' => 'mariadb', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_DB_PORT', @@ -268,7 +268,7 @@ return [ 'default' => '3306', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_DB_SCHEMA', @@ -277,7 +277,7 @@ return [ 'default' => 'appwrite', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_DB_USER', @@ -286,7 +286,7 @@ return [ 'default' => 'user', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_DB_PASS', @@ -295,7 +295,7 @@ return [ 'default' => 'password', 'required' => false, 'question' => '', - 'filter' => 'password' + 'filter' => 'password', ], [ 'name' => '_APP_DB_ROOT_PASS', @@ -304,7 +304,7 @@ return [ 'default' => 'rootsecretpassword', 'required' => false, 'question' => '', - 'filter' => 'password' + 'filter' => 'password', ], ], ], @@ -319,7 +319,7 @@ return [ 'default' => 'influxdb', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_INFLUXDB_PORT', @@ -328,7 +328,7 @@ return [ 'default' => '8086', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], ], ], @@ -343,7 +343,7 @@ return [ 'default' => 'telegraf', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_STATSD_PORT', @@ -352,7 +352,7 @@ return [ 'default' => '8125', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], ], ], @@ -367,7 +367,7 @@ return [ 'default' => '', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_SMTP_PORT', @@ -376,7 +376,7 @@ return [ 'default' => '', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_SMTP_SECURE', @@ -385,7 +385,7 @@ return [ 'default' => '', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_SMTP_USERNAME', @@ -394,7 +394,7 @@ return [ 'default' => '', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_SMTP_PASSWORD', @@ -403,7 +403,7 @@ return [ 'default' => '', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], ], ], @@ -418,7 +418,7 @@ return [ 'default' => '', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_SMS_FROM', @@ -427,7 +427,7 @@ return [ 'default' => '', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], ], ], @@ -442,7 +442,7 @@ return [ 'default' => '30000000', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_STORAGE_PREVIEW_LIMIT', @@ -451,7 +451,7 @@ return [ 'default' => '20000000', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_STORAGE_ANTIVIRUS', @@ -460,7 +460,7 @@ return [ 'default' => 'disabled', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_STORAGE_ANTIVIRUS_HOST', @@ -469,7 +469,7 @@ return [ 'default' => 'clamav', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_STORAGE_ANTIVIRUS_PORT', @@ -478,7 +478,7 @@ return [ 'default' => '3310', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_STORAGE_DEVICE', @@ -661,7 +661,7 @@ return [ 'default' => '30000000', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_FUNCTIONS_TIMEOUT', @@ -670,7 +670,7 @@ return [ 'default' => '900', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_FUNCTIONS_BUILD_TIMEOUT', @@ -679,7 +679,7 @@ return [ 'default' => '900', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_FUNCTIONS_CONTAINERS', @@ -688,7 +688,7 @@ return [ 'default' => '10', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_FUNCTIONS_CPUS', @@ -697,7 +697,7 @@ return [ 'default' => '0', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_FUNCTIONS_MEMORY', @@ -706,7 +706,7 @@ return [ 'default' => '0', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_FUNCTIONS_MEMORY_SWAP', @@ -715,16 +715,16 @@ return [ 'default' => '0', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_FUNCTIONS_RUNTIMES', - 'description' => "This option allows you to enable or disable runtime environments for cloud functions. Disable unused runtimes to save disk space.\n\nTo enable cloud function runtimes, pass a list of enabled environments separated by a comma.\n\nCurrently, supported environments are: " . \implode(', ', \array_keys(Config::getParam('runtimes'))), + 'description' => "This option allows you to enable or disable runtime environments for cloud functions. Disable unused runtimes to save disk space.\n\nTo enable cloud function runtimes, pass a list of enabled environments separated by a comma.\n\nCurrently, supported environments are: ".\implode(', ', \array_keys(Config::getParam('runtimes'))), 'introduction' => '0.8.0', 'default' => 'node-16.0,php-8.0,python-3.9,ruby-3.0', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_EXECUTOR_SECRET', @@ -733,7 +733,7 @@ return [ 'default' => 'your-secret-key', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_EXECUTOR_HOST', @@ -742,7 +742,7 @@ return [ 'default' => 'http://appwrite-executor/v1', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_EXECUTOR_RUNTIME_NETWORK', @@ -751,7 +751,7 @@ return [ 'default' => 'appwrite_runtimes', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_FUNCTIONS_ENVS', @@ -760,7 +760,7 @@ return [ 'default' => 'node-16.0,php-7.4,python-3.9,ruby-3.0', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_FUNCTIONS_INACTIVE_THRESHOLD', @@ -769,7 +769,7 @@ return [ 'default' => '60', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => 'DOCKERHUB_PULL_USERNAME', @@ -778,7 +778,7 @@ return [ 'default' => '', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => 'DOCKERHUB_PULL_PASSWORD', @@ -787,7 +787,7 @@ return [ 'default' => '', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => 'DOCKERHUB_PULL_EMAIL', @@ -796,7 +796,7 @@ return [ 'default' => '', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => 'OPEN_RUNTIMES_NETWORK', @@ -805,7 +805,7 @@ return [ 'default' => 'appwrite_runtimes', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], ], ], @@ -820,7 +820,7 @@ return [ 'default' => '86400', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_MAINTENANCE_RETENTION_CACHE', @@ -829,7 +829,7 @@ return [ 'default' => '2592000', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_MAINTENANCE_RETENTION_EXECUTION', @@ -838,7 +838,7 @@ return [ 'default' => '1209600', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_MAINTENANCE_RETENTION_AUDIT', @@ -847,7 +847,7 @@ return [ 'default' => '1209600', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_MAINTENANCE_RETENTION_ABUSE', @@ -856,7 +856,7 @@ return [ 'default' => '86400', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_MAINTENANCE_RETENTION_USAGE_HOURLY', @@ -865,7 +865,7 @@ return [ 'default' => '8640000', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], ], ], @@ -880,7 +880,7 @@ return [ 'default' => '10', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_GRAPHQL_MAX_COMPLEXITY', @@ -889,7 +889,7 @@ return [ 'default' => '250', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], [ 'name' => '_APP_GRAPHQL_MAX_DEPTH', @@ -898,7 +898,7 @@ return [ 'default' => '3', 'required' => false, 'question' => '', - 'filter' => '' + 'filter' => '', ], ], ], diff --git a/app/controllers/api/account.php b/app/controllers/api/account.php index aa447290bf..c68514b8b2 100644 --- a/app/controllers/api/account.php +++ b/app/controllers/api/account.php @@ -10,8 +10,6 @@ use Appwrite\Event\Mail; use Appwrite\Event\Phone as EventPhone; use Appwrite\Extend\Exception; use Appwrite\Network\Validator\Email; -use Utopia\Validator\Host; -use Utopia\Validator\URL; use Appwrite\OpenSSL\OpenSSL; use Appwrite\Template\Template; use Appwrite\URL\URL as URLParser; @@ -26,19 +24,21 @@ use Utopia\App; use Utopia\Audit\Audit as EventAudit; use Utopia\Config\Config; use Utopia\Database\Database; -use Utopia\Database\Document; use Utopia\Database\DateTime; +use Utopia\Database\Document; use Utopia\Database\Exception\Duplicate; use Utopia\Database\Helpers\ID; use Utopia\Database\Helpers\Permission; -use Utopia\Database\Query; use Utopia\Database\Helpers\Role; +use Utopia\Database\Query; use Utopia\Database\Validator\Authorization; use Utopia\Database\Validator\UID; use Utopia\Locale\Locale; use Utopia\Validator\ArrayList; use Utopia\Validator\Assoc; +use Utopia\Validator\Host; use Utopia\Validator\Text; +use Utopia\Validator\URL; use Utopia\Validator\WhiteList; $oauthDefaultSuccess = '/auth/oauth2/success'; @@ -72,17 +72,16 @@ App::post('/v1/account') ->inject('dbForProject') ->inject('events') ->action(function (string $userId, string $email, string $password, string $name, Request $request, Response $response, Document $project, Database $dbForProject, Event $events) { - $email = \strtolower($email); if ('console' === $project->getId()) { $whitelistEmails = $project->getAttribute('authWhitelistEmails'); $whitelistIPs = $project->getAttribute('authWhitelistIPs'); - if (!empty($whitelistEmails) && !\in_array($email, $whitelistEmails)) { + if (! empty($whitelistEmails) && ! \in_array($email, $whitelistEmails)) { throw new Exception(Exception::USER_EMAIL_NOT_WHITELISTED); } - if (!empty($whitelistIPs) && !\in_array($request->getIP(), $whitelistIPs)) { + if (! empty($whitelistIPs) && ! \in_array($request->getIP(), $whitelistIPs)) { throw new Exception(Exception::USER_IP_NOT_WHITELISTED); } } @@ -99,7 +98,7 @@ App::post('/v1/account') try { $userId = $userId == 'unique()' ? ID::unique() : $userId; - $user = Authorization::skip(fn() => $dbForProject->createDocument('users', new Document([ + $user = Authorization::skip(fn () => $dbForProject->createDocument('users', new Document([ '$id' => $userId, '$permissions' => [ Permission::read(Role::any()), @@ -120,7 +119,7 @@ App::post('/v1/account') 'sessions' => null, 'tokens' => null, 'memberships' => null, - 'search' => implode(' ', [$userId, $email, $name]) + 'search' => implode(' ', [$userId, $email, $name]), ]))); } catch (Duplicate $th) { throw new Exception(Exception::USER_ALREADY_EXISTS); @@ -168,7 +167,6 @@ App::post('/v1/account/sessions/email') ->inject('geodb') ->inject('events') ->action(function (string $email, string $password, Request $request, Response $response, Database $dbForProject, Document $project, Locale $locale, Reader $geodb, Event $events) { - $email = \strtolower($email); $protocol = $request->getProtocol(); @@ -176,7 +174,7 @@ App::post('/v1/account/sessions/email') Query::equal('email', [$email]), ]); - if (!$profile || !Auth::passwordVerify($password, $profile->getAttribute('password'), $profile->getAttribute('hash'), $profile->getAttribute('hashOptions'))) { + if (! $profile || ! Auth::passwordVerify($password, $profile->getAttribute('password'), $profile->getAttribute('hash'), $profile->getAttribute('hashOptions'))) { throw new Exception(Exception::USER_INVALID_CREDENTIALS); } @@ -226,31 +224,26 @@ App::post('/v1/account/sessions/email') Permission::delete(Role::user($profile->getId())), ])); - - if (!Config::getParam('domainVerification')) { + if (! Config::getParam('domainVerification')) { $response - ->addHeader('X-Fallback-Cookies', \json_encode([Auth::$cookieName => Auth::encodeSession($profile->getId(), $secret)])) - ; + ->addHeader('X-Fallback-Cookies', \json_encode([Auth::$cookieName => Auth::encodeSession($profile->getId(), $secret)])); } $response - ->addCookie(Auth::$cookieName . '_legacy', Auth::encodeSession($profile->getId(), $secret), (new \DateTime($expire))->getTimestamp(), '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, null) + ->addCookie(Auth::$cookieName.'_legacy', Auth::encodeSession($profile->getId(), $secret), (new \DateTime($expire))->getTimestamp(), '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, null) ->addCookie(Auth::$cookieName, Auth::encodeSession($profile->getId(), $secret), (new \DateTime($expire))->getTimestamp(), '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, Config::getParam('cookieSamesite')) - ->setStatusCode(Response::STATUS_CODE_CREATED) - ; + ->setStatusCode(Response::STATUS_CODE_CREATED); - $countryName = $locale->getText('countries.' . strtolower($session->getAttribute('countryCode')), $locale->getText('locale.country.unknown')); + $countryName = $locale->getText('countries.'.strtolower($session->getAttribute('countryCode')), $locale->getText('locale.country.unknown')); $session ->setAttribute('current', true) ->setAttribute('countryName', $countryName) - ->setAttribute('expire', $expire) - ; + ->setAttribute('expire', $expire); $events ->setParam('userId', $profile->getId()) - ->setParam('sessionId', $session->getId()) - ; + ->setParam('sessionId', $session->getId()); $response->dynamic($session, Response::MODEL_SESSION); }); @@ -258,7 +251,7 @@ App::post('/v1/account/sessions/email') App::get('/v1/account/sessions/oauth2/:provider') ->desc('Create OAuth2 Session') ->groups(['api', 'account']) - ->label('error', __DIR__ . '/../../views/general/error.phtml') + ->label('error', __DIR__.'/../../views/general/error.phtml') ->label('scope', 'public') ->label('sdk.auth', []) ->label('sdk.namespace', 'account') @@ -269,47 +262,46 @@ App::get('/v1/account/sessions/oauth2/:provider') ->label('sdk.methodType', 'webAuth') ->label('abuse-limit', 50) ->label('abuse-key', 'ip:{ip}') - ->param('provider', '', new WhiteList(\array_keys(Config::getParam('providers')), true), 'OAuth2 Provider. Currently, supported providers are: ' . \implode(', ', \array_keys(\array_filter(Config::getParam('providers'), fn($node) => (!$node['mock'])))) . '.') - ->param('success', '', fn($clients) => new Host($clients), 'URL to redirect back to your app after a successful login attempt. Only URLs from hostnames in your project platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API.', true, ['clients']) - ->param('failure', '', fn($clients) => new Host($clients), 'URL to redirect back to your app after a failed login attempt. Only URLs from hostnames in your project platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API.', true, ['clients']) - ->param('scopes', [], new ArrayList(new Text(APP_LIMIT_ARRAY_ELEMENT_SIZE), APP_LIMIT_ARRAY_PARAMS_SIZE), 'A list of custom OAuth2 scopes. Check each provider internal docs for a list of supported scopes. Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' scopes are allowed, each ' . APP_LIMIT_ARRAY_ELEMENT_SIZE . ' characters long.', true) + ->param('provider', '', new WhiteList(\array_keys(Config::getParam('providers')), true), 'OAuth2 Provider. Currently, supported providers are: '.\implode(', ', \array_keys(\array_filter(Config::getParam('providers'), fn ($node) => (! $node['mock'])))).'.') + ->param('success', '', fn ($clients) => new Host($clients), 'URL to redirect back to your app after a successful login attempt. Only URLs from hostnames in your project platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API.', true, ['clients']) + ->param('failure', '', fn ($clients) => new Host($clients), 'URL to redirect back to your app after a failed login attempt. Only URLs from hostnames in your project platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API.', true, ['clients']) + ->param('scopes', [], new ArrayList(new Text(APP_LIMIT_ARRAY_ELEMENT_SIZE), APP_LIMIT_ARRAY_PARAMS_SIZE), 'A list of custom OAuth2 scopes. Check each provider internal docs for a list of supported scopes. Maximum of '.APP_LIMIT_ARRAY_PARAMS_SIZE.' scopes are allowed, each '.APP_LIMIT_ARRAY_ELEMENT_SIZE.' characters long.', true) ->inject('request') ->inject('response') ->inject('project') ->action(function (string $provider, string $success, string $failure, array $scopes, Request $request, Response $response, Document $project) use ($oauthDefaultSuccess, $oauthDefaultFailure) { - $protocol = $request->getProtocol(); - $callback = $protocol . '://' . $request->getHostname() . '/v1/account/sessions/oauth2/callback/' . $provider . '/' . $project->getId(); - $providerEnabled = $project->getAttribute('authProviders', [])[$provider . 'Enabled'] ?? false; + $callback = $protocol.'://'.$request->getHostname().'/v1/account/sessions/oauth2/callback/'.$provider.'/'.$project->getId(); + $providerEnabled = $project->getAttribute('authProviders', [])[$provider.'Enabled'] ?? false; - if (!$providerEnabled) { - throw new Exception(Exception::PROJECT_PROVIDER_DISABLED, 'This provider is disabled. Please enable the provider from your ' . APP_NAME . ' console to continue.'); + if (! $providerEnabled) { + throw new Exception(Exception::PROJECT_PROVIDER_DISABLED, 'This provider is disabled. Please enable the provider from your '.APP_NAME.' console to continue.'); } - $appId = $project->getAttribute('authProviders', [])[$provider . 'Appid'] ?? ''; - $appSecret = $project->getAttribute('authProviders', [])[$provider . 'Secret'] ?? '{}'; + $appId = $project->getAttribute('authProviders', [])[$provider.'Appid'] ?? ''; + $appSecret = $project->getAttribute('authProviders', [])[$provider.'Secret'] ?? '{}'; - if (!empty($appSecret) && isset($appSecret['version'])) { - $key = App::getEnv('_APP_OPENSSL_KEY_V' . $appSecret['version']); + if (! empty($appSecret) && isset($appSecret['version'])) { + $key = App::getEnv('_APP_OPENSSL_KEY_V'.$appSecret['version']); $appSecret = OpenSSL::decrypt($appSecret['data'], $appSecret['method'], $key, 0, \hex2bin($appSecret['iv']), \hex2bin($appSecret['tag'])); } if (empty($appId) || empty($appSecret)) { - throw new Exception(Exception::PROJECT_PROVIDER_DISABLED, 'This provider is disabled. Please configure the provider app ID and app secret key from your ' . APP_NAME . ' console to continue.'); + throw new Exception(Exception::PROJECT_PROVIDER_DISABLED, 'This provider is disabled. Please configure the provider app ID and app secret key from your '.APP_NAME.' console to continue.'); } - $className = 'Appwrite\\Auth\\OAuth2\\' . \ucfirst($provider); + $className = 'Appwrite\\Auth\\OAuth2\\'.\ucfirst($provider); - if (!\class_exists($className)) { + if (! \class_exists($className)) { throw new Exception(Exception::PROJECT_PROVIDER_UNSUPPORTED); } if (empty($success)) { - $success = $protocol . '://' . $request->getHostname() . $oauthDefaultSuccess; + $success = $protocol.'://'.$request->getHostname().$oauthDefaultSuccess; } if (empty($failure)) { - $failure = $protocol . '://' . $request->getHostname() . $oauthDefaultFailure; + $failure = $protocol.'://'.$request->getHostname().$oauthDefaultFailure; } $oauth2 = new $className($appId, $appSecret, $callback, ['success' => $success, 'failure' => $failure], $scopes); @@ -323,7 +315,7 @@ App::get('/v1/account/sessions/oauth2/:provider') App::get('/v1/account/sessions/oauth2/callback/:provider/:projectId') ->desc('OAuth2 Callback') ->groups(['api', 'account']) - ->label('error', __DIR__ . '/../../views/general/error.phtml') + ->label('error', __DIR__.'/../../views/general/error.phtml') ->label('scope', 'public') ->label('docs', false) ->param('projectId', '', new Text(1024), 'Project ID.') @@ -333,21 +325,20 @@ App::get('/v1/account/sessions/oauth2/callback/:provider/:projectId') ->inject('request') ->inject('response') ->action(function (string $projectId, string $provider, string $code, string $state, Request $request, Response $response) { - $domain = $request->getHostname(); $protocol = $request->getProtocol(); $response ->addHeader('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0') ->addHeader('Pragma', 'no-cache') - ->redirect($protocol . '://' . $domain . '/v1/account/sessions/oauth2/' . $provider . '/redirect?' - . \http_build_query(['project' => $projectId, 'code' => $code, 'state' => $state])); + ->redirect($protocol.'://'.$domain.'/v1/account/sessions/oauth2/'.$provider.'/redirect?' + .\http_build_query(['project' => $projectId, 'code' => $code, 'state' => $state])); }); App::post('/v1/account/sessions/oauth2/callback/:provider/:projectId') ->desc('OAuth2 Callback') ->groups(['api', 'account']) - ->label('error', __DIR__ . '/../../views/general/error.phtml') + ->label('error', __DIR__.'/../../views/general/error.phtml') ->label('scope', 'public') ->label('origin', '*') ->label('docs', false) @@ -358,21 +349,20 @@ App::post('/v1/account/sessions/oauth2/callback/:provider/:projectId') ->inject('request') ->inject('response') ->action(function (string $projectId, string $provider, string $code, string $state, Request $request, Response $response) { - $domain = $request->getHostname(); $protocol = $request->getProtocol(); $response ->addHeader('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0') ->addHeader('Pragma', 'no-cache') - ->redirect($protocol . '://' . $domain . '/v1/account/sessions/oauth2/' . $provider . '/redirect?' - . \http_build_query(['project' => $projectId, 'code' => $code, 'state' => $state])); + ->redirect($protocol.'://'.$domain.'/v1/account/sessions/oauth2/'.$provider.'/redirect?' + .\http_build_query(['project' => $projectId, 'code' => $code, 'state' => $state])); }); App::get('/v1/account/sessions/oauth2/:provider/redirect') ->desc('OAuth2 Redirect') ->groups(['api', 'account', 'session']) - ->label('error', __DIR__ . '/../../views/general/error.phtml') + ->label('error', __DIR__.'/../../views/general/error.phtml') ->label('event', 'users.[userId].sessions.[sessionId].create') ->label('scope', 'public') ->label('audits.event', 'session.create') @@ -394,33 +384,32 @@ App::get('/v1/account/sessions/oauth2/:provider/redirect') ->inject('geodb') ->inject('events') ->action(function (string $provider, string $code, string $state, Request $request, Response $response, Document $project, Document $user, Database $dbForProject, Reader $geodb, Event $events) use ($oauthDefaultSuccess) { - $protocol = $request->getProtocol(); - $callback = $protocol . '://' . $request->getHostname() . '/v1/account/sessions/oauth2/callback/' . $provider . '/' . $project->getId(); + $callback = $protocol.'://'.$request->getHostname().'/v1/account/sessions/oauth2/callback/'.$provider.'/'.$project->getId(); $defaultState = ['success' => $project->getAttribute('url', ''), 'failure' => '']; $validateURL = new URL(); - $appId = $project->getAttribute('authProviders', [])[$provider . 'Appid'] ?? ''; - $appSecret = $project->getAttribute('authProviders', [])[$provider . 'Secret'] ?? '{}'; - $providerEnabled = $project->getAttribute('authProviders', [])[$provider . 'Enabled'] ?? false; + $appId = $project->getAttribute('authProviders', [])[$provider.'Appid'] ?? ''; + $appSecret = $project->getAttribute('authProviders', [])[$provider.'Secret'] ?? '{}'; + $providerEnabled = $project->getAttribute('authProviders', [])[$provider.'Enabled'] ?? false; - if (!$providerEnabled) { - throw new Exception(Exception::PROJECT_PROVIDER_DISABLED, 'This provider is disabled. Please enable the provider from your ' . APP_NAME . ' console to continue.'); + if (! $providerEnabled) { + throw new Exception(Exception::PROJECT_PROVIDER_DISABLED, 'This provider is disabled. Please enable the provider from your '.APP_NAME.' console to continue.'); } - if (!empty($appSecret) && isset($appSecret['version'])) { - $key = App::getEnv('_APP_OPENSSL_KEY_V' . $appSecret['version']); + if (! empty($appSecret) && isset($appSecret['version'])) { + $key = App::getEnv('_APP_OPENSSL_KEY_V'.$appSecret['version']); $appSecret = OpenSSL::decrypt($appSecret['data'], $appSecret['method'], $key, 0, \hex2bin($appSecret['iv']), \hex2bin($appSecret['tag'])); } - $className = 'Appwrite\\Auth\\OAuth2\\' . \ucfirst($provider); + $className = 'Appwrite\\Auth\\OAuth2\\'.\ucfirst($provider); - if (!\class_exists($className)) { + if (! \class_exists($className)) { throw new Exception(Exception::PROJECT_PROVIDER_UNSUPPORTED); } $oauth2 = new $className($appId, $appSecret, $callback); - if (!empty($state)) { + if (! empty($state)) { try { $state = \array_merge($defaultState, $oauth2->parseState($state)); } catch (\Exception$exception) { @@ -430,11 +419,11 @@ App::get('/v1/account/sessions/oauth2/:provider/redirect') $state = $defaultState; } - if (!$validateURL->isValid($state['success'])) { + if (! $validateURL->isValid($state['success'])) { throw new Exception(Exception::PROJECT_INVALID_SUCCESS_URL); } - if (!empty($state['failure']) && !$validateURL->isValid($state['failure'])) { + if (! empty($state['failure']) && ! $validateURL->isValid($state['failure'])) { throw new Exception(Exception::PROJECT_INVALID_FAILURE_URL); } @@ -443,7 +432,7 @@ App::get('/v1/account/sessions/oauth2/:provider/redirect') $accessTokenExpiry = $oauth2->getAccessTokenExpiry($code); if (empty($accessToken)) { - if (!empty($state['failure'])) { + if (! empty($state['failure'])) { $response->redirect($state['failure'], 301, 0); } @@ -453,7 +442,7 @@ App::get('/v1/account/sessions/oauth2/:provider/redirect') $oauth2ID = $oauth2->getUserID($accessToken); if (empty($oauth2ID)) { - if (!empty($state['failure'])) { + if (! empty($state['failure'])) { $response->redirect($state['failure'], 301, 0); } @@ -466,7 +455,7 @@ App::get('/v1/account/sessions/oauth2/:provider/redirect') if ($current) { // Delete current session of new one. $currentDocument = $dbForProject->getDocument('sessions', $current); - if (!$currentDocument->isEmpty()) { + if (! $currentDocument->isEmpty()) { $dbForProject->deleteDocument('sessions', $currentDocument->getId()); $dbForProject->deleteCachedDocument('users', $user->getId()); } @@ -503,7 +492,7 @@ App::get('/v1/account/sessions/oauth2/:provider/redirect') try { $userId = ID::unique(); - $user = Authorization::skip(fn() => $dbForProject->createDocument('users', new Document([ + $user = Authorization::skip(fn () => $dbForProject->createDocument('users', new Document([ '$id' => $userId, '$permissions' => [ Permission::read(Role::any()), @@ -524,7 +513,7 @@ App::get('/v1/account/sessions/oauth2/:provider/redirect') 'sessions' => null, 'tokens' => null, 'memberships' => null, - 'search' => implode(' ', [$userId, $email, $name]) + 'search' => implode(' ', [$userId, $email, $name]), ]))); } catch (Duplicate $th) { throw new Exception(Exception::USER_ALREADY_EXISTS); @@ -551,7 +540,7 @@ App::get('/v1/account/sessions/oauth2/:provider/redirect') 'providerUid' => $oauth2ID, 'providerAccessToken' => $accessToken, 'providerRefreshToken' => $refreshToken, - 'providerAccessTokenExpiry' => DateTime::addSeconds(new \DateTime(), (int)$accessTokenExpiry), + 'providerAccessTokenExpiry' => DateTime::addSeconds(new \DateTime(), (int) $accessTokenExpiry), 'secret' => Auth::hash($secret), // One way hash encryption to protect DB leak 'userAgent' => $request->getUserAgent('UNKNOWN'), 'ip' => $request->getIP(), @@ -563,13 +552,11 @@ App::get('/v1/account/sessions/oauth2/:provider/redirect') if ($isAnonymousUser) { $user ->setAttribute('name', $oauth2->getUserName($accessToken)) - ->setAttribute('email', $oauth2->getUserEmail($accessToken)) - ; + ->setAttribute('email', $oauth2->getUserEmail($accessToken)); } $user - ->setAttribute('status', true) - ; + ->setAttribute('status', true); Authorization::setRole(Role::user($user->getId())->toString()); @@ -588,10 +575,9 @@ App::get('/v1/account/sessions/oauth2/:provider/redirect') $events ->setParam('userId', $user->getId()) ->setParam('sessionId', $session->getId()) - ->setPayload($response->output($session, Response::MODEL_SESSION)) - ; + ->setPayload($response->output($session, Response::MODEL_SESSION)); - if (!Config::getParam('domainVerification')) { + if (! Config::getParam('domainVerification')) { $response->addHeader('X-Fallback-Cookies', \json_encode([Auth::$cookieName => Auth::encodeSession($user->getId(), $secret)])); } @@ -610,10 +596,9 @@ App::get('/v1/account/sessions/oauth2/:provider/redirect') $response ->addHeader('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0') ->addHeader('Pragma', 'no-cache') - ->addCookie(Auth::$cookieName . '_legacy', Auth::encodeSession($user->getId(), $secret), (new \DateTime($expire))->getTimestamp(), '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, null) + ->addCookie(Auth::$cookieName.'_legacy', Auth::encodeSession($user->getId(), $secret), (new \DateTime($expire))->getTimestamp(), '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, null) ->addCookie(Auth::$cookieName, Auth::encodeSession($user->getId(), $secret), (new \DateTime($expire))->getTimestamp(), '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, Config::getParam('cookieSamesite')) - ->redirect($state['success']) - ; + ->redirect($state['success']); }); App::post('/v1/account/sessions/magic-url') @@ -635,7 +620,7 @@ App::post('/v1/account/sessions/magic-url') ->label('abuse-key', 'url:{url},email:{param-email}') ->param('userId', '', new CustomId(), 'Unique Id. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can\'t start with a special char. Max length is 36 chars.') ->param('email', '', new Email(), 'User email.') - ->param('url', '', fn($clients) => new Host($clients), 'URL to redirect the user back to your app from the magic URL login. Only URLs from hostnames in your project platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API.', true, ['clients']) + ->param('url', '', fn ($clients) => new Host($clients), 'URL to redirect the user back to your app from the magic URL login. Only URLs from hostnames in your project platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API.', true, ['clients']) ->inject('request') ->inject('response') ->inject('project') @@ -644,7 +629,6 @@ App::post('/v1/account/sessions/magic-url') ->inject('events') ->inject('mails') ->action(function (string $userId, string $email, string $url, Request $request, Response $response, Document $project, Database $dbForProject, Locale $locale, Event $events, Mail $mails) { - if (empty(App::getEnv('_APP_SMTP_HOST'))) { throw new Exception(Exception::GENERAL_SMTP_DISABLED, 'SMTP disabled'); } @@ -655,7 +639,7 @@ App::post('/v1/account/sessions/magic-url') $user = $dbForProject->findOne('users', [Query::equal('email', [$email])]); - if (!$user) { + if (! $user) { $limit = $project->getAttribute('auths', [])['limit'] ?? 0; if ($limit !== 0) { @@ -688,7 +672,7 @@ App::post('/v1/account/sessions/magic-url') 'sessions' => null, 'tokens' => null, 'memberships' => null, - 'search' => implode(' ', [$userId, $email]) + 'search' => implode(' ', [$userId, $email]), ]))); } @@ -718,7 +702,7 @@ App::post('/v1/account/sessions/magic-url') $dbForProject->deleteCachedDocument('users', $user->getId()); if (empty($url)) { - $url = $request->getProtocol() . '://' . $request->getHostname() . '/auth/magic-url'; + $url = $request->getProtocol().'://'.$request->getHostname().'/auth/magic-url'; } $url = Template::parseURL($url); @@ -727,18 +711,18 @@ App::post('/v1/account/sessions/magic-url') $from = $project->isEmpty() || $project->getId() === 'console' ? '' : \sprintf($locale->getText('emails.sender'), $project->getAttribute('name')); - $body = Template::fromFile(__DIR__ . '/../../config/locale/templates/email-base.tpl'); - $subject = $locale->getText("emails.magicSession.subject"); + $body = Template::fromFile(__DIR__.'/../../config/locale/templates/email-base.tpl'); + $subject = $locale->getText('emails.magicSession.subject'); $body ->setParam('{{subject}}', $subject) - ->setParam('{{hello}}', $locale->getText("emails.magicSession.hello")) + ->setParam('{{hello}}', $locale->getText('emails.magicSession.hello')) ->setParam('{{name}}', '') - ->setParam('{{body}}', $locale->getText("emails.magicSession.body")) + ->setParam('{{body}}', $locale->getText('emails.magicSession.body')) ->setParam('{{redirect}}', $url) - ->setParam('{{footer}}', $locale->getText("emails.magicSession.footer")) - ->setParam('{{thanks}}', $locale->getText("emails.magicSession.thanks")) - ->setParam('{{signature}}', $locale->getText("emails.magicSession.signature")) + ->setParam('{{footer}}', $locale->getText('emails.magicSession.footer')) + ->setParam('{{thanks}}', $locale->getText('emails.magicSession.thanks')) + ->setParam('{{signature}}', $locale->getText('emails.magicSession.signature')) ->setParam('{{project}}', $project->getAttribute('name')) ->setParam('{{direction}}', $locale->getText('settings.direction')) ->setParam('{{bg-body}}', '#f7f7f7') @@ -752,8 +736,7 @@ App::post('/v1/account/sessions/magic-url') ->setBody($body) ->setFrom($from) ->setRecipient($user->getAttribute('email')) - ->trigger() - ; + ->trigger(); $events->setPayload( $response->output( @@ -767,8 +750,7 @@ App::post('/v1/account/sessions/magic-url') $response ->setStatusCode(Response::STATUS_CODE_CREATED) - ->dynamic($token, Response::MODEL_TOKEN) - ; + ->dynamic($token, Response::MODEL_TOKEN); }); App::put('/v1/account/sessions/magic-url') @@ -800,10 +782,8 @@ App::put('/v1/account/sessions/magic-url') ->inject('geodb') ->inject('events') ->action(function (string $userId, string $secret, Request $request, Response $response, Database $dbForProject, Document $project, Locale $locale, Reader $geodb, Event $events) { - /** @var Utopia\Database\Document $user */ - - $user = Authorization::skip(fn() => $dbForProject->getDocument('users', $userId)); + $user = Authorization::skip(fn () => $dbForProject->getDocument('users', $userId)); if ($user->isEmpty()) { throw new Exception(Exception::USER_NOT_FOUND); @@ -811,7 +791,7 @@ App::put('/v1/account/sessions/magic-url') $token = Auth::tokenVerify($user->getAttribute('tokens', []), Auth::TOKEN_TYPE_MAGIC_URL, $secret); - if (!$token) { + if (! $token) { throw new Exception(Exception::USER_INVALID_TOKEN); } @@ -867,28 +847,25 @@ App::put('/v1/account/sessions/magic-url') $events ->setParam('userId', $user->getId()) - ->setParam('sessionId', $session->getId()) - ; + ->setParam('sessionId', $session->getId()); - if (!Config::getParam('domainVerification')) { + if (! Config::getParam('domainVerification')) { $response->addHeader('X-Fallback-Cookies', \json_encode([Auth::$cookieName => Auth::encodeSession($user->getId(), $secret)])); } $protocol = $request->getProtocol(); $response - ->addCookie(Auth::$cookieName . '_legacy', Auth::encodeSession($user->getId(), $secret), (new \DateTime($expire))->getTimestamp(), '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, null) + ->addCookie(Auth::$cookieName.'_legacy', Auth::encodeSession($user->getId(), $secret), (new \DateTime($expire))->getTimestamp(), '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, null) ->addCookie(Auth::$cookieName, Auth::encodeSession($user->getId(), $secret), (new \DateTime($expire))->getTimestamp(), '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, Config::getParam('cookieSamesite')) - ->setStatusCode(Response::STATUS_CODE_CREATED) - ; + ->setStatusCode(Response::STATUS_CODE_CREATED); - $countryName = $locale->getText('countries.' . strtolower($session->getAttribute('countryCode')), $locale->getText('locale.country.unknown')); + $countryName = $locale->getText('countries.'.strtolower($session->getAttribute('countryCode')), $locale->getText('locale.country.unknown')); $session ->setAttribute('current', true) ->setAttribute('countryName', $countryName) - ->setAttribute('expire', $expire) - ; + ->setAttribute('expire', $expire); $response->dynamic($session, Response::MODEL_SESSION); }); @@ -919,7 +896,6 @@ App::post('/v1/account/sessions/phone') ->inject('events') ->inject('messaging') ->action(function (string $userId, string $phone, Request $request, Response $response, Document $project, Database $dbForProject, Event $events, EventPhone $messaging) { - if (empty(App::getEnv('_APP_SMS_PROVIDER'))) { throw new Exception(Exception::GENERAL_PHONE_DISABLED, 'Phone provider not configured'); } @@ -930,7 +906,7 @@ App::post('/v1/account/sessions/phone') $user = $dbForProject->findOne('users', [Query::equal('phone', [$phone])]); - if (!$user) { + if (! $user) { $limit = $project->getAttribute('auths', [])['limit'] ?? 0; if ($limit !== 0) { @@ -963,7 +939,7 @@ App::post('/v1/account/sessions/phone') 'sessions' => null, 'tokens' => null, 'memberships' => null, - 'search' => implode(' ', [$userId, $phone]) + 'search' => implode(' ', [$userId, $phone]), ]))); } @@ -1009,8 +985,7 @@ App::post('/v1/account/sessions/phone') $response ->setStatusCode(Response::STATUS_CODE_CREATED) - ->dynamic($token, Response::MODEL_TOKEN) - ; + ->dynamic($token, Response::MODEL_TOKEN); }); App::put('/v1/account/sessions/phone') @@ -1039,8 +1014,7 @@ App::put('/v1/account/sessions/phone') ->inject('geodb') ->inject('events') ->action(function (string $userId, string $secret, Request $request, Response $response, Database $dbForProject, Document $project, Locale $locale, Reader $geodb, Event $events) { - - $user = Authorization::skip(fn() => $dbForProject->getDocument('users', $userId)); + $user = Authorization::skip(fn () => $dbForProject->getDocument('users', $userId)); if ($user->isEmpty()) { throw new Exception(Exception::USER_NOT_FOUND); @@ -1048,7 +1022,7 @@ App::put('/v1/account/sessions/phone') $token = Auth::phoneTokenVerify($user->getAttribute('tokens', []), $secret); - if (!$token) { + if (! $token) { throw new Exception(Exception::USER_INVALID_TOKEN); } @@ -1102,28 +1076,25 @@ App::put('/v1/account/sessions/phone') $events ->setParam('userId', $user->getId()) - ->setParam('sessionId', $session->getId()) - ; + ->setParam('sessionId', $session->getId()); - if (!Config::getParam('domainVerification')) { + if (! Config::getParam('domainVerification')) { $response->addHeader('X-Fallback-Cookies', \json_encode([Auth::$cookieName => Auth::encodeSession($user->getId(), $secret)])); } $protocol = $request->getProtocol(); $response - ->addCookie(Auth::$cookieName . '_legacy', Auth::encodeSession($user->getId(), $secret), (new \DateTime($expire))->getTimestamp(), '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, null) + ->addCookie(Auth::$cookieName.'_legacy', Auth::encodeSession($user->getId(), $secret), (new \DateTime($expire))->getTimestamp(), '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, null) ->addCookie(Auth::$cookieName, Auth::encodeSession($user->getId(), $secret), (new \DateTime($expire))->getTimestamp(), '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, Config::getParam('cookieSamesite')) - ->setStatusCode(Response::STATUS_CODE_CREATED) - ; + ->setStatusCode(Response::STATUS_CODE_CREATED); - $countryName = $locale->getText('countries.' . strtolower($session->getAttribute('countryCode')), $locale->getText('locale.country.unknown')); + $countryName = $locale->getText('countries.'.strtolower($session->getAttribute('countryCode')), $locale->getText('locale.country.unknown')); $session ->setAttribute('current', true) ->setAttribute('countryName', $countryName) - ->setAttribute('expire', $expire) - ; + ->setAttribute('expire', $expire); $response->dynamic($session, Response::MODEL_SESSION); }); @@ -1157,14 +1128,13 @@ App::post('/v1/account/sessions/anonymous') ->inject('geodb') ->inject('events') ->action(function (Request $request, Response $response, Locale $locale, Document $user, Document $project, Database $dbForProject, Reader $geodb, Event $events) { - $protocol = $request->getProtocol(); if ('console' === $project->getId()) { throw new Exception(Exception::USER_ANONYMOUS_CONSOLE_PROHIBITED, 'Failed to create anonymous user'); } - if (!$user->isEmpty()) { + if (! $user->isEmpty()) { throw new Exception(Exception::USER_SESSION_ALREADY_EXISTS, 'Cannot create an anonymous user when logged in'); } @@ -1179,7 +1149,7 @@ App::post('/v1/account/sessions/anonymous') } $userId = ID::unique(); - $user = Authorization::skip(fn() => $dbForProject->createDocument('users', new Document([ + $user = Authorization::skip(fn () => $dbForProject->createDocument('users', new Document([ '$id' => $userId, '$permissions' => [ Permission::read(Role::any()), @@ -1200,7 +1170,7 @@ App::post('/v1/account/sessions/anonymous') 'sessions' => null, 'tokens' => null, 'memberships' => null, - 'search' => $userId + 'search' => $userId, ]))); // Create session token @@ -1228,36 +1198,33 @@ App::post('/v1/account/sessions/anonymous') Authorization::setRole(Role::user($user->getId())->toString()); - $session = $dbForProject->createDocument('sessions', $session-> setAttribute('$permissions', [ - Permission::read(Role::user($user->getId())), - Permission::update(Role::user($user->getId())), - Permission::delete(Role::user($user->getId())), - ])); + $session = $dbForProject->createDocument('sessions', $session->setAttribute('$permissions', [ + Permission::read(Role::user($user->getId())), + Permission::update(Role::user($user->getId())), + Permission::delete(Role::user($user->getId())), + ])); $dbForProject->deleteCachedDocument('users', $user->getId()); $events ->setParam('userId', $user->getId()) - ->setParam('sessionId', $session->getId()) - ; + ->setParam('sessionId', $session->getId()); - if (!Config::getParam('domainVerification')) { + if (! Config::getParam('domainVerification')) { $response->addHeader('X-Fallback-Cookies', \json_encode([Auth::$cookieName => Auth::encodeSession($user->getId(), $secret)])); } $response - ->addCookie(Auth::$cookieName . '_legacy', Auth::encodeSession($user->getId(), $secret), (new \DateTime($expire))->getTimestamp(), '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, null) + ->addCookie(Auth::$cookieName.'_legacy', Auth::encodeSession($user->getId(), $secret), (new \DateTime($expire))->getTimestamp(), '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, null) ->addCookie(Auth::$cookieName, Auth::encodeSession($user->getId(), $secret), (new \DateTime($expire))->getTimestamp(), '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, Config::getParam('cookieSamesite')) - ->setStatusCode(Response::STATUS_CODE_CREATED) - ; + ->setStatusCode(Response::STATUS_CODE_CREATED); - $countryName = $locale->getText('countries.' . strtolower($session->getAttribute('countryCode')), $locale->getText('locale.country.unknown')); + $countryName = $locale->getText('countries.'.strtolower($session->getAttribute('countryCode')), $locale->getText('locale.country.unknown')); $session ->setAttribute('current', true) ->setAttribute('countryName', $countryName) - ->setAttribute('expire', $expire) - ; + ->setAttribute('expire', $expire); $response->dynamic($session, Response::MODEL_SESSION); }); @@ -1280,8 +1247,6 @@ App::post('/v1/account/jwt') ->inject('user') ->inject('dbForProject') ->action(function (Response $response, Document $user, Database $dbForProject) { - - $sessions = $user->getAttribute('sessions', []); $current = new Document(); @@ -1300,13 +1265,13 @@ App::post('/v1/account/jwt') $response ->setStatusCode(Response::STATUS_CODE_CREATED) ->dynamic(new Document(['jwt' => $jwt->encode([ - // 'uid' => 1, - // 'aud' => 'http://site.com', - // 'scopes' => ['user'], - // 'iss' => 'http://api.mysite.com', - 'userId' => $user->getId(), - 'sessionId' => $current->getId(), - ])]), Response::MODEL_JWT); + // 'uid' => 1, + // 'aud' => 'http://site.com', + // 'scopes' => ['user'], + // 'iss' => 'http://api.mysite.com', + 'userId' => $user->getId(), + 'sessionId' => $current->getId(), + ])]), Response::MODEL_JWT); }); App::get('/v1/account') @@ -1326,7 +1291,6 @@ App::get('/v1/account') ->inject('response') ->inject('user') ->action(function (Response $response, Document $user) { - $response->dynamic($user, Response::MODEL_ACCOUNT); }); @@ -1347,7 +1311,6 @@ App::get('/v1/account/prefs') ->inject('response') ->inject('user') ->action(function (Response $response, Document $user) { - $prefs = $user->getAttribute('prefs', new \stdClass()); $response->dynamic(new Document($prefs), Response::MODEL_PREFERENCES); @@ -1371,13 +1334,12 @@ App::get('/v1/account/sessions') ->inject('locale') ->inject('project') ->action(function (Response $response, Document $user, Locale $locale, Document $project) { - $sessions = $user->getAttribute('sessions', []); $authDuration = $project->getAttribute('auths', [])['duration'] ?? Auth::TOKEN_EXPIRATION_LOGIN_LONG; $current = Auth::sessionVerify($sessions, Auth::$secret, $authDuration); foreach ($sessions as $key => $session) {/** @var Document $session */ - $countryName = $locale->getText('countries.' . strtolower($session->getAttribute('countryCode')), $locale->getText('locale.country.unknown')); + $countryName = $locale->getText('countries.'.strtolower($session->getAttribute('countryCode')), $locale->getText('locale.country.unknown')); $session->setAttribute('countryName', $countryName); $session->setAttribute('current', ($current == $session->getId()) ? true : false); @@ -1410,7 +1372,6 @@ App::get('/v1/account/logs') ->inject('geodb') ->inject('dbForProject') ->action(function (array $queries, Response $response, Document $user, Locale $locale, Reader $geodb, Database $dbForProject) { - $queries = Query::parseQueries($queries); $grouped = Query::groupByType($queries); $limit = $grouped['limit'] ?? APP_LIMIT_COUNT; @@ -1423,7 +1384,7 @@ App::get('/v1/account/logs') $output = []; foreach ($logs as $i => &$log) { - $log['userAgent'] = (!empty($log['userAgent'])) ? $log['userAgent'] : 'UNKNOWN'; + $log['userAgent'] = (! empty($log['userAgent'])) ? $log['userAgent'] : 'UNKNOWN'; $detector = new Detector($log['userAgent']); @@ -1438,8 +1399,8 @@ App::get('/v1/account/logs') $record = $geodb->get($log['ip']); if ($record) { - $output[$i]['countryCode'] = $locale->getText('countries.' . strtolower($record['country']['iso_code']), false) ? \strtolower($record['country']['iso_code']) : '--'; - $output[$i]['countryName'] = $locale->getText('countries.' . strtolower($record['country']['iso_code']), $locale->getText('locale.country.unknown')); + $output[$i]['countryCode'] = $locale->getText('countries.'.strtolower($record['country']['iso_code']), false) ? \strtolower($record['country']['iso_code']) : '--'; + $output[$i]['countryName'] = $locale->getText('countries.'.strtolower($record['country']['iso_code']), $locale->getText('locale.country.unknown')); } else { $output[$i]['countryCode'] = '--'; $output[$i]['countryName'] = $locale->getText('locale.country.unknown'); @@ -1473,7 +1434,6 @@ App::get('/v1/account/sessions/:sessionId') ->inject('dbForProject') ->inject('project') ->action(function (?string $sessionId, Response $response, Document $user, Locale $locale, Database $dbForProject, Document $project) { - $sessions = $user->getAttribute('sessions', []); $authDuration = $project->getAttribute('auths', [])['duration'] ?? Auth::TOKEN_EXPIRATION_LOGIN_LONG; $sessionId = ($sessionId === 'current') @@ -1482,13 +1442,12 @@ App::get('/v1/account/sessions/:sessionId') foreach ($sessions as $session) {/** @var Document $session */ if ($sessionId == $session->getId()) { - $countryName = $locale->getText('countries.' . strtolower($session->getAttribute('countryCode')), $locale->getText('locale.country.unknown')); + $countryName = $locale->getText('countries.'.strtolower($session->getAttribute('countryCode')), $locale->getText('locale.country.unknown')); $session ->setAttribute('current', ($session->getAttribute('secret') == Auth::hash(Auth::$secret))) ->setAttribute('countryName', $countryName) - ->setAttribute('expire', DateTime::addSeconds(new \DateTime($session->getCreatedAt()), $authDuration)) - ; + ->setAttribute('expire', DateTime::addSeconds(new \DateTime($session->getCreatedAt()), $authDuration)); return $response->dynamic($session, Response::MODEL_SESSION); } @@ -1521,7 +1480,6 @@ App::patch('/v1/account/name') ->inject('dbForProject') ->inject('events') ->action(function (string $name, Response $response, Document $user, Database $dbForProject, Event $events) { - $user = $dbForProject->updateDocument('users', $user->getId(), $user ->setAttribute('name', $name) ->setAttribute('search', implode(' ', [$user->getId(), $name, $user->getAttribute('email', ''), $user->getAttribute('phone', '')]))); @@ -1556,9 +1514,8 @@ App::patch('/v1/account/password') ->inject('dbForProject') ->inject('events') ->action(function (string $password, string $oldPassword, Response $response, Document $user, Database $dbForProject, Event $events) { - // Check old password only if its an existing user. - if (!empty($user->getAttribute('passwordUpdate')) && !Auth::passwordVerify($oldPassword, $user->getAttribute('password'), $user->getAttribute('hash'), $user->getAttribute('hashOptions'))) { // Double check user password + if (! empty($user->getAttribute('passwordUpdate')) && ! Auth::passwordVerify($oldPassword, $user->getAttribute('password'), $user->getAttribute('hash'), $user->getAttribute('hashOptions'))) { // Double check user password throw new Exception(Exception::USER_INVALID_CREDENTIALS); } @@ -1601,8 +1558,8 @@ App::patch('/v1/account/email') $isAnonymousUser = Auth::isAnonymousUser($user); // Check if request is from an anonymous account for converting if ( - !$isAnonymousUser && - !Auth::passwordVerify($password, $user->getAttribute('password'), $user->getAttribute('hash'), $user->getAttribute('hashOptions')) + ! $isAnonymousUser && + ! Auth::passwordVerify($password, $user->getAttribute('password'), $user->getAttribute('hash'), $user->getAttribute('hashOptions')) ) { // Double check user password throw new Exception(Exception::USER_INVALID_CREDENTIALS); } @@ -1653,12 +1610,11 @@ App::patch('/v1/account/phone') ->inject('dbForProject') ->inject('events') ->action(function (string $phone, string $password, Response $response, Document $user, Database $dbForProject, Event $events) { - $isAnonymousUser = Auth::isAnonymousUser($user); // Check if request is from an anonymous account for converting if ( - !$isAnonymousUser && - !Auth::passwordVerify($password, $user->getAttribute('password'), $user->getAttribute('hash'), $user->getAttribute('hashOptions')) + ! $isAnonymousUser && + ! Auth::passwordVerify($password, $user->getAttribute('password'), $user->getAttribute('hash'), $user->getAttribute('hashOptions')) ) { // Double check user password throw new Exception(Exception::USER_INVALID_CREDENTIALS); } @@ -1703,7 +1659,6 @@ App::patch('/v1/account/prefs') ->inject('dbForProject') ->inject('events') ->action(function (array $prefs, Response $response, Document $user, Database $dbForProject, Event $events) { - $user = $dbForProject->updateDocument('users', $user->getId(), $user->setAttribute('prefs', $prefs)); $events->setParam('userId', $user->getId()); @@ -1733,14 +1688,13 @@ App::patch('/v1/account/status') ->inject('dbForProject') ->inject('events') ->action(function (Request $request, Response $response, Document $user, Database $dbForProject, Event $events) { - $user = $dbForProject->updateDocument('users', $user->getId(), $user->setAttribute('status', false)); $events ->setParam('userId', $user->getId()) ->setPayload($response->output($user, Response::MODEL_ACCOUNT)); - if (!Config::getParam('domainVerification')) { + if (! Config::getParam('domainVerification')) { $response->addHeader('X-Fallback-Cookies', \json_encode([])); } @@ -1772,7 +1726,6 @@ App::delete('/v1/account/sessions/:sessionId') ->inject('events') ->inject('project') ->action(function (?string $sessionId, Request $request, Response $response, Document $user, Database $dbForProject, Locale $locale, Event $events, Document $project) { - $protocol = $request->getProtocol(); $authDuration = $project->getAttribute('auths', [])['duration'] ?? Auth::TOKEN_EXPIRATION_LOGIN_LONG; $sessionId = ($sessionId === 'current') @@ -1792,19 +1745,16 @@ App::delete('/v1/account/sessions/:sessionId') if ($session->getAttribute('secret') == Auth::hash(Auth::$secret)) { // If current session delete the cookies too $session ->setAttribute('current', true) - ->setAttribute('countryName', $locale->getText('countries.' . strtolower($session->getAttribute('countryCode')), $locale->getText('locale.country.unknown'))) - ; + ->setAttribute('countryName', $locale->getText('countries.'.strtolower($session->getAttribute('countryCode')), $locale->getText('locale.country.unknown'))); - if (!Config::getParam('domainVerification')) { + if (! Config::getParam('domainVerification')) { $response - ->addHeader('X-Fallback-Cookies', \json_encode([])) - ; + ->addHeader('X-Fallback-Cookies', \json_encode([])); } $response - ->addCookie(Auth::$cookieName . '_legacy', '', \time() - 3600, '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, null) - ->addCookie(Auth::$cookieName, '', \time() - 3600, '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, Config::getParam('cookieSamesite')) - ; + ->addCookie(Auth::$cookieName.'_legacy', '', \time() - 3600, '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, null) + ->addCookie(Auth::$cookieName, '', \time() - 3600, '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, Config::getParam('cookieSamesite')); } $dbForProject->deleteCachedDocument('users', $user->getId()); @@ -1812,8 +1762,8 @@ App::delete('/v1/account/sessions/:sessionId') $events ->setParam('userId', $user->getId()) ->setParam('sessionId', $session->getId()) - ->setPayload($response->output($session, Response::MODEL_SESSION)) - ; + ->setPayload($response->output($session, Response::MODEL_SESSION)); + return $response->noContent(); } } @@ -1868,12 +1818,12 @@ App::patch('/v1/account/sessions/:sessionId') $provider = $session->getAttribute('provider'); $refreshToken = $session->getAttribute('providerRefreshToken'); - $appId = $project->getAttribute('authProviders', [])[$provider . 'Appid'] ?? ''; - $appSecret = $project->getAttribute('authProviders', [])[$provider . 'Secret'] ?? '{}'; + $appId = $project->getAttribute('authProviders', [])[$provider.'Appid'] ?? ''; + $appSecret = $project->getAttribute('authProviders', [])[$provider.'Secret'] ?? '{}'; - $className = 'Appwrite\\Auth\\OAuth2\\' . \ucfirst($provider); + $className = 'Appwrite\\Auth\\OAuth2\\'.\ucfirst($provider); - if (!\class_exists($className)) { + if (! \class_exists($className)) { throw new Exception(Exception::PROJECT_PROVIDER_UNSUPPORTED); } @@ -1884,7 +1834,7 @@ App::patch('/v1/account/sessions/:sessionId') $session ->setAttribute('providerAccessToken', $oauth2->getAccessToken('')) ->setAttribute('providerRefreshToken', $oauth2->getRefreshToken('')) - ->setAttribute('providerAccessTokenExpiry', DateTime::addSeconds(new \DateTime(), (int)$oauth2->getAccessTokenExpiry(''))); + ->setAttribute('providerAccessTokenExpiry', DateTime::addSeconds(new \DateTime(), (int) $oauth2->getAccessTokenExpiry(''))); $dbForProject->updateDocument('sessions', $sessionId, $session); @@ -1897,8 +1847,7 @@ App::patch('/v1/account/sessions/:sessionId') $events ->setParam('userId', $user->getId()) ->setParam('sessionId', $session->getId()) - ->setPayload($response->output($session, Response::MODEL_SESSION)) - ; + ->setPayload($response->output($session, Response::MODEL_SESSION)); return $response->dynamic($session, Response::MODEL_SESSION); } @@ -1930,29 +1879,27 @@ App::delete('/v1/account/sessions') ->inject('locale') ->inject('events') ->action(function (Request $request, Response $response, Document $user, Database $dbForProject, Locale $locale, Event $events) { - $protocol = $request->getProtocol(); $sessions = $user->getAttribute('sessions', []); foreach ($sessions as $session) {/** @var Document $session */ $dbForProject->deleteDocument('sessions', $session->getId()); - if (!Config::getParam('domainVerification')) { + if (! Config::getParam('domainVerification')) { $response->addHeader('X-Fallback-Cookies', \json_encode([])); } $session ->setAttribute('current', false) - ->setAttribute('countryName', $locale->getText('countries.' . strtolower($session->getAttribute('countryCode')), $locale->getText('locale.country.unknown'))) - ; + ->setAttribute('countryName', $locale->getText('countries.'.strtolower($session->getAttribute('countryCode')), $locale->getText('locale.country.unknown'))); if ($session->getAttribute('secret') == Auth::hash(Auth::$secret)) { $session->setAttribute('current', true); $session->setAttribute('expire', DateTime::addSeconds(new \DateTime($session->getCreatedAt()), Auth::TOKEN_EXPIRATION_LOGIN_LONG)); - // If current session delete the cookies too + // If current session delete the cookies too $response - ->addCookie(Auth::$cookieName . '_legacy', '', \time() - 3600, '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, null) + ->addCookie(Auth::$cookieName.'_legacy', '', \time() - 3600, '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, null) ->addCookie(Auth::$cookieName, '', \time() - 3600, '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, Config::getParam('cookieSamesite')); // Use current session for events. @@ -1997,7 +1944,6 @@ App::post('/v1/account/recovery') ->inject('mails') ->inject('events') ->action(function (string $email, string $url, Request $request, Response $response, Database $dbForProject, Document $project, Locale $locale, Mail $mails, Event $events) { - if (empty(App::getEnv('_APP_SMTP_HOST'))) { throw new Exception(Exception::GENERAL_SMTP_DISABLED, 'SMTP Disabled'); } @@ -2012,7 +1958,7 @@ App::post('/v1/account/recovery') Query::equal('email', [$email]), ]); - if (!$profile) { + if (! $profile) { throw new Exception(Exception::USER_NOT_FOUND); } @@ -2051,18 +1997,18 @@ App::post('/v1/account/recovery') $projectName = $project->isEmpty() ? 'Console' : $project->getAttribute('name', '[APP-NAME]'); $from = $project->isEmpty() || $project->getId() === 'console' ? '' : \sprintf($locale->getText('emails.sender'), $projectName); - $body = Template::fromFile(__DIR__ . '/../../config/locale/templates/email-base.tpl'); - $subject = $locale->getText("emails.recovery.subject"); + $body = Template::fromFile(__DIR__.'/../../config/locale/templates/email-base.tpl'); + $subject = $locale->getText('emails.recovery.subject'); $body ->setParam('{{subject}}', $subject) - ->setParam('{{hello}}', $locale->getText("emails.recovery.hello")) + ->setParam('{{hello}}', $locale->getText('emails.recovery.hello')) ->setParam('{{name}}', $profile->getAttribute('name')) - ->setParam('{{body}}', $locale->getText("emails.recovery.body")) + ->setParam('{{body}}', $locale->getText('emails.recovery.body')) ->setParam('{{redirect}}', $url) - ->setParam('{{footer}}', $locale->getText("emails.recovery.footer")) - ->setParam('{{thanks}}', $locale->getText("emails.recovery.thanks")) - ->setParam('{{signature}}', $locale->getText("emails.recovery.signature")) + ->setParam('{{footer}}', $locale->getText('emails.recovery.footer')) + ->setParam('{{thanks}}', $locale->getText('emails.recovery.thanks')) + ->setParam('{{signature}}', $locale->getText('emails.recovery.signature')) ->setParam('{{project}}', $projectName) ->setParam('{{direction}}', $locale->getText('settings.direction')) ->setParam('{{bg-body}}', '#f7f7f7') @@ -2071,7 +2017,6 @@ App::post('/v1/account/recovery') $body = $body->render(); - $mails ->setRecipient($profile->getAttribute('email', '')) ->setName($profile->getAttribute('name')) @@ -2079,7 +2024,6 @@ App::post('/v1/account/recovery') ->setFrom($from) ->setSubject($subject) ->trigger(); - ; $events ->setParam('userId', $profile->getId()) @@ -2088,8 +2032,7 @@ App::post('/v1/account/recovery') ->setPayload($response->output( $recovery->setAttribute('secret', $secret), Response::MODEL_TOKEN - )) - ; + )); // Hide secret for clients $recovery->setAttribute('secret', ($isPrivilegedUser || $isAppUser) ? $secret : ''); @@ -2138,7 +2081,7 @@ App::put('/v1/account/recovery') $tokens = $profile->getAttribute('tokens', []); $recovery = Auth::tokenVerify($tokens, Auth::TOKEN_TYPE_RECOVERY, $secret); - if (!$recovery) { + if (! $recovery) { throw new Exception(Exception::USER_INVALID_TOKEN); } @@ -2162,8 +2105,7 @@ App::put('/v1/account/recovery') $events ->setParam('userId', $profile->getId()) - ->setParam('tokenId', $recoveryDocument->getId()) - ; + ->setParam('tokenId', $recoveryDocument->getId()); $response->dynamic($recoveryDocument, Response::MODEL_TOKEN); }); @@ -2186,7 +2128,7 @@ App::post('/v1/account/verification') ->label('sdk.response.model', Response::MODEL_TOKEN) ->label('abuse-limit', 10) ->label('abuse-key', 'url:{url},userId:{userId}') - ->param('url', '', fn($clients) => new Host($clients), 'URL to redirect the user back to your app from the verification email. Only URLs from hostnames in your project platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API.', false, ['clients']) // TODO add built-in confirm page + ->param('url', '', fn ($clients) => new Host($clients), 'URL to redirect the user back to your app from the verification email. Only URLs from hostnames in your project platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API.', false, ['clients']) // TODO add built-in confirm page ->inject('request') ->inject('response') ->inject('project') @@ -2196,7 +2138,6 @@ App::post('/v1/account/verification') ->inject('events') ->inject('mails') ->action(function (string $url, Request $request, Response $response, Document $project, Document $user, Database $dbForProject, Locale $locale, Event $events, Mail $mails) { - if (empty(App::getEnv('_APP_SMTP_HOST'))) { throw new Exception(Exception::GENERAL_SMTP_DISABLED, 'SMTP Disabled'); } @@ -2235,17 +2176,17 @@ App::post('/v1/account/verification') $projectName = $project->isEmpty() ? 'Console' : $project->getAttribute('name', '[APP-NAME]'); $from = $project->isEmpty() || $project->getId() === 'console' ? '' : \sprintf($locale->getText('emails.sender'), $projectName); - $body = Template::fromFile(__DIR__ . '/../../config/locale/templates/email-base.tpl'); - $subject = $locale->getText("emails.verification.subject"); + $body = Template::fromFile(__DIR__.'/../../config/locale/templates/email-base.tpl'); + $subject = $locale->getText('emails.verification.subject'); $body ->setParam('{{subject}}', $subject) - ->setParam('{{hello}}', $locale->getText("emails.verification.hello")) + ->setParam('{{hello}}', $locale->getText('emails.verification.hello')) ->setParam('{{name}}', $user->getAttribute('name')) - ->setParam('{{body}}', $locale->getText("emails.verification.body")) + ->setParam('{{body}}', $locale->getText('emails.verification.body')) ->setParam('{{redirect}}', $url) - ->setParam('{{footer}}', $locale->getText("emails.verification.footer")) - ->setParam('{{thanks}}', $locale->getText("emails.verification.thanks")) - ->setParam('{{signature}}', $locale->getText("emails.verification.signature")) + ->setParam('{{footer}}', $locale->getText('emails.verification.footer')) + ->setParam('{{thanks}}', $locale->getText('emails.verification.thanks')) + ->setParam('{{signature}}', $locale->getText('emails.verification.signature')) ->setParam('{{project}}', $projectName) ->setParam('{{direction}}', $locale->getText('settings.direction')) ->setParam('{{bg-body}}', '#f7f7f7') @@ -2260,8 +2201,7 @@ App::post('/v1/account/verification') ->setFrom($from) ->setRecipient($user->getAttribute('email')) ->setName($user->getAttribute('name')) - ->trigger() - ; + ->trigger(); $events ->setParam('userId', $user->getId()) @@ -2269,8 +2209,7 @@ App::post('/v1/account/verification') ->setPayload($response->output( $verification->setAttribute('secret', $verificationSecret), Response::MODEL_TOKEN - )) - ; + )); // Hide secret for clients $verification->setAttribute('secret', ($isPrivilegedUser || $isAppUser) ? $verificationSecret : ''); @@ -2305,8 +2244,7 @@ App::put('/v1/account/verification') ->inject('dbForProject') ->inject('events') ->action(function (string $userId, string $secret, Response $response, Document $user, Database $dbForProject, Event $events) { - - $profile = Authorization::skip(fn() => $dbForProject->getDocument('users', $userId)); + $profile = Authorization::skip(fn () => $dbForProject->getDocument('users', $userId)); if ($profile->isEmpty()) { throw new Exception(Exception::USER_NOT_FOUND); @@ -2315,7 +2253,7 @@ App::put('/v1/account/verification') $tokens = $profile->getAttribute('tokens', []); $verification = Auth::tokenVerify($tokens, Auth::TOKEN_TYPE_VERIFICATION, $secret); - if (!$verification) { + if (! $verification) { throw new Exception(Exception::USER_INVALID_TOKEN); } @@ -2334,8 +2272,7 @@ App::put('/v1/account/verification') $events ->setParam('userId', $user->getId()) - ->setParam('tokenId', $verificationDocument->getId()) - ; + ->setParam('tokenId', $verificationDocument->getId()); $response->dynamic($verificationDocument, Response::MODEL_TOKEN); }); @@ -2365,7 +2302,6 @@ App::post('/v1/account/verification/phone') ->inject('events') ->inject('messaging') ->action(function (Request $request, Response $response, Document $user, Database $dbForProject, Event $events, EventPhone $messaging) { - if (empty(App::getEnv('_APP_SMS_PROVIDER'))) { throw new Exception(Exception::GENERAL_PHONE_DISABLED); } @@ -2406,8 +2342,7 @@ App::post('/v1/account/verification/phone') $messaging ->setRecipient($user->getAttribute('phone')) ->setMessage($secret) - ->trigger() - ; + ->trigger(); $events ->setParam('userId', $user->getId()) @@ -2415,8 +2350,7 @@ App::post('/v1/account/verification/phone') ->setPayload($response->output( $verification->setAttribute('secret', $verificationSecret), Response::MODEL_TOKEN - )) - ; + )); // Hide secret for clients $verification->setAttribute('secret', ($isPrivilegedUser || $isAppUser) ? $verificationSecret : ''); @@ -2451,8 +2385,7 @@ App::put('/v1/account/verification/phone') ->inject('dbForProject') ->inject('events') ->action(function (string $userId, string $secret, Response $response, Document $user, Database $dbForProject, Event $events) { - - $profile = Authorization::skip(fn() => $dbForProject->getDocument('users', $userId)); + $profile = Authorization::skip(fn () => $dbForProject->getDocument('users', $userId)); if ($profile->isEmpty()) { throw new Exception(Exception::USER_NOT_FOUND); @@ -2460,7 +2393,7 @@ App::put('/v1/account/verification/phone') $verification = Auth::phoneTokenVerify($user->getAttribute('tokens', []), $secret); - if (!$verification) { + if (! $verification) { throw new Exception(Exception::USER_INVALID_TOKEN); } @@ -2478,8 +2411,7 @@ App::put('/v1/account/verification/phone') $events ->setParam('userId', $user->getId()) - ->setParam('tokenId', $verificationDocument->getId()) - ; + ->setParam('tokenId', $verificationDocument->getId()); $response->dynamic($verificationDocument, Response::MODEL_TOKEN); }); diff --git a/app/controllers/api/avatars.php b/app/controllers/api/avatars.php index 19daaea20d..88009b8403 100644 --- a/app/controllers/api/avatars.php +++ b/app/controllers/api/avatars.php @@ -1,7 +1,6 @@ output($output, $quality); $response - ->addHeader('Expires', \date('D, d M Y H:i:s', \time() + 60 * 60 * 24 * 30) . ' GMT') + ->addHeader('Expires', \date('D, d M Y H:i:s', \time() + 60 * 60 * 24 * 30).' GMT') ->setContentType('image/png') - ->file($data) - ; + ->file($data); unset($image); }; @@ -67,12 +65,12 @@ App::get('/v1/avatars/credit-cards/:code') ->label('sdk.description', '/docs/references/avatars/get-credit-card.md') ->label('sdk.response.code', Response::STATUS_CODE_OK) ->label('sdk.response.type', Response::CONTENT_TYPE_IMAGE_PNG) - ->param('code', '', new WhiteList(\array_keys(Config::getParam('avatar-credit-cards'))), 'Credit Card Code. Possible values: ' . \implode(', ', \array_keys(Config::getParam('avatar-credit-cards'))) . '.') + ->param('code', '', new WhiteList(\array_keys(Config::getParam('avatar-credit-cards'))), 'Credit Card Code. Possible values: '.\implode(', ', \array_keys(Config::getParam('avatar-credit-cards'))).'.') ->param('width', 100, new Range(0, 2000), 'Image width. Pass an integer between 0 to 2000. Defaults to 100.', true) ->param('height', 100, new Range(0, 2000), 'Image height. Pass an integer between 0 to 2000. Defaults to 100.', true) ->param('quality', 100, new Range(0, 100), 'Image quality. Pass an integer between 0 to 100. Defaults to 100.', true) ->inject('response') - ->action(fn (string $code, int $width, int $height, int $quality, Response $response) => $avatarCallback('credit-cards', $code, $width, $height, $quality, $response)); + ->action(fn (string $code, int $width, int $height, int $quality, Response $response) => $avatarCallback('credit-cards', $code, $width, $height, $quality, $response)); App::get('/v1/avatars/browsers/:code') ->desc('Get Browser Icon') @@ -132,18 +130,17 @@ App::get('/v1/avatars/image') ->param('height', 400, new Range(0, 2000), 'Resize preview image height, Pass an integer between 0 to 2000. Defaults to 400.', true) ->inject('response') ->action(function (string $url, int $width, int $height, Response $response) { - $quality = 80; $output = 'png'; $type = 'png'; - if (!\extension_loaded('imagick')) { + if (! \extension_loaded('imagick')) { throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Imagick extension is missing'); } $fetch = @\file_get_contents($url, false); - if (!$fetch) { + if (! $fetch) { throw new Exception(Exception::AVATAR_IMAGE_NOT_FOUND); } @@ -158,10 +155,9 @@ App::get('/v1/avatars/image') $data = $image->output($output, $quality); $response - ->addHeader('Expires', \date('D, d M Y H:i:s', \time() + 60 * 60 * 24 * 30) . ' GMT') + ->addHeader('Expires', \date('D, d M Y H:i:s', \time() + 60 * 60 * 24 * 30).' GMT') ->setContentType('image/png') - ->file($data) - ; + ->file($data); unset($image); }); @@ -181,14 +177,13 @@ App::get('/v1/avatars/favicon') ->param('url', '', new URL(['http', 'https']), 'Website URL which you want to fetch the favicon from.') ->inject('response') ->action(function (string $url, Response $response) { - $width = 56; $height = 56; $quality = 80; $output = 'png'; $type = 'png'; - if (!\extension_loaded('imagick')) { + if (! \extension_loaded('imagick')) { throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Imagick extension is missing'); } @@ -210,7 +205,7 @@ App::get('/v1/avatars/favicon') \curl_close($curl); - if (!$html) { + if (! $html) { throw new Exception(Exception::AVATAR_REMOTE_URL_FAILED); } @@ -261,7 +256,7 @@ App::get('/v1/avatars/favicon') if (empty($outputHref) || empty($outputExt)) { $default = \parse_url($url); - $outputHref = $default['scheme'] . '://' . $default['host'] . '/favicon.ico'; + $outputHref = $default['scheme'].'://'.$default['host'].'/favicon.ico'; $outputExt = 'ico'; } @@ -272,15 +267,14 @@ App::get('/v1/avatars/favicon') throw new Exception(Exception::AVATAR_ICON_NOT_FOUND, 'Favicon not found'); } $response - ->addHeader('Expires', \date('D, d M Y H:i:s', \time() + 60 * 60 * 24 * 30) . ' GMT') + ->addHeader('Expires', \date('D, d M Y H:i:s', \time() + 60 * 60 * 24 * 30).' GMT') ->setContentType('image/x-icon') - ->file($data) - ; + ->file($data); } $fetch = @\file_get_contents($outputHref, false); - if (!$fetch) { + if (! $fetch) { throw new Exception(Exception::AVATAR_ICON_NOT_FOUND); } @@ -290,10 +284,9 @@ App::get('/v1/avatars/favicon') $data = $image->output($output, $quality); $response - ->addHeader('Expires', \date('D, d M Y H:i:s', \time() + 60 * 60 * 24 * 30) . ' GMT') + ->addHeader('Expires', \date('D, d M Y H:i:s', \time() + 60 * 60 * 24 * 30).' GMT') ->setContentType('image/png') - ->file($data) - ; + ->file($data); unset($image); }); @@ -314,7 +307,6 @@ App::get('/v1/avatars/qr') ->param('download', false, new Boolean(true), 'Return resulting image with \'Content-Disposition: attachment \' headers for the browser to start downloading it. Pass 0 for no header, or 1 for otherwise. Default value is set to 0.', true) ->inject('response') ->action(function (string $text, int $size, int $margin, bool $download, Response $response) { - $download = ($download === '1' || $download === 'true' || $download === 1 || $download === true); $options = new QROptions([ 'addQuietzone' => true, @@ -332,10 +324,9 @@ App::get('/v1/avatars/qr') $image->crop((int) $size, (int) $size); $response - ->addHeader('Expires', \date('D, d M Y H:i:s', \time() + (60 * 60 * 24 * 45)) . ' GMT') // 45 days cache + ->addHeader('Expires', \date('D, d M Y H:i:s', \time() + (60 * 60 * 24 * 45)).' GMT') // 45 days cache ->setContentType('image/png') - ->send($image->output('png', 9)) - ; + ->send($image->output('png', 9)); }); App::get('/v1/avatars/initials') @@ -357,17 +348,16 @@ App::get('/v1/avatars/initials') ->inject('response') ->inject('user') ->action(function (string $name, int $width, int $height, string $background, Response $response, Document $user) { - $themes = [ ['background' => '#FFA1CE'], // Default (Pink) ['background' => '#FDC584'], // Orange ['background' => '#94DBD1'], // Green ['background' => '#A1C4FF'], // Blue ['background' => '#FFA1CE'], // Pink - ['background' => '#CBB1FC'] // Purple + ['background' => '#CBB1FC'], // Purple ]; - $name = (!empty($name)) ? $name : $user->getAttribute('name', $user->getAttribute('email', '')); + $name = (! empty($name)) ? $name : $user->getAttribute('name', $user->getAttribute('email', '')); $words = \explode(' ', \strtoupper($name)); // if there is no space, try to split by `_` underscore $words = (count($words) == 1) ? \explode('_', \strtoupper($name)) : $words; @@ -389,7 +379,7 @@ App::get('/v1/avatars/initials') // Wrap rand value to avoid out of range $rand = ($rand > \count($themes) - 1) ? $rand % \count($themes) : $rand; - $background = (!empty($background)) ? '#' . $background : $themes[$rand]['background']; + $background = (! empty($background)) ? '#'.$background : $themes[$rand]['background']; $image = new \Imagick(); $punch = new \Imagick(); @@ -398,8 +388,8 @@ App::get('/v1/avatars/initials') $punch->newImage($width, $height, 'transparent'); - $draw->setFont(__DIR__ . "/../../assets/fonts/poppins-v9-latin-500.ttf"); - $image->setFont(__DIR__ . "/../../assets/fonts/poppins-v9-latin-500.ttf"); + $draw->setFont(__DIR__.'/../../assets/fonts/poppins-v9-latin-500.ttf'); + $image->setFont(__DIR__.'/../../assets/fonts/poppins-v9-latin-500.ttf'); $draw->setFillColor(new ImagickPixel('black')); $draw->setFontSize($fontSize); @@ -411,14 +401,13 @@ App::get('/v1/avatars/initials') $punch->negateImage(true, Imagick::CHANNEL_ALPHA); $image->newImage($width, $height, $background); - $image->setImageFormat("png"); + $image->setImageFormat('png'); $image->compositeImage($punch, Imagick::COMPOSITE_COPYOPACITY, 0, 0); //$image->setImageCompressionQuality(9 - round(($quality / 100) * 9)); $response - ->addHeader('Expires', \date('D, d M Y H:i:s', \time() + (60 * 60 * 24 * 45)) . ' GMT') // 45 days cache + ->addHeader('Expires', \date('D, d M Y H:i:s', \time() + (60 * 60 * 24 * 45)).' GMT') // 45 days cache ->setContentType('image/png') - ->file($image->getImageBlob()) - ; + ->file($image->getImageBlob()); }); diff --git a/app/controllers/api/databases.php b/app/controllers/api/databases.php index 9ec46817ac..8e15026b91 100644 --- a/app/controllers/api/databases.php +++ b/app/controllers/api/databases.php @@ -1,59 +1,60 @@ getDocument('database_' . $db->getInternalId(), $collectionId); + $collection = $dbForProject->getDocument('database_'.$db->getInternalId(), $collectionId); if ($collection->isEmpty()) { throw new Exception(Exception::COLLECTION_NOT_FOUND); } - if (!empty($format)) { - if (!Structure::hasFormat($format, $type)) { + if (! empty($format)) { + if (! Structure::hasFormat($format, $type)) { throw new Exception(Exception::ATTRIBUTE_FORMAT_UNSUPPORTED, "Format {$format} not available for {$type} attributes."); } } @@ -98,7 +99,7 @@ function createAttribute(string $databaseId, string $collectionId, Document $att try { $attribute = new Document([ - '$id' => ID::custom($db->getInternalId() . '_' . $collection->getInternalId() . '_' . $key), + '$id' => ID::custom($db->getInternalId().'_'.$collection->getInternalId().'_'.$key), 'key' => $key, 'databaseInternalId' => $db->getInternalId(), 'databaseId' => $db->getId(), @@ -124,23 +125,21 @@ function createAttribute(string $databaseId, string $collectionId, Document $att throw new Exception(Exception::ATTRIBUTE_LIMIT_EXCEEDED, 'Attribute limit exceeded'); } - $dbForProject->deleteCachedDocument('database_' . $db->getInternalId(), $collectionId); - $dbForProject->deleteCachedCollection('database_' . $db->getInternalId() . '_collection_' . $collection->getInternalId()); + $dbForProject->deleteCachedDocument('database_'.$db->getInternalId(), $collectionId); + $dbForProject->deleteCachedCollection('database_'.$db->getInternalId().'_collection_'.$collection->getInternalId()); $database ->setType(DATABASE_TYPE_CREATE_ATTRIBUTE) ->setDatabase($db) ->setCollection($collection) - ->setDocument($attribute) - ; + ->setDocument($attribute); $events ->setContext('collection', $collection) ->setContext('database', $db) ->setParam('databaseId', $databaseId) ->setParam('collectionId', $collection->getId()) - ->setParam('attributeId', $attribute->getId()) - ; + ->setParam('attributeId', $attribute->getId()); $response->setStatusCode(Response::STATUS_CODE_CREATED); @@ -168,7 +167,6 @@ App::post('/v1/databases') ->inject('dbForProject') ->inject('events') ->action(function (string $databaseId, string $name, Response $response, Database $dbForProject, Event $events) { - $databaseId = $databaseId == 'unique()' ? ID::unique() : $databaseId; try { @@ -197,7 +195,7 @@ App::post('/v1/databases') 'array' => $attribute['array'], 'filters' => $attribute['filters'], 'default' => $attribute['default'] ?? null, - 'format' => $attribute['format'] ?? '' + 'format' => $attribute['format'] ?? '', ]); } @@ -210,7 +208,7 @@ App::post('/v1/databases') 'orders' => $index['orders'], ]); } - $dbForProject->createCollection('database_' . $database->getInternalId(), $attributes, $indexes); + $dbForProject->createCollection('database_'.$database->getInternalId(), $attributes, $indexes); } catch (DuplicateException $th) { throw new Exception(Exception::DATABASE_ALREADY_EXISTS); } @@ -234,15 +232,14 @@ App::get('/v1/databases') ->label('sdk.response.code', Response::STATUS_CODE_OK) ->label('sdk.response.type', Response::CONTENT_TYPE_JSON) ->label('sdk.response.model', Response::MODEL_DATABASE_LIST) - ->param('queries', [], new Databases(), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/databases#querying-documents). Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' queries are allowed, each ' . APP_LIMIT_ARRAY_ELEMENT_SIZE . ' characters long. You may filter on the following attributes: ' . implode(', ', Databases::ALLOWED_ATTRIBUTES), true) + ->param('queries', [], new Databases(), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/databases#querying-documents). Maximum of '.APP_LIMIT_ARRAY_PARAMS_SIZE.' queries are allowed, each '.APP_LIMIT_ARRAY_ELEMENT_SIZE.' characters long. You may filter on the following attributes: '.implode(', ', Databases::ALLOWED_ATTRIBUTES), true) ->param('search', '', new Text(256), 'Search term to filter your list results. Max length: 256 chars.', true) ->inject('response') ->inject('dbForProject') ->action(function (array $queries, string $search, Response $response, Database $dbForProject) { - $queries = Query::parseQueries($queries); - if (!empty($search)) { + if (! empty($search)) { $queries[] = Query::search('search', $search); } @@ -285,8 +282,7 @@ App::get('/v1/databases/:databaseId') ->inject('response') ->inject('dbForProject') ->action(function (string $databaseId, Response $response, Database $dbForProject) { - - $database = $dbForProject->getDocument('databases', $databaseId); + $database = $dbForProject->getDocument('databases', $databaseId); if ($database->isEmpty()) { throw new Exception(Exception::DATABASE_NOT_FOUND); @@ -313,7 +309,6 @@ App::get('/v1/databases/:databaseId/logs') ->inject('locale') ->inject('geodb') ->action(function (string $databaseId, array $queries, Response $response, Database $dbForProject, Locale $locale, Reader $geodb) { - $database = $dbForProject->getDocument('databases', $databaseId); if ($database->isEmpty()) { @@ -326,13 +321,13 @@ App::get('/v1/databases/:databaseId/logs') $offset = $grouped['offset'] ?? 0; $audit = new Audit($dbForProject); - $resource = 'database/' . $databaseId; + $resource = 'database/'.$databaseId; $logs = $audit->getLogsByResource($resource, $limit, $offset); $output = []; foreach ($logs as $i => &$log) { - $log['userAgent'] = (!empty($log['userAgent'])) ? $log['userAgent'] : 'UNKNOWN'; + $log['userAgent'] = (! empty($log['userAgent'])) ? $log['userAgent'] : 'UNKNOWN'; $detector = new Detector($log['userAgent']); $detector->skipBotDetection(); // OPTIONAL: If called, bot detection will completely be skipped (bots will be detected as regular devices then) @@ -360,14 +355,14 @@ App::get('/v1/databases/:databaseId/logs') 'clientEngineVersion' => $client['clientEngineVersion'], 'deviceName' => $device['deviceName'], 'deviceBrand' => $device['deviceBrand'], - 'deviceModel' => $device['deviceModel'] + 'deviceModel' => $device['deviceModel'], ]); $record = $geodb->get($log['ip']); if ($record) { - $output[$i]['countryCode'] = $locale->getText('countries.' . strtolower($record['country']['iso_code']), false) ? \strtolower($record['country']['iso_code']) : '--'; - $output[$i]['countryName'] = $locale->getText('countries.' . strtolower($record['country']['iso_code']), $locale->getText('locale.country.unknown')); + $output[$i]['countryCode'] = $locale->getText('countries.'.strtolower($record['country']['iso_code']), false) ? \strtolower($record['country']['iso_code']) : '--'; + $output[$i]['countryName'] = $locale->getText('countries.'.strtolower($record['country']['iso_code']), $locale->getText('locale.country.unknown')); } else { $output[$i]['countryCode'] = '--'; $output[$i]['countryName'] = $locale->getText('locale.country.unknown'); @@ -380,7 +375,6 @@ App::get('/v1/databases/:databaseId/logs') ]), Response::MODEL_LOG_LIST); }); - App::put('/v1/databases/:databaseId') ->desc('Update Database') ->groups(['api', 'database', 'schema']) @@ -402,8 +396,7 @@ App::put('/v1/databases/:databaseId') ->inject('dbForProject') ->inject('events') ->action(function (string $databaseId, string $name, Response $response, Database $dbForProject, Event $events) { - - $database = $dbForProject->getDocument('databases', $databaseId); + $database = $dbForProject->getDocument('databases', $databaseId); if ($database->isEmpty()) { throw new Exception(Exception::DATABASE_NOT_FOUND); @@ -416,7 +409,7 @@ App::put('/v1/databases/:databaseId') } catch (AuthorizationException $exception) { throw new Exception(Exception::USER_UNAUTHORIZED); } catch (StructureException $exception) { - throw new Exception(Exception::DOCUMENT_INVALID_STRUCTURE, 'Bad structure. ' . $exception->getMessage()); + throw new Exception(Exception::DOCUMENT_INVALID_STRUCTURE, 'Bad structure. '.$exception->getMessage()); } $events->setParam('databaseId', $database->getId()); @@ -444,28 +437,25 @@ App::delete('/v1/databases/:databaseId') ->inject('events') ->inject('deletes') ->action(function (string $databaseId, Response $response, Database $dbForProject, Event $events, Delete $deletes) { - $database = $dbForProject->getDocument('databases', $databaseId); if ($database->isEmpty()) { throw new Exception(Exception::DATABASE_NOT_FOUND); } - if (!$dbForProject->deleteDocument('databases', $databaseId)) { + if (! $dbForProject->deleteDocument('databases', $databaseId)) { throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Failed to remove collection from DB'); } - $dbForProject->deleteCachedCollection('databases' . $database->getInternalId()); + $dbForProject->deleteCachedCollection('databases'.$database->getInternalId()); $deletes ->setType(DELETE_TYPE_DOCUMENT) - ->setDocument($database) - ; + ->setDocument($database); $events ->setParam('databaseId', $database->getId()) - ->setPayload($response->output($database, Response::MODEL_DATABASE)) - ; + ->setPayload($response->output($database, Response::MODEL_DATABASE)); $response->noContent(); }); @@ -496,7 +486,6 @@ App::post('/v1/databases/:databaseId/collections') ->inject('dbForProject') ->inject('events') ->action(function (string $databaseId, string $collectionId, string $name, ?array $permissions, bool $documentSecurity, Response $response, Database $dbForProject, Event $events) { - $database = Authorization::skip(fn () => $dbForProject->getDocument('databases', $databaseId)); if ($database->isEmpty()) { @@ -509,7 +498,7 @@ App::post('/v1/databases/:databaseId/collections') $permissions = Permission::aggregate($permissions); try { - $dbForProject->createDocument('database_' . $database->getInternalId(), new Document([ + $dbForProject->createDocument('database_'.$database->getInternalId(), new Document([ '$id' => $collectionId, 'databaseInternalId' => $database->getInternalId(), 'databaseId' => $databaseId, @@ -519,9 +508,9 @@ App::post('/v1/databases/:databaseId/collections') 'name' => $name, 'search' => implode(' ', [$collectionId, $name]), ])); - $collection = $dbForProject->getDocument('database_' . $database->getInternalId(), $collectionId); + $collection = $dbForProject->getDocument('database_'.$database->getInternalId(), $collectionId); - $dbForProject->createCollection('database_' . $database->getInternalId() . '_collection_' . $collection->getInternalId()); + $dbForProject->createCollection('database_'.$database->getInternalId().'_collection_'.$collection->getInternalId()); } catch (DuplicateException) { throw new Exception(Exception::COLLECTION_ALREADY_EXISTS); } catch (LimitException) { @@ -553,12 +542,11 @@ App::get('/v1/databases/:databaseId/collections') ->label('sdk.response.type', Response::CONTENT_TYPE_JSON) ->label('sdk.response.model', Response::MODEL_COLLECTION_LIST) ->param('databaseId', '', new UID(), 'Database ID.') - ->param('queries', [], new Collections(), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/databases#querying-documents). Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' queries are allowed, each ' . APP_LIMIT_ARRAY_ELEMENT_SIZE . ' characters long. You may filter on the following attributes: ' . implode(', ', Collections::ALLOWED_ATTRIBUTES), true) + ->param('queries', [], new Collections(), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/databases#querying-documents). Maximum of '.APP_LIMIT_ARRAY_PARAMS_SIZE.' queries are allowed, each '.APP_LIMIT_ARRAY_ELEMENT_SIZE.' characters long. You may filter on the following attributes: '.implode(', ', Collections::ALLOWED_ATTRIBUTES), true) ->param('search', '', new Text(256), 'Search term to filter your list results. Max length: 256 chars.', true) ->inject('response') ->inject('dbForProject') ->action(function (string $databaseId, array $queries, string $search, Response $response, Database $dbForProject) { - $database = Authorization::skip(fn () => $dbForProject->getDocument('databases', $databaseId)); if ($database->isEmpty()) { @@ -567,7 +555,7 @@ App::get('/v1/databases/:databaseId/collections') $queries = Query::parseQueries($queries); - if (!empty($search)) { + if (! empty($search)) { $queries[] = Query::search('search', $search); } @@ -577,7 +565,7 @@ App::get('/v1/databases/:databaseId/collections') if ($cursor) { /** @var Query $cursor */ $collectionId = $cursor->getValue(); - $cursorDocument = $dbForProject->getDocument('database_' . $database->getInternalId(), $collectionId); + $cursorDocument = $dbForProject->getDocument('database_'.$database->getInternalId(), $collectionId); if ($cursorDocument->isEmpty()) { throw new Exception(Exception::GENERAL_CURSOR_NOT_FOUND, "Collection '{$collectionId}' for the 'cursor' value not found."); @@ -589,8 +577,8 @@ App::get('/v1/databases/:databaseId/collections') $filterQueries = Query::groupByType($queries)['filters']; $response->dynamic(new Document([ - 'collections' => $dbForProject->find('database_' . $database->getInternalId(), $queries), - 'total' => $dbForProject->count('database_' . $database->getInternalId(), $filterQueries, APP_LIMIT_COUNT), + 'collections' => $dbForProject->find('database_'.$database->getInternalId(), $queries), + 'total' => $dbForProject->count('database_'.$database->getInternalId(), $filterQueries, APP_LIMIT_COUNT), ]), Response::MODEL_COLLECTION_LIST); }); @@ -613,14 +601,13 @@ App::get('/v1/databases/:databaseId/collections/:collectionId') ->inject('response') ->inject('dbForProject') ->action(function (string $databaseId, string $collectionId, Response $response, Database $dbForProject) { - $database = Authorization::skip(fn () => $dbForProject->getDocument('databases', $databaseId)); if ($database->isEmpty()) { throw new Exception(Exception::DATABASE_NOT_FOUND); } - $collection = $dbForProject->getDocument('database_' . $database->getInternalId(), $collectionId); + $collection = $dbForProject->getDocument('database_'.$database->getInternalId(), $collectionId); if ($collection->isEmpty()) { throw new Exception(Exception::COLLECTION_NOT_FOUND); @@ -651,14 +638,13 @@ App::get('/v1/databases/:databaseId/collections/:collectionId/logs') ->inject('locale') ->inject('geodb') ->action(function (string $databaseId, string $collectionId, array $queries, Response $response, Database $dbForProject, Locale $locale, Reader $geodb) { - $database = Authorization::skip(fn () => $dbForProject->getDocument('databases', $databaseId)); if ($database->isEmpty()) { throw new Exception(Exception::DATABASE_NOT_FOUND); } - $collectionDocument = $dbForProject->getDocument('database_' . $database->getInternalId(), $collectionId); - $collection = $dbForProject->getCollection('database_' . $database->getInternalId() . '_collection_' . $collectionDocument->getInternalId()); + $collectionDocument = $dbForProject->getDocument('database_'.$database->getInternalId(), $collectionId); + $collection = $dbForProject->getCollection('database_'.$database->getInternalId().'_collection_'.$collectionDocument->getInternalId()); if ($collection->isEmpty()) { throw new Exception(Exception::COLLECTION_NOT_FOUND); @@ -670,13 +656,13 @@ App::get('/v1/databases/:databaseId/collections/:collectionId/logs') $offset = $grouped['offset'] ?? 0; $audit = new Audit($dbForProject); - $resource = 'database/' . $databaseId . '/collection/' . $collectionId; + $resource = 'database/'.$databaseId.'/collection/'.$collectionId; $logs = $audit->getLogsByResource($resource, $limit, $offset); $output = []; foreach ($logs as $i => &$log) { - $log['userAgent'] = (!empty($log['userAgent'])) ? $log['userAgent'] : 'UNKNOWN'; + $log['userAgent'] = (! empty($log['userAgent'])) ? $log['userAgent'] : 'UNKNOWN'; $detector = new Detector($log['userAgent']); $detector->skipBotDetection(); // OPTIONAL: If called, bot detection will completely be skipped (bots will be detected as regular devices then) @@ -704,14 +690,14 @@ App::get('/v1/databases/:databaseId/collections/:collectionId/logs') 'clientEngineVersion' => $client['clientEngineVersion'], 'deviceName' => $device['deviceName'], 'deviceBrand' => $device['deviceBrand'], - 'deviceModel' => $device['deviceModel'] + 'deviceModel' => $device['deviceModel'], ]); $record = $geodb->get($log['ip']); if ($record) { - $output[$i]['countryCode'] = $locale->getText('countries.' . strtolower($record['country']['iso_code']), false) ? \strtolower($record['country']['iso_code']) : '--'; - $output[$i]['countryName'] = $locale->getText('countries.' . strtolower($record['country']['iso_code']), $locale->getText('locale.country.unknown')); + $output[$i]['countryCode'] = $locale->getText('countries.'.strtolower($record['country']['iso_code']), false) ? \strtolower($record['country']['iso_code']) : '--'; + $output[$i]['countryName'] = $locale->getText('countries.'.strtolower($record['country']['iso_code']), $locale->getText('locale.country.unknown')); } else { $output[$i]['countryCode'] = '--'; $output[$i]['countryName'] = $locale->getText('locale.country.unknown'); @@ -724,7 +710,6 @@ App::get('/v1/databases/:databaseId/collections/:collectionId/logs') ]), Response::MODEL_LOG_LIST); }); - App::put('/v1/databases/:databaseId/collections/:collectionId') ->alias('/v1/database/collections/:collectionId', ['databaseId' => 'default']) ->desc('Update Collection') @@ -752,14 +737,13 @@ App::put('/v1/databases/:databaseId/collections/:collectionId') ->inject('dbForProject') ->inject('events') ->action(function (string $databaseId, string $collectionId, string $name, ?array $permissions, bool $documentSecurity, bool $enabled, Response $response, Database $dbForProject, Event $events) { - $database = Authorization::skip(fn () => $dbForProject->getDocument('databases', $databaseId)); if ($database->isEmpty()) { throw new Exception(Exception::DATABASE_NOT_FOUND); } - $collection = $dbForProject->getDocument('database_' . $database->getInternalId(), $collectionId); + $collection = $dbForProject->getDocument('database_'.$database->getInternalId(), $collectionId); if ($collection->isEmpty()) { throw new Exception(Exception::COLLECTION_NOT_FOUND); @@ -773,7 +757,7 @@ App::put('/v1/databases/:databaseId/collections/:collectionId') $enabled ??= $collection->getAttribute('enabled', true); try { - $collection = $dbForProject->updateDocument('database_' . $database->getInternalId(), $collectionId, $collection + $collection = $dbForProject->updateDocument('database_'.$database->getInternalId(), $collectionId, $collection ->setAttribute('name', $name) ->setAttribute('$permissions', $permissions) ->setAttribute('documentSecurity', $documentSecurity) @@ -782,7 +766,7 @@ App::put('/v1/databases/:databaseId/collections/:collectionId') } catch (AuthorizationException) { throw new Exception(Exception::USER_UNAUTHORIZED); } catch (StructureException $exception) { - throw new Exception(Exception::DOCUMENT_INVALID_STRUCTURE, 'Bad structure. ' . $exception->getMessage()); + throw new Exception(Exception::DOCUMENT_INVALID_STRUCTURE, 'Bad structure. '.$exception->getMessage()); } $events @@ -816,36 +800,33 @@ App::delete('/v1/databases/:databaseId/collections/:collectionId') ->inject('events') ->inject('deletes') ->action(function (string $databaseId, string $collectionId, Response $response, Database $dbForProject, Event $events, Delete $deletes) { - $database = Authorization::skip(fn () => $dbForProject->getDocument('databases', $databaseId)); if ($database->isEmpty()) { throw new Exception(Exception::DATABASE_NOT_FOUND); } - $collection = $dbForProject->getDocument('database_' . $database->getInternalId(), $collectionId); + $collection = $dbForProject->getDocument('database_'.$database->getInternalId(), $collectionId); if ($collection->isEmpty()) { throw new Exception(Exception::COLLECTION_NOT_FOUND); } - if (!$dbForProject->deleteDocument('database_' . $database->getInternalId(), $collectionId)) { + if (! $dbForProject->deleteDocument('database_'.$database->getInternalId(), $collectionId)) { throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Failed to remove collection from DB'); } - $dbForProject->deleteCachedCollection('database_' . $database->getInternalId() . '_collection_' . $collection->getInternalId()); + $dbForProject->deleteCachedCollection('database_'.$database->getInternalId().'_collection_'.$collection->getInternalId()); $deletes ->setType(DELETE_TYPE_DOCUMENT) - ->setDocument($collection) - ; + ->setDocument($collection); $events ->setContext('database', $database) ->setParam('databaseId', $databaseId) ->setParam('collectionId', $collection->getId()) - ->setPayload($response->output($collection, Response::MODEL_COLLECTION)) - ; + ->setPayload($response->output($collection, Response::MODEL_COLLECTION)); $response->noContent(); }); @@ -879,10 +860,9 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/attributes/string ->inject('database') ->inject('events') ->action(function (string $databaseId, string $collectionId, string $key, ?int $size, ?bool $required, ?string $default, bool $array, Response $response, Database $dbForProject, EventDatabase $database, Event $events) { - // Ensure attribute default is within required size $validator = new Text($size); - if (!is_null($default) && !$validator->isValid($default)) { + if (! is_null($default) && ! $validator->isValid($default)) { throw new Exception(Exception::ATTRIBUTE_VALUE_INVALID, $validator->getDescription()); } @@ -928,7 +908,6 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/attributes/email' ->inject('database') ->inject('events') ->action(function (string $databaseId, string $collectionId, string $key, ?bool $required, ?string $default, bool $array, Response $response, Database $dbForProject, EventDatabase $database, Event $events) { - $attribute = createAttribute($databaseId, $collectionId, new Document([ 'key' => $key, 'type' => Database::VAR_STRING, @@ -964,7 +943,7 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/attributes/enum') ->param('databaseId', '', new UID(), 'Database ID.') ->param('collectionId', '', new UID(), 'Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection).') ->param('key', '', new Key(), 'Attribute Key.') - ->param('elements', [], new ArrayList(new Text(APP_LIMIT_ARRAY_ELEMENT_SIZE), APP_LIMIT_ARRAY_PARAMS_SIZE), 'Array of elements in enumerated type. Uses length of longest element to determine size. Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' elements are allowed, each ' . APP_LIMIT_ARRAY_ELEMENT_SIZE . ' characters long.') + ->param('elements', [], new ArrayList(new Text(APP_LIMIT_ARRAY_ELEMENT_SIZE), APP_LIMIT_ARRAY_PARAMS_SIZE), 'Array of elements in enumerated type. Uses length of longest element to determine size. Maximum of '.APP_LIMIT_ARRAY_PARAMS_SIZE.' elements are allowed, each '.APP_LIMIT_ARRAY_ELEMENT_SIZE.' characters long.') ->param('required', null, new Boolean(), 'Is attribute required?') ->param('default', null, new Text(0), 'Default value for attribute when not provided. Cannot be set when attribute is required.', true) ->param('array', false, new Boolean(), 'Is attribute an array?', true) @@ -973,7 +952,6 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/attributes/enum') ->inject('database') ->inject('events') ->action(function (string $databaseId, string $collectionId, string $key, array $elements, ?bool $required, ?string $default, bool $array, Response $response, Database $dbForProject, EventDatabase $database, Event $events) { - // use length of longest string as attribute size $size = 0; foreach ($elements as $element) { @@ -984,7 +962,7 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/attributes/enum') $size = ($length > $size) ? $length : $size; } - if (!is_null($default) && !in_array($default, $elements)) { + if (! is_null($default) && ! in_array($default, $elements)) { throw new Exception(Exception::ATTRIBUTE_VALUE_INVALID, 'Default value not found in elements'); } @@ -1032,7 +1010,6 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/attributes/ip') ->inject('database') ->inject('events') ->action(function (string $databaseId, string $collectionId, string $key, ?bool $required, ?string $default, bool $array, Response $response, Database $dbForProject, EventDatabase $database, Event $events) { - $attribute = createAttribute($databaseId, $collectionId, new Document([ 'key' => $key, 'type' => Database::VAR_STRING, @@ -1076,7 +1053,6 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/attributes/url') ->inject('database') ->inject('events') ->action(function (string $databaseId, string $collectionId, string $key, ?bool $required, ?string $default, bool $array, Response $response, Database $dbForProject, EventDatabase $database, Event $events) { - $attribute = createAttribute($databaseId, $collectionId, new Document([ 'key' => $key, 'type' => Database::VAR_STRING, @@ -1122,7 +1098,6 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/attributes/intege ->inject('database') ->inject('events') ->action(function (string $databaseId, string $collectionId, string $key, ?bool $required, ?int $min, ?int $max, ?int $default, bool $array, Response $response, Database $dbForProject, EventDatabase $database, Event $events) { - // Ensure attribute default is within range $min = (is_null($min)) ? PHP_INT_MIN : \intval($min); $max = (is_null($max)) ? PHP_INT_MAX : \intval($max); @@ -1133,7 +1108,7 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/attributes/intege $validator = new Range($min, $max, Database::VAR_INTEGER); - if (!is_null($default) && !$validator->isValid($default)) { + if (! is_null($default) && ! $validator->isValid($default)) { throw new Exception(Exception::ATTRIBUTE_VALUE_INVALID, $validator->getDescription()); } @@ -1155,7 +1130,7 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/attributes/intege $formatOptions = $attribute->getAttribute('formatOptions', []); - if (!empty($formatOptions)) { + if (! empty($formatOptions)) { $attribute->setAttribute('min', \intval($formatOptions['min'])); $attribute->setAttribute('max', \intval($formatOptions['max'])); } @@ -1195,7 +1170,6 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/attributes/float' ->inject('database') ->inject('events') ->action(function (string $databaseId, string $collectionId, string $key, ?bool $required, ?float $min, ?float $max, ?float $default, bool $array, Response $response, Database $dbForProject, EventDatabase $database, Event $events) { - // Ensure attribute default is within range $min = (is_null($min)) ? -PHP_FLOAT_MAX : \floatval($min); $max = (is_null($max)) ? PHP_FLOAT_MAX : \floatval($max); @@ -1205,13 +1179,13 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/attributes/float' } // Ensure default value is a float - if (!is_null($default)) { + if (! is_null($default)) { $default = \floatval($default); } $validator = new Range($min, $max, Database::VAR_FLOAT); - if (!is_null($default) && !$validator->isValid($default)) { + if (! is_null($default) && ! $validator->isValid($default)) { throw new Exception(Exception::ATTRIBUTE_VALUE_INVALID, $validator->getDescription()); } @@ -1231,7 +1205,7 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/attributes/float' $formatOptions = $attribute->getAttribute('formatOptions', []); - if (!empty($formatOptions)) { + if (! empty($formatOptions)) { $attribute->setAttribute('min', \floatval($formatOptions['min'])); $attribute->setAttribute('max', \floatval($formatOptions['max'])); } @@ -1269,7 +1243,6 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/attributes/boolea ->inject('database') ->inject('events') ->action(function (string $databaseId, string $collectionId, string $key, ?bool $required, ?bool $default, bool $array, Response $response, Database $dbForProject, EventDatabase $database, Event $events) { - $attribute = createAttribute($databaseId, $collectionId, new Document([ 'key' => $key, 'type' => Database::VAR_BOOLEAN, @@ -1284,7 +1257,6 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/attributes/boolea ->dynamic($attribute, Response::MODEL_ATTRIBUTE_BOOLEAN); }); - App::post('/v1/databases/:databaseId/collections/:collectionId/attributes/datetime') ->alias('/v1/database/collections/:collectionId/attributes/datetime', ['databaseId' => 'default']) ->desc('Create DateTime Attribute') @@ -1313,7 +1285,6 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/attributes/dateti ->inject('database') ->inject('events') ->action(function (string $databaseId, string $collectionId, string $key, ?bool $required, ?string $default, bool $array, Response $response, Database $dbForProject, EventDatabase $database, Event $events) { - $attribute = createAttribute($databaseId, $collectionId, new Document([ 'key' => $key, 'type' => Database::VAR_DATETIME, @@ -1321,7 +1292,7 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/attributes/dateti 'required' => $required, 'default' => $default, 'array' => $array, - 'filters' => ['datetime'] + 'filters' => ['datetime'], ]), $response, $dbForProject, $database, $events); $response @@ -1329,7 +1300,6 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/attributes/dateti ->dynamic($attribute, Response::MODEL_ATTRIBUTE_DATETIME); }); - App::get('/v1/databases/:databaseId/collections/:collectionId/attributes') ->alias('/v1/database/collections/:collectionId/attributes', ['databaseId' => 'default']) ->desc('List Attributes') @@ -1349,13 +1319,12 @@ App::get('/v1/databases/:databaseId/collections/:collectionId/attributes') ->inject('response') ->inject('dbForProject') ->action(function (string $databaseId, string $collectionId, Response $response, Database $dbForProject) { - $database = Authorization::skip(fn () => $dbForProject->getDocument('databases', $databaseId)); if ($database->isEmpty()) { throw new Exception(Exception::DATABASE_NOT_FOUND); } - $collection = $dbForProject->getDocument('database_' . $database->getInternalId(), $collectionId); + $collection = $dbForProject->getDocument('database_'.$database->getInternalId(), $collectionId); if ($collection->isEmpty()) { throw new Exception(Exception::COLLECTION_NOT_FOUND); @@ -1365,7 +1334,7 @@ App::get('/v1/databases/:databaseId/collections/:collectionId/attributes') $response->dynamic(new Document([ 'total' => \count($attributes), - 'attributes' => $attributes + 'attributes' => $attributes, ]), Response::MODEL_ATTRIBUTE_LIST); }); @@ -1392,27 +1361,26 @@ App::get('/v1/databases/:databaseId/collections/:collectionId/attributes/:key') Response::MODEL_ATTRIBUTE_URL, Response::MODEL_ATTRIBUTE_IP, Response::MODEL_ATTRIBUTE_DATETIME, - Response::MODEL_ATTRIBUTE_STRING])// needs to be last, since its condition would dominate any other string attribute + Response::MODEL_ATTRIBUTE_STRING, ])// needs to be last, since its condition would dominate any other string attribute ->param('databaseId', '', new UID(), 'Database ID.') ->param('collectionId', '', new UID(), 'Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection).') ->param('key', '', new Key(), 'Attribute Key.') ->inject('response') ->inject('dbForProject') ->action(function (string $databaseId, string $collectionId, string $key, Response $response, Database $dbForProject) { - $database = Authorization::skip(fn () => $dbForProject->getDocument('databases', $databaseId)); if ($database->isEmpty()) { throw new Exception(Exception::DATABASE_NOT_FOUND); } - $collection = $dbForProject->getDocument('database_' . $database->getInternalId(), $collectionId); + $collection = $dbForProject->getDocument('database_'.$database->getInternalId(), $collectionId); if ($collection->isEmpty()) { throw new Exception(Exception::COLLECTION_NOT_FOUND); } - $attribute = $dbForProject->getDocument('attributes', $database->getInternalId() . '_' . $collection->getInternalId() . '_' . $key); + $attribute = $dbForProject->getDocument('attributes', $database->getInternalId().'_'.$collection->getInternalId().'_'.$key); if ($attribute->isEmpty()) { throw new Exception(Exception::ATTRIBUTE_NOT_FOUND); @@ -1464,19 +1432,18 @@ App::delete('/v1/databases/:databaseId/collections/:collectionId/attributes/:key ->inject('database') ->inject('events') ->action(function (string $databaseId, string $collectionId, string $key, Response $response, Database $dbForProject, EventDatabase $database, Event $events) { - $db = Authorization::skip(fn () => $dbForProject->getDocument('databases', $databaseId)); if ($db->isEmpty()) { throw new Exception(Exception::DATABASE_NOT_FOUND); } - $collection = $dbForProject->getDocument('database_' . $db->getInternalId(), $collectionId); + $collection = $dbForProject->getDocument('database_'.$db->getInternalId(), $collectionId); if ($collection->isEmpty()) { throw new Exception(Exception::COLLECTION_NOT_FOUND); } - $attribute = $dbForProject->getDocument('attributes', $db->getInternalId() . '_' . $collection->getInternalId() . '_' . $key); + $attribute = $dbForProject->getDocument('attributes', $db->getInternalId().'_'.$collection->getInternalId().'_'.$key); if ($attribute->isEmpty()) { throw new Exception(Exception::ATTRIBUTE_NOT_FOUND); @@ -1487,15 +1454,14 @@ App::delete('/v1/databases/:databaseId/collections/:collectionId/attributes/:key $attribute = $dbForProject->updateDocument('attributes', $attribute->getId(), $attribute->setAttribute('status', 'deleting')); } - $dbForProject->deleteCachedDocument('database_' . $db->getInternalId(), $collectionId); - $dbForProject->deleteCachedCollection('database_' . $db->getInternalId() . '_collection_' . $collection->getInternalId()); + $dbForProject->deleteCachedDocument('database_'.$db->getInternalId(), $collectionId); + $dbForProject->deleteCachedCollection('database_'.$db->getInternalId().'_collection_'.$collection->getInternalId()); $database ->setType(DATABASE_TYPE_DELETE_ATTRIBUTE) ->setCollection($collection) ->setDatabase($db) - ->setDocument($attribute) - ; + ->setDocument($attribute); // Select response model based on type and format $type = $attribute->getAttribute('type'); @@ -1522,8 +1488,7 @@ App::delete('/v1/databases/:databaseId/collections/:collectionId/attributes/:key ->setParam('attributeId', $attribute->getId()) ->setContext('collection', $collection) ->setContext('database', $db) - ->setPayload($response->output($attribute, $model)) - ; + ->setPayload($response->output($attribute, $model)); $response->noContent(); }); @@ -1549,20 +1514,19 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/indexes') ->param('collectionId', '', new UID(), 'Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection).') ->param('key', null, new Key(), 'Index Key.') ->param('type', null, new WhiteList([Database::INDEX_KEY, Database::INDEX_FULLTEXT, Database::INDEX_UNIQUE, Database::INDEX_SPATIAL, Database::INDEX_ARRAY]), 'Index type.') - ->param('attributes', null, new ArrayList(new Key(true), APP_LIMIT_ARRAY_PARAMS_SIZE), 'Array of attributes to index. Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' attributes are allowed, each 32 characters long.') - ->param('orders', [], new ArrayList(new WhiteList(['ASC', 'DESC'], false, Database::VAR_STRING), APP_LIMIT_ARRAY_PARAMS_SIZE), 'Array of index orders. Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' orders are allowed.', true) + ->param('attributes', null, new ArrayList(new Key(true), APP_LIMIT_ARRAY_PARAMS_SIZE), 'Array of attributes to index. Maximum of '.APP_LIMIT_ARRAY_PARAMS_SIZE.' attributes are allowed, each 32 characters long.') + ->param('orders', [], new ArrayList(new WhiteList(['ASC', 'DESC'], false, Database::VAR_STRING), APP_LIMIT_ARRAY_PARAMS_SIZE), 'Array of index orders. Maximum of '.APP_LIMIT_ARRAY_PARAMS_SIZE.' orders are allowed.', true) ->inject('response') ->inject('dbForProject') ->inject('database') ->inject('events') ->action(function (string $databaseId, string $collectionId, string $key, string $type, array $attributes, array $orders, Response $response, Database $dbForProject, EventDatabase $database, Event $events) { - $db = Authorization::skip(fn () => $dbForProject->getDocument('databases', $databaseId)); if ($db->isEmpty()) { throw new Exception(Exception::DATABASE_NOT_FOUND); } - $collection = $dbForProject->getDocument('database_' . $db->getInternalId(), $collectionId); + $collection = $dbForProject->getDocument('database_'.$db->getInternalId(), $collectionId); if ($collection->isEmpty()) { throw new Exception(Exception::COLLECTION_NOT_FOUND); @@ -1570,7 +1534,7 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/indexes') $count = $dbForProject->count('indexes', [ Query::equal('collectionInternalId', [$collection->getInternalId()]), - Query::equal('databaseInternalId', [$db->getInternalId()]) + Query::equal('databaseInternalId', [$db->getInternalId()]), ], 61); $limit = 64 - MariaDB::getCountOfDefaultIndexes(); @@ -1589,7 +1553,7 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/indexes') 'required' => true, 'array' => false, 'default' => null, - 'size' => 36 + 'size' => 36, ]; $oldAttributes[] = [ @@ -1600,7 +1564,7 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/indexes') 'required' => false, 'array' => false, 'default' => null, - 'size' => 0 + 'size' => 0, ]; $oldAttributes[] = [ @@ -1611,7 +1575,7 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/indexes') 'required' => false, 'array' => false, 'default' => null, - 'size' => 0 + 'size' => 0, ]; // lengths hidden by default @@ -1622,7 +1586,7 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/indexes') $attributeIndex = \array_search($attribute, array_column($oldAttributes, 'key')); if ($attributeIndex === false) { - throw new Exception(Exception::ATTRIBUTE_UNKNOWN, 'Unknown attribute: ' . $attribute); + throw new Exception(Exception::ATTRIBUTE_UNKNOWN, 'Unknown attribute: '.$attribute); } $attributeStatus = $oldAttributes[$attributeIndex]['status']; @@ -1631,7 +1595,7 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/indexes') // ensure attribute is available if ($attributeStatus !== 'available') { - throw new Exception(Exception::ATTRIBUTE_NOT_AVAILABLE, 'Attribute not available: ' . $oldAttributes[$attributeIndex]['key']); + throw new Exception(Exception::ATTRIBUTE_NOT_AVAILABLE, 'Attribute not available: '.$oldAttributes[$attributeIndex]['key']); } // set attribute size as index length only for strings @@ -1640,7 +1604,7 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/indexes') try { $index = $dbForProject->createDocument('indexes', new Document([ - '$id' => ID::custom($db->getInternalId() . '_' . $collection->getInternalId() . '_' . $key), + '$id' => ID::custom($db->getInternalId().'_'.$collection->getInternalId().'_'.$key), 'key' => $key, 'status' => 'processing', // processing, available, failed, deleting, stuck 'databaseInternalId' => $db->getInternalId(), @@ -1656,22 +1620,20 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/indexes') throw new Exception(Exception::INDEX_ALREADY_EXISTS); } - $dbForProject->deleteCachedDocument('database_' . $db->getInternalId(), $collectionId); + $dbForProject->deleteCachedDocument('database_'.$db->getInternalId(), $collectionId); $database ->setType(DATABASE_TYPE_CREATE_INDEX) ->setDatabase($db) ->setCollection($collection) - ->setDocument($index) - ; + ->setDocument($index); $events ->setParam('databaseId', $databaseId) ->setParam('collectionId', $collection->getId()) ->setParam('indexId', $index->getId()) ->setContext('collection', $collection) - ->setContext('database', $db) - ; + ->setContext('database', $db); $response ->setStatusCode(Response::STATUS_CODE_ACCEPTED) @@ -1697,13 +1659,12 @@ App::get('/v1/databases/:databaseId/collections/:collectionId/indexes') ->inject('response') ->inject('dbForProject') ->action(function (string $databaseId, string $collectionId, Response $response, Database $dbForProject) { - $database = Authorization::skip(fn () => $dbForProject->getDocument('databases', $databaseId)); if ($database->isEmpty()) { throw new Exception(Exception::DATABASE_NOT_FOUND); } - $collection = $dbForProject->getDocument('database_' . $database->getInternalId(), $collectionId); + $collection = $dbForProject->getDocument('database_'.$database->getInternalId(), $collectionId); if ($collection->isEmpty()) { throw new Exception(Exception::COLLECTION_NOT_FOUND); @@ -1737,13 +1698,12 @@ App::get('/v1/databases/:databaseId/collections/:collectionId/indexes/:key') ->inject('response') ->inject('dbForProject') ->action(function (string $databaseId, string $collectionId, string $key, Response $response, Database $dbForProject) { - $database = Authorization::skip(fn () => $dbForProject->getDocument('databases', $databaseId)); if ($database->isEmpty()) { throw new Exception(Exception::DATABASE_NOT_FOUND); } - $collection = $dbForProject->getDocument('database_' . $database->getInternalId(), $collectionId); + $collection = $dbForProject->getDocument('database_'.$database->getInternalId(), $collectionId); if ($collection->isEmpty()) { throw new Exception(Exception::COLLECTION_NOT_FOUND); @@ -1752,14 +1712,14 @@ App::get('/v1/databases/:databaseId/collections/:collectionId/indexes/:key') $indexes = $collection->getAttribute('indexes'); // Search for index - $indexIndex = array_search($key, array_map(fn($idx) => $idx['key'], $indexes)); + $indexIndex = array_search($key, array_map(fn ($idx) => $idx['key'], $indexes)); if ($indexIndex === false) { throw new Exception(Exception::INDEX_NOT_FOUND); } $index = $indexes[$indexIndex]; - $index->setAttribute('collectionId', $database->getInternalId() . '_' . $collectionId); + $index->setAttribute('collectionId', $database->getInternalId().'_'.$collectionId); $response->dynamic($index, Response::MODEL_INDEX); }); @@ -1788,19 +1748,18 @@ App::delete('/v1/databases/:databaseId/collections/:collectionId/indexes/:key') ->inject('database') ->inject('events') ->action(function (string $databaseId, string $collectionId, string $key, Response $response, Database $dbForProject, EventDatabase $database, Event $events) { - $db = Authorization::skip(fn () => $dbForProject->getDocument('databases', $databaseId)); if ($db->isEmpty()) { throw new Exception(Exception::DATABASE_NOT_FOUND); } - $collection = $dbForProject->getDocument('database_' . $db->getInternalId(), $collectionId); + $collection = $dbForProject->getDocument('database_'.$db->getInternalId(), $collectionId); if ($collection->isEmpty()) { throw new Exception(Exception::COLLECTION_NOT_FOUND); } - $index = $dbForProject->getDocument('indexes', $db->getInternalId() . '_' . $collection->getInternalId() . '_' . $key); + $index = $dbForProject->getDocument('indexes', $db->getInternalId().'_'.$collection->getInternalId().'_'.$key); if (empty($index->getId())) { throw new Exception(Exception::INDEX_NOT_FOUND); @@ -1811,14 +1770,13 @@ App::delete('/v1/databases/:databaseId/collections/:collectionId/indexes/:key') $index = $dbForProject->updateDocument('indexes', $index->getId(), $index->setAttribute('status', 'deleting')); } - $dbForProject->deleteCachedDocument('database_' . $db->getInternalId(), $collectionId); + $dbForProject->deleteCachedDocument('database_'.$db->getInternalId(), $collectionId); $database ->setType(DATABASE_TYPE_DELETE_INDEX) ->setDatabase($db) ->setCollection($collection) - ->setDocument($index) - ; + ->setDocument($index); $events ->setParam('databaseId', $databaseId) @@ -1826,8 +1784,7 @@ App::delete('/v1/databases/:databaseId/collections/:collectionId/indexes/:key') ->setParam('indexId', $index->getId()) ->setContext('collection', $collection) ->setContext('database', $db) - ->setPayload($response->output($index, Response::MODEL_INDEX)) - ; + ->setPayload($response->output($index, Response::MODEL_INDEX)); $response->noContent(); }); @@ -1865,7 +1822,6 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/documents') ->inject('events') ->inject('mode') ->action(function (string $databaseId, string $documentId, string $collectionId, string|array $data, ?array $permissions, Response $response, Database $dbForProject, Document $user, Event $events, string $mode) { - $data = (\is_string($data)) ? \json_decode($data, true) : $data; // Cast to JSON array if (empty($data)) { @@ -1876,22 +1832,22 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/documents') throw new Exception(Exception::DOCUMENT_INVALID_STRUCTURE, '$id is not allowed for creating new documents, try update instead'); } - $database = Authorization::skip(fn() => $dbForProject->getDocument('databases', $databaseId)); + $database = Authorization::skip(fn () => $dbForProject->getDocument('databases', $databaseId)); if ($database->isEmpty()) { throw new Exception(Exception::DATABASE_NOT_FOUND); } - $collection = Authorization::skip(fn() => $dbForProject->getDocument('database_' . $database->getInternalId(), $collectionId)); + $collection = Authorization::skip(fn () => $dbForProject->getDocument('database_'.$database->getInternalId(), $collectionId)); - if ($collection->isEmpty() || !$collection->getAttribute('enabled')) { - if (!($mode === APP_MODE_ADMIN && Auth::isPrivilegedUser(Authorization::getRoles()))) { + if ($collection->isEmpty() || ! $collection->getAttribute('enabled')) { + if (! ($mode === APP_MODE_ADMIN && Auth::isPrivilegedUser(Authorization::getRoles()))) { throw new Exception(Exception::COLLECTION_NOT_FOUND); } } $validator = new Authorization(Database::PERMISSION_CREATE); - if (!$validator->isValid($collection->getCreate())) { + if (! $validator->isValid($collection->getCreate())) { throw new Exception(Exception::USER_UNAUTHORIZED); } @@ -1907,7 +1863,7 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/documents') // Add permissions for current the user if none were provided. if (\is_null($permissions)) { $permissions = []; - if (!empty($user->getId())) { + if (! empty($user->getId())) { foreach ($allowedPermissions as $permission) { $permissions[] = (new Permission($permission, 'user', $user->getId()))->toString(); } @@ -1916,7 +1872,7 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/documents') // Users can only manage their own roles, API keys and Admin users can manage any $roles = Authorization::getRoles(); - if (!Auth::isAppUser($roles) && !Auth::isPrivilegedUser($roles)) { + if (! Auth::isAppUser($roles) && ! Auth::isPrivilegedUser($roles)) { foreach (Database::PERMISSIONS as $type) { foreach ($permissions as $permission) { $permission = Permission::parse($permission); @@ -1928,8 +1884,8 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/documents') $permission->getIdentifier(), $permission->getDimension() ))->toString(); - if (!Authorization::isRole($role)) { - throw new Exception(Exception::USER_UNAUTHORIZED, 'Permissions must be one of: (' . \implode(', ', $roles) . ')'); + if (! Authorization::isRole($role)) { + throw new Exception(Exception::USER_UNAUTHORIZED, 'Permissions must be one of: ('.\implode(', ', $roles).')'); } } } @@ -1940,7 +1896,7 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/documents') $data['$permissions'] = $permissions; try { - $document = $dbForProject->createDocument('database_' . $database->getInternalId() . '_collection_' . $collection->getInternalId(), new Document($data)); + $document = $dbForProject->createDocument('database_'.$database->getInternalId().'_collection_'.$collection->getInternalId(), new Document($data)); $document->setAttribute('$collectionId', $collectionId); $document->setAttribute('$databaseId', $databaseId); } catch (StructureException $exception) { @@ -1954,8 +1910,7 @@ App::post('/v1/databases/:databaseId/collections/:collectionId/documents') ->setParam('collectionId', $collection->getId()) ->setParam('documentId', $document->getId()) ->setContext('collection', $collection) - ->setContext('database', $database) - ; + ->setContext('database', $database); $response ->setStatusCode(Response::STATUS_CODE_CREATED) @@ -1979,22 +1934,21 @@ App::get('/v1/databases/:databaseId/collections/:collectionId/documents') ->label('sdk.offline.model', '/databases/{databaseId}/collections/{collectionId}/documents') ->param('databaseId', '', new UID(), 'Database ID.') ->param('collectionId', '', new UID(), 'Collection ID. You can create a new collection using the Database service [server integration](https://appwrite.io/docs/server/databases#databasesCreateCollection).') - ->param('queries', [], new ArrayList(new Text(APP_LIMIT_ARRAY_ELEMENT_SIZE), APP_LIMIT_ARRAY_PARAMS_SIZE), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/databases#querying-documents). Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' queries are allowed, each ' . APP_LIMIT_ARRAY_ELEMENT_SIZE . ' characters long.', true) + ->param('queries', [], new ArrayList(new Text(APP_LIMIT_ARRAY_ELEMENT_SIZE), APP_LIMIT_ARRAY_PARAMS_SIZE), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/databases#querying-documents). Maximum of '.APP_LIMIT_ARRAY_PARAMS_SIZE.' queries are allowed, each '.APP_LIMIT_ARRAY_ELEMENT_SIZE.' characters long.', true) ->inject('response') ->inject('dbForProject') ->inject('mode') ->action(function (string $databaseId, string $collectionId, array $queries, Response $response, Database $dbForProject, string $mode) { - $database = Authorization::skip(fn () => $dbForProject->getDocument('databases', $databaseId)); if ($database->isEmpty()) { throw new Exception(Exception::DATABASE_NOT_FOUND); } - $collection = Authorization::skip(fn() => $dbForProject->getDocument('database_' . $database->getInternalId(), $collectionId)); + $collection = Authorization::skip(fn () => $dbForProject->getDocument('database_'.$database->getInternalId(), $collectionId)); - if ($collection->isEmpty() || !$collection->getAttribute('enabled')) { - if (!($mode === APP_MODE_ADMIN && Auth::isPrivilegedUser(Authorization::getRoles()))) { + if ($collection->isEmpty() || ! $collection->getAttribute('enabled')) { + if (! ($mode === APP_MODE_ADMIN && Auth::isPrivilegedUser(Authorization::getRoles()))) { throw new Exception(Exception::COLLECTION_NOT_FOUND); } } @@ -2002,14 +1956,14 @@ App::get('/v1/databases/:databaseId/collections/:collectionId/documents') $documentSecurity = $collection->getAttribute('documentSecurity', false); $validator = new Authorization(Database::PERMISSION_READ); $valid = $validator->isValid($collection->getRead()); - if (!$documentSecurity && !$valid) { + if (! $documentSecurity && ! $valid) { throw new Exception(Exception::USER_UNAUTHORIZED); } // Validate queries $queriesValidator = new Documents($collection->getAttribute('attributes'), $collection->getAttribute('indexes')); $validQueries = $queriesValidator->isValid($queries); - if (!$validQueries) { + if (! $validQueries) { throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, $queriesValidator->getDescription()); } @@ -2022,10 +1976,10 @@ App::get('/v1/databases/:databaseId/collections/:collectionId/documents') /** @var Query $cursor */ $documentId = $cursor->getValue(); - if ($documentSecurity && !$valid) { - $cursorDocument = $dbForProject->getDocument('database_' . $database->getInternalId() . '_collection_' . $collection->getInternalId(), $documentId); + if ($documentSecurity && ! $valid) { + $cursorDocument = $dbForProject->getDocument('database_'.$database->getInternalId().'_collection_'.$collection->getInternalId(), $documentId); } else { - $cursorDocument = Authorization::skip(fn() => $dbForProject->getDocument('database_' . $database->getInternalId() . '_collection_' . $collection->getInternalId(), $documentId)); + $cursorDocument = Authorization::skip(fn () => $dbForProject->getDocument('database_'.$database->getInternalId().'_collection_'.$collection->getInternalId(), $documentId)); } if ($cursorDocument->isEmpty()) { @@ -2037,12 +1991,12 @@ App::get('/v1/databases/:databaseId/collections/:collectionId/documents') $filterQueries = Query::groupByType($queries)['filters']; - if ($documentSecurity && !$valid) { - $documents = $dbForProject->find('database_' . $database->getInternalId() . '_collection_' . $collection->getInternalId(), $queries); - $total = $dbForProject->count('database_' . $database->getInternalId() . '_collection_' . $collection->getInternalId(), $filterQueries, APP_LIMIT_COUNT); + if ($documentSecurity && ! $valid) { + $documents = $dbForProject->find('database_'.$database->getInternalId().'_collection_'.$collection->getInternalId(), $queries); + $total = $dbForProject->count('database_'.$database->getInternalId().'_collection_'.$collection->getInternalId(), $filterQueries, APP_LIMIT_COUNT); } else { - $documents = Authorization::skip(fn () => $dbForProject->find('database_' . $database->getInternalId() . '_collection_' . $collection->getInternalId(), $queries)); - $total = Authorization::skip(fn () => $dbForProject->count('database_' . $database->getInternalId() . '_collection_' . $collection->getInternalId(), $filterQueries, APP_LIMIT_COUNT)); + $documents = Authorization::skip(fn () => $dbForProject->find('database_'.$database->getInternalId().'_collection_'.$collection->getInternalId(), $queries)); + $total = Authorization::skip(fn () => $dbForProject->count('database_'.$database->getInternalId().'_collection_'.$collection->getInternalId(), $filterQueries, APP_LIMIT_COUNT)); } /** @@ -2051,6 +2005,7 @@ App::get('/v1/databases/:databaseId/collections/:collectionId/documents') $documents = array_map(function (Document $document) use ($collectionId, $databaseId) { $document->setAttribute('$collectionId', $collectionId); $document->setAttribute('$databaseId', $databaseId); + return $document; }, $documents); @@ -2083,17 +2038,16 @@ App::get('/v1/databases/:databaseId/collections/:collectionId/documents/:documen ->inject('dbForProject') ->inject('mode') ->action(function (string $databaseId, string $collectionId, string $documentId, Response $response, Database $dbForProject, string $mode) { - $database = Authorization::skip(fn () => $dbForProject->getDocument('databases', $databaseId)); if ($database->isEmpty()) { throw new Exception(Exception::DATABASE_NOT_FOUND); } - $collection = Authorization::skip(fn() => $dbForProject->getDocument('database_' . $database->getInternalId(), $collectionId)); + $collection = Authorization::skip(fn () => $dbForProject->getDocument('database_'.$database->getInternalId(), $collectionId)); - if ($collection->isEmpty() || !$collection->getAttribute('enabled')) { - if (!($mode === APP_MODE_ADMIN && Auth::isPrivilegedUser(Authorization::getRoles()))) { + if ($collection->isEmpty() || ! $collection->getAttribute('enabled')) { + if (! ($mode === APP_MODE_ADMIN && Auth::isPrivilegedUser(Authorization::getRoles()))) { throw new Exception(Exception::COLLECTION_NOT_FOUND); } } @@ -2101,14 +2055,14 @@ App::get('/v1/databases/:databaseId/collections/:collectionId/documents/:documen $documentSecurity = $collection->getAttribute('documentSecurity', false); $validator = new Authorization(Database::PERMISSION_READ); $valid = $validator->isValid($collection->getRead()); - if (!$documentSecurity && !$valid) { + if (! $documentSecurity && ! $valid) { throw new Exception(Exception::USER_UNAUTHORIZED); } - if ($documentSecurity && !$valid) { - $document = $dbForProject->getDocument('database_' . $database->getInternalId() . '_collection_' . $collection->getInternalId(), $documentId); + if ($documentSecurity && ! $valid) { + $document = $dbForProject->getDocument('database_'.$database->getInternalId().'_collection_'.$collection->getInternalId(), $documentId); } else { - $document = Authorization::skip(fn () => $dbForProject->getDocument('database_' . $database->getInternalId() . '_collection_' . $collection->getInternalId(), $documentId)); + $document = Authorization::skip(fn () => $dbForProject->getDocument('database_'.$database->getInternalId().'_collection_'.$collection->getInternalId(), $documentId)); } if ($document->isEmpty()) { @@ -2147,20 +2101,19 @@ App::get('/v1/databases/:databaseId/collections/:collectionId/documents/:documen ->inject('locale') ->inject('geodb') ->action(function (string $databaseId, string $collectionId, string $documentId, array $queries, Response $response, Database $dbForProject, Locale $locale, Reader $geodb) { - $database = Authorization::skip(fn () => $dbForProject->getDocument('databases', $databaseId)); if ($database->isEmpty()) { throw new Exception(Exception::DATABASE_NOT_FOUND); } - $collection = $dbForProject->getDocument('database_' . $database->getInternalId(), $collectionId); + $collection = $dbForProject->getDocument('database_'.$database->getInternalId(), $collectionId); if ($collection->isEmpty()) { throw new Exception(Exception::COLLECTION_NOT_FOUND); } - $document = $dbForProject->getDocument('database_' . $database->getInternalId() . '_collection_' . $collection->getInternalId(), $documentId); + $document = $dbForProject->getDocument('database_'.$database->getInternalId().'_collection_'.$collection->getInternalId(), $documentId); if ($document->isEmpty()) { throw new Exception(Exception::DOCUMENT_NOT_FOUND); @@ -2172,13 +2125,13 @@ App::get('/v1/databases/:databaseId/collections/:collectionId/documents/:documen $offset = $grouped['offset'] ?? 0; $audit = new Audit($dbForProject); - $resource = 'database/' . $databaseId . '/collection/' . $collectionId . '/document/' . $document->getId(); + $resource = 'database/'.$databaseId.'/collection/'.$collectionId.'/document/'.$document->getId(); $logs = $audit->getLogsByResource($resource, $limit, $offset); $output = []; foreach ($logs as $i => &$log) { - $log['userAgent'] = (!empty($log['userAgent'])) ? $log['userAgent'] : 'UNKNOWN'; + $log['userAgent'] = (! empty($log['userAgent'])) ? $log['userAgent'] : 'UNKNOWN'; $detector = new Detector($log['userAgent']); $detector->skipBotDetection(); // OPTIONAL: If called, bot detection will completely be skipped (bots will be detected as regular devices then) @@ -2206,14 +2159,14 @@ App::get('/v1/databases/:databaseId/collections/:collectionId/documents/:documen 'clientEngineVersion' => $client['clientEngineVersion'], 'deviceName' => $device['deviceName'], 'deviceBrand' => $device['deviceBrand'], - 'deviceModel' => $device['deviceModel'] + 'deviceModel' => $device['deviceModel'], ]); $record = $geodb->get($log['ip']); if ($record) { - $output[$i]['countryCode'] = $locale->getText('countries.' . strtolower($record['country']['iso_code']), false) ? \strtolower($record['country']['iso_code']) : '--'; - $output[$i]['countryName'] = $locale->getText('countries.' . strtolower($record['country']['iso_code']), $locale->getText('locale.country.unknown')); + $output[$i]['countryCode'] = $locale->getText('countries.'.strtolower($record['country']['iso_code']), false) ? \strtolower($record['country']['iso_code']) : '--'; + $output[$i]['countryName'] = $locale->getText('countries.'.strtolower($record['country']['iso_code']), $locale->getText('locale.country.unknown')); } else { $output[$i]['countryCode'] = '--'; $output[$i]['countryName'] = $locale->getText('locale.country.unknown'); @@ -2257,7 +2210,6 @@ App::patch('/v1/databases/:databaseId/collections/:collectionId/documents/:docum ->inject('events') ->inject('mode') ->action(function (string $databaseId, string $collectionId, string $documentId, string|array $data, ?array $permissions, Response $response, Database $dbForProject, Event $events, string $mode) { - $data = (\is_string($data)) ? \json_decode($data, true) : $data; // Cast to JSON array if (empty($data) && \is_null($permissions)) { @@ -2270,10 +2222,10 @@ App::patch('/v1/databases/:databaseId/collections/:collectionId/documents/:docum throw new Exception(Exception::DATABASE_NOT_FOUND); } - $collection = Authorization::skip(fn() => $dbForProject->getDocument('database_' . $database->getInternalId(), $collectionId)); + $collection = Authorization::skip(fn () => $dbForProject->getDocument('database_'.$database->getInternalId(), $collectionId)); - if ($collection->isEmpty() || !$collection->getAttribute('enabled')) { - if (!($mode === APP_MODE_ADMIN && Auth::isPrivilegedUser(Authorization::getRoles()))) { + if ($collection->isEmpty() || ! $collection->getAttribute('enabled')) { + if (! ($mode === APP_MODE_ADMIN && Auth::isPrivilegedUser(Authorization::getRoles()))) { throw new Exception(Exception::COLLECTION_NOT_FOUND); } } @@ -2281,12 +2233,12 @@ App::patch('/v1/databases/:databaseId/collections/:collectionId/documents/:docum $documentSecurity = $collection->getAttribute('documentSecurity', false); $validator = new Authorization(Database::PERMISSION_UPDATE); $valid = $validator->isValid($collection->getUpdate()); - if (!$documentSecurity && !$valid) { + if (! $documentSecurity && ! $valid) { throw new Exception(Exception::USER_UNAUTHORIZED); } // Read permission should not be required for update - $document = Authorization::skip(fn() => $dbForProject->getDocument('database_' . $database->getInternalId() . '_collection_' . $collection->getInternalId(), $documentId)); + $document = Authorization::skip(fn () => $dbForProject->getDocument('database_'.$database->getInternalId().'_collection_'.$collection->getInternalId(), $documentId)); if ($document->isEmpty()) { throw new Exception(Exception::DOCUMENT_NOT_FOUND); @@ -2301,7 +2253,7 @@ App::patch('/v1/databases/:databaseId/collections/:collectionId/documents/:docum // Users can only manage their own roles, API keys and Admin users can manage any $roles = Authorization::getRoles(); - if (!Auth::isAppUser($roles) && !Auth::isPrivilegedUser($roles) && !\is_null($permissions)) { + if (! Auth::isAppUser($roles) && ! Auth::isPrivilegedUser($roles) && ! \is_null($permissions)) { foreach (Database::PERMISSIONS as $type) { foreach ($permissions as $permission) { $permission = Permission::parse($permission); @@ -2313,8 +2265,8 @@ App::patch('/v1/databases/:databaseId/collections/:collectionId/documents/:docum $permission->getIdentifier(), $permission->getDimension() ))->toString(); - if (!Authorization::isRole($role)) { - throw new Exception(Exception::USER_UNAUTHORIZED, 'Permissions must be one of: (' . \implode(', ', $roles) . ')'); + if (! Authorization::isRole($role)) { + throw new Exception(Exception::USER_UNAUTHORIZED, 'Permissions must be one of: ('.\implode(', ', $roles).')'); } } } @@ -2331,10 +2283,10 @@ App::patch('/v1/databases/:databaseId/collections/:collectionId/documents/:docum $data['$permissions'] = $permissions; try { - if ($documentSecurity && !$valid) { - $document = $dbForProject->updateDocument('database_' . $database->getInternalId() . '_collection_' . $collection->getInternalId(), $document->getId(), new Document($data)); + if ($documentSecurity && ! $valid) { + $document = $dbForProject->updateDocument('database_'.$database->getInternalId().'_collection_'.$collection->getInternalId(), $document->getId(), new Document($data)); } else { - $document = Authorization::skip(fn() => $dbForProject->updateDocument('database_' . $database->getInternalId() . '_collection_' . $collection->getInternalId(), $document->getId(), new Document($data))); + $document = Authorization::skip(fn () => $dbForProject->updateDocument('database_'.$database->getInternalId().'_collection_'.$collection->getInternalId(), $document->getId(), new Document($data))); } /** @@ -2355,8 +2307,7 @@ App::patch('/v1/databases/:databaseId/collections/:collectionId/documents/:docum ->setParam('collectionId', $collection->getId()) ->setParam('documentId', $document->getId()) ->setContext('collection', $collection) - ->setContext('database', $database) - ; + ->setContext('database', $database); $response->dynamic($document, Response::MODEL_DOCUMENT); }); @@ -2391,17 +2342,16 @@ App::delete('/v1/databases/:databaseId/collections/:collectionId/documents/:docu ->inject('deletes') ->inject('mode') ->action(function (string $databaseId, string $collectionId, string $documentId, Response $response, Database $dbForProject, Event $events, Delete $deletes, string $mode) { - $database = Authorization::skip(fn () => $dbForProject->getDocument('databases', $databaseId)); if ($database->isEmpty()) { throw new Exception(Exception::DATABASE_NOT_FOUND); } - $collection = Authorization::skip(fn() => $dbForProject->getDocument('database_' . $database->getInternalId(), $collectionId)); + $collection = Authorization::skip(fn () => $dbForProject->getDocument('database_'.$database->getInternalId(), $collectionId)); - if ($collection->isEmpty() || !$collection->getAttribute('enabled')) { - if (!($mode === APP_MODE_ADMIN && Auth::isPrivilegedUser(Authorization::getRoles()))) { + if ($collection->isEmpty() || ! $collection->getAttribute('enabled')) { + if (! ($mode === APP_MODE_ADMIN && Auth::isPrivilegedUser(Authorization::getRoles()))) { throw new Exception(Exception::COLLECTION_NOT_FOUND); } } @@ -2409,28 +2359,28 @@ App::delete('/v1/databases/:databaseId/collections/:collectionId/documents/:docu $documentSecurity = $collection->getAttribute('documentSecurity', false); $validator = new Authorization(Database::PERMISSION_DELETE); $valid = $validator->isValid($collection->getDelete()); - if (!$documentSecurity && !$valid) { + if (! $documentSecurity && ! $valid) { throw new Exception(Exception::USER_UNAUTHORIZED); } // Read permission should not be required for delete - $document = Authorization::skip(fn() => $dbForProject->getDocument('database_' . $database->getInternalId() . '_collection_' . $collection->getInternalId(), $documentId)); + $document = Authorization::skip(fn () => $dbForProject->getDocument('database_'.$database->getInternalId().'_collection_'.$collection->getInternalId(), $documentId)); if ($document->isEmpty()) { throw new Exception(Exception::DOCUMENT_NOT_FOUND); } - if ($documentSecurity && !$valid) { + if ($documentSecurity && ! $valid) { try { - $dbForProject->deleteDocument('database_' . $database->getInternalId() . '_collection_' . $collection->getInternalId(), $documentId); + $dbForProject->deleteDocument('database_'.$database->getInternalId().'_collection_'.$collection->getInternalId(), $documentId); } catch (AuthorizationException) { throw new Exception(Exception::USER_UNAUTHORIZED); } } else { - Authorization::skip(fn() => $dbForProject->deleteDocument('database_' . $database->getInternalId() . '_collection_' . $collection->getInternalId(), $documentId)); + Authorization::skip(fn () => $dbForProject->deleteDocument('database_'.$database->getInternalId().'_collection_'.$collection->getInternalId(), $documentId)); } - $dbForProject->deleteCachedDocument('database_' . $database->getInternalId() . '_collection_' . $collection->getInternalId(), $documentId); + $dbForProject->deleteCachedDocument('database_'.$database->getInternalId().'_collection_'.$collection->getInternalId(), $documentId); /** * Reset $collection attribute to remove prefix. @@ -2440,8 +2390,7 @@ App::delete('/v1/databases/:databaseId/collections/:collectionId/documents/:docu $deletes ->setType(DELETE_TYPE_AUDIT) - ->setDocument($document) - ; + ->setDocument($document); $events ->setParam('databaseId', $databaseId) @@ -2449,8 +2398,7 @@ App::delete('/v1/databases/:databaseId/collections/:collectionId/documents/:docu ->setParam('documentId', $document->getId()) ->setContext('collection', $collection) ->setContext('database', $database) - ->setPayload($response->output($document, Response::MODEL_DOCUMENT)) - ; + ->setPayload($response->output($document, Response::MODEL_DOCUMENT)); $response->noContent(); }); @@ -2469,7 +2417,6 @@ App::get('/v1/databases/usage') ->inject('response') ->inject('dbForProject') ->action(function (string $range, Response $response, Database $dbForProject) { - $usage = []; if (App::getEnv('_APP_USAGE_STATS', 'enabled') == 'enabled') { $periods = [ @@ -2506,7 +2453,7 @@ App::get('/v1/databases/usage') 'documents.$all.requests.create', 'documents.$all.requests.read', 'documents.$all.requests.update', - 'documents.$all.requests.delete' + 'documents.$all.requests.delete', ]; $stats = []; @@ -2555,16 +2502,16 @@ App::get('/v1/databases/usage') 'databasesCount' => $stats['databases.$all.count.total'] ?? [], 'documentsCount' => $stats['documents.$all.count.total'] ?? [], 'collectionsCount' => $stats['collections.$all.count.total'] ?? [], - 'documentsCreate' => $stats['documents.$all.requests.create'] ?? [], - 'documentsRead' => $stats['documents.$all.requests.read'] ?? [], + 'documentsCreate' => $stats['documents.$all.requests.create'] ?? [], + 'documentsRead' => $stats['documents.$all.requests.read'] ?? [], 'documentsUpdate' => $stats['documents.$all.requests.update'] ?? [], 'documentsDelete' => $stats['documents.$all.requests.delete'] ?? [], 'collectionsCreate' => $stats['collections.$all.requests.create'] ?? [], - 'collectionsRead' => $stats['collections.$all.requests.read'] ?? [], + 'collectionsRead' => $stats['collections.$all.requests.read'] ?? [], 'collectionsUpdate' => $stats['collections.$all.requests.update'] ?? [], 'collectionsDelete' => $stats['collections.$all.requests.delete'] ?? [], 'databasesCreate' => $stats['databases.$all.requests.create'] ?? [], - 'databasesRead' => $stats['databases.$all.requests.read'] ?? [], + 'databasesRead' => $stats['databases.$all.requests.read'] ?? [], 'databasesUpdate' => $stats['databases.$all.requests.update'] ?? [], 'databasesDelete' => $stats['databases.$all.requests.delete'] ?? [], ]); @@ -2588,7 +2535,6 @@ App::get('/v1/databases/:databaseId/usage') ->inject('response') ->inject('dbForProject') ->action(function (string $databaseId, string $range, Response $response, Database $dbForProject) { - $usage = []; if (App::getEnv('_APP_USAGE_STATS', 'enabled') == 'enabled') { $periods = [ @@ -2611,16 +2557,16 @@ App::get('/v1/databases/:databaseId/usage') ]; $metrics = [ - 'collections.' . $databaseId . '.count.total', - 'collections.' . $databaseId . '.requests.create', - 'collections.' . $databaseId . '.requests.read', - 'collections.' . $databaseId . '.requests.update', - 'collections.' . $databaseId . '.requests.delete', - 'documents.' . $databaseId . '.count.total', - 'documents.' . $databaseId . '.requests.create', - 'documents.' . $databaseId . '.requests.read', - 'documents.' . $databaseId . '.requests.update', - 'documents.' . $databaseId . '.requests.delete' + 'collections.'.$databaseId.'.count.total', + 'collections.'.$databaseId.'.requests.create', + 'collections.'.$databaseId.'.requests.read', + 'collections.'.$databaseId.'.requests.update', + 'collections.'.$databaseId.'.requests.delete', + 'documents.'.$databaseId.'.count.total', + 'documents.'.$databaseId.'.requests.create', + 'documents.'.$databaseId.'.requests.read', + 'documents.'.$databaseId.'.requests.update', + 'documents.'.$databaseId.'.requests.delete', ]; $stats = []; @@ -2668,12 +2614,12 @@ App::get('/v1/databases/:databaseId/usage') 'range' => $range, 'collectionsCount' => $stats["collections.{$databaseId}.count.total"] ?? [], 'collectionsCreate' => $stats["collections.{$databaseId}.requests.create"] ?? [], - 'collectionsRead' => $stats["collections.{$databaseId}.requests.read"] ?? [], + 'collectionsRead' => $stats["collections.{$databaseId}.requests.read"] ?? [], 'collectionsUpdate' => $stats["collections.{$databaseId}.requests.update"] ?? [], 'collectionsDelete' => $stats["collections.{$databaseId}.requests.delete"] ?? [], 'documentsCount' => $stats["documents.{$databaseId}.count.total"] ?? [], - 'documentsCreate' => $stats["documents.{$databaseId}.requests.create"] ?? [], - 'documentsRead' => $stats["documents.{$databaseId}.requests.read"] ?? [], + 'documentsCreate' => $stats["documents.{$databaseId}.requests.create"] ?? [], + 'documentsRead' => $stats["documents.{$databaseId}.requests.read"] ?? [], 'documentsUpdate' => $stats["documents.{$databaseId}.requests.update"] ?? [], 'documentsDelete' => $stats["documents.{$databaseId}.requests.delete"] ?? [], ]); @@ -2699,11 +2645,10 @@ App::get('/v1/databases/:databaseId/collections/:collectionId/usage') ->inject('response') ->inject('dbForProject') ->action(function (string $databaseId, string $range, string $collectionId, Response $response, Database $dbForProject) { - $database = $dbForProject->getDocument('databases', $databaseId); - $collectionDocument = $dbForProject->getDocument('database_' . $database->getInternalId(), $collectionId); - $collection = $dbForProject->getCollection('database_' . $database->getInternalId() . '_collection_' . $collectionDocument->getInternalId()); + $collectionDocument = $dbForProject->getDocument('database_'.$database->getInternalId(), $collectionId); + $collection = $dbForProject->getCollection('database_'.$database->getInternalId().'_collection_'.$collectionDocument->getInternalId()); if ($collection->isEmpty()) { throw new Exception(Exception::COLLECTION_NOT_FOUND); @@ -2783,8 +2728,8 @@ App::get('/v1/databases/:databaseId/collections/:collectionId/usage') 'documentsCount' => $stats["documents.{$databaseId}/{$collectionId}.count.total"] ?? [], 'documentsCreate' => $stats["documents.{$databaseId}/{$collectionId}.requests.create"] ?? [], 'documentsRead' => $stats["documents.{$databaseId}/{$collectionId}.requests.read"] ?? [], - 'documentsUpdate' => $stats["documents.{$databaseId}/{$collectionId}.requests.update"] ?? [], - 'documentsDelete' => $stats["documents.{$databaseId}/{$collectionId}.requests.delete" ?? []] + 'documentsUpdate' => $stats["documents.{$databaseId}/{$collectionId}.requests.update"] ?? [], + 'documentsDelete' => $stats["documents.{$databaseId}/{$collectionId}.requests.delete" ?? []], ]); } diff --git a/app/controllers/api/domains.php b/app/controllers/api/domains.php index 9eb0497b7d..16e304a2d4 100644 --- a/app/controllers/api/domains.php +++ b/app/controllers/api/domains.php @@ -1,21 +1,21 @@ desc("Suggest domain names") + ->desc('Suggest domain names') ->groups(['api', 'projects']) ->label('scope', 'projects.write') ->label('sdk.auth', [APP_AUTH_TYPE_ADMIN]) @@ -41,15 +41,14 @@ App::post('/v1/domains/suggest') ->inject('response') ->inject('registrar') ->action(function (string $domain, $response, $registrar) { - - $domain = new Domain($domain); - $suggestions = $registrar->suggest([$domain->getName()], [$domain->getTLD()]); + $domain = new Domain($domain); + $suggestions = $registrar->suggest([$domain->getName()], [$domain->getTLD()]); - $response->dynamic(new Document(["domains" => $suggestions]), Response::MODEL_DOMAIN_LIST); + $response->dynamic(new Document(['domains' => $suggestions]), Response::MODEL_DOMAIN_LIST); }); App::post('/v1/domains/available') - ->desc("Checks if a domain is available for registration") + ->desc('Checks if a domain is available for registration') ->groups(['api', 'projects']) ->label('scope', 'projects.write') ->label('sdk.auth', [APP_AUTH_TYPE_ADMIN]) @@ -62,17 +61,16 @@ App::post('/v1/domains/available') ->inject('response') ->inject('registrar') ->action(function (string $domain, $response, $registrar) { - - $domain = [ - "domain" => $domain, - "available" => $registrar->available($domain) - ]; + $domain = [ + 'domain' => $domain, + 'available' => $registrar->available($domain), + ]; - $response->dynamic(new Document(["domain" => $domain]), Response::MODEL_DOMAIN); + $response->dynamic(new Document(['domain' => $domain]), Response::MODEL_DOMAIN); }); App::post('/v1/domains') - ->desc("Create a domain for 3rd party registrar, prompt to assign nameservers") + ->desc('Create a domain for 3rd party registrar, prompt to assign nameservers') ->groups(['api', 'projects']) ->label('scope', 'projects.write') ->label('sdk.auth', [APP_AUTH_TYPE_ADMIN]) @@ -87,62 +85,61 @@ App::post('/v1/domains') ->inject('dbForConsole') ->inject('registrar') ->action(function ( - string $projectId, - string $domain, - Response $response, - Database $dbForConsole, + string $projectId, + string $domain, + Response $response, + Database $dbForConsole, Registrar $registrar - ) { + ) { + if (! $registrar->available($domain)) { + throw new Exception(Exception::DOMAIN_ALREADY_EXISTS); + } - if(!$registrar->available($domain)) { - throw new Exception(Exception::DOMAIN_ALREADY_EXISTS); - } + $project = $dbForConsole->getDocument('projects', $projectId); - $project = $dbForConsole->getDocument('projects', $projectId); + if ($project->isEmpty()) { + throw new Exception(Exception::PROJECT_NOT_FOUND); + } - if ($project->isEmpty()) { - throw new Exception(Exception::PROJECT_NOT_FOUND); - } + $document = $dbForConsole->findOne('domains', [ + Query::equal('domain', [$domain]), + Query::equal('projectInternalId', [$project->getInternalId()]), + ]); - $document = $dbForConsole->findOne('domains', [ - Query::equal('domain', [$domain]), - Query::equal('projectInternalId', [$project->getInternalId()]), - ]); + if ($document && ! $document->isEmpty()) { + throw new Exception(Exception::DOMAIN_ALREADY_EXISTS); + } - if ($document && !$document->isEmpty()) { - throw new Exception(Exception::DOMAIN_ALREADY_EXISTS); - } + $domain = new Domain($domain); - $domain = new Domain($domain); + $domain = new Document([ + '$id' => ID::unique(), + '$permissions' => [ + Permission::read(Role::any()), + Permission::update(Role::any()), + Permission::delete(Role::any()), + ], + 'projectInternalId' => $project->getInternalId(), + 'projectId' => $project->getId(), + 'domain' => $domain->get(), + 'tld' => $domain->getSuffix(), + 'registerable' => $domain->getRegisterable(), + 'verification' => false, + 'certificateId' => null, + 'registered' => false, + ]); - $domain = new Document([ - '$id' => ID::unique(), - '$permissions' => [ - Permission::read(Role::any()), - Permission::update(Role::any()), - Permission::delete(Role::any()), - ], - 'projectInternalId' => $project->getInternalId(), - 'projectId' => $project->getId(), - 'domain' => $domain->get(), - 'tld' => $domain->getSuffix(), - 'registerable' => $domain->getRegisterable(), - 'verification' => false, - 'certificateId' => null, - 'registered' => false, - ]); + $domain = $dbForConsole->createDocument('domains', $domain); - $domain = $dbForConsole->createDocument('domains', $domain); + $dbForConsole->deleteCachedDocument('projects', $project->getId()); - $dbForConsole->deleteCachedDocument('projects', $project->getId()); - - $response - ->setStatusCode(Response::STATUS_CODE_CREATED) - ->dynamic($domain, Response::MODEL_DOMAIN); + $response + ->setStatusCode(Response::STATUS_CODE_CREATED) + ->dynamic($domain, Response::MODEL_DOMAIN); }); App::post('/v1/domains/purchase') - ->desc("Purchase, create and domain assign nameservers") + ->desc('Purchase, create and domain assign nameservers') ->groups(['api', 'projects']) ->label('scope', 'projects.write') ->label('sdk.auth', [APP_AUTH_TYPE_ADMIN]) @@ -169,8 +166,8 @@ App::post('/v1/domains/purchase') ->inject('dbForConsole') ->inject('registrar') ->action(function ( - string $projectId, - string $domain, + string $projectId, + string $domain, string $firstname, string $lastname, string $phone, @@ -183,88 +180,81 @@ App::post('/v1/domains/purchase') string $country, string $postalcode, string $org, - Response $response, - Database $dbForConsole, + Response $response, + Database $dbForConsole, Registrar $registrar - ) { + ) { + if (! $registrar->available($domain)) { + throw new Exception(); + } - if(!$registrar->available($domain)) { - throw new Exception(); - } + $contact = new Contact( + $firstname, + $lastname, + $phone, + $email, + $address1, + $address2, + $address3, + $city, + $state, + $country, + $postalcode, + $org, + '' + ); - - $contact = new Contact( - $firstname, - $lastname, - $phone, - $email, - $address1, - $address2, - $address3, - $city, - $state, - $country, - $postalcode, - $org, - '' - ); + try { + $registrar->purchase($domain, [$contact]); + } catch (Exception $e) { + throw new Exception(); + } - try { + $project = $dbForConsole->getDocument('projects', $projectId); - $registrar->purchase($domain, [$contact]); + if ($project->isEmpty()) { + throw new Exception(Exception::PROJECT_NOT_FOUND); + } - } catch (Exception $e) { + $document = $dbForConsole->findOne('domains', [ + Query::equal('domain', [$domain]), + Query::equal('projectInternalId', [$project->getInternalId()]), + ]); - throw new Exception(); + if ($document && ! $document->isEmpty()) { + throw new Exception(Exception::DOMAIN_ALREADY_EXISTS); + } - } + $domain = new Domain($domain); - $project = $dbForConsole->getDocument('projects', $projectId); + $domain = new Document([ + '$id' => ID::unique(), + '$permissions' => [ + Permission::read(Role::any()), + Permission::update(Role::any()), + Permission::delete(Role::any()), + ], + 'projectInternalId' => $project->getInternalId(), + 'projectId' => $project->getId(), + 'domain' => $domain->get(), + 'tld' => $domain->getSuffix(), + 'registerable' => $domain->getRegisterable(), + 'verification' => false, + 'certificateId' => null, + 'registered' => true, + ]); - if ($project->isEmpty()) { - throw new Exception(Exception::PROJECT_NOT_FOUND); - } + $domain = $dbForConsole->createDocument('domains', $domain); - $document = $dbForConsole->findOne('domains', [ - Query::equal('domain', [$domain]), - Query::equal('projectInternalId', [$project->getInternalId()]), - ]); - - if ($document && !$document->isEmpty()) { - throw new Exception(Exception::DOMAIN_ALREADY_EXISTS); - } - - $domain = new Domain($domain); - - $domain = new Document([ - '$id' => ID::unique(), - '$permissions' => [ - Permission::read(Role::any()), - Permission::update(Role::any()), - Permission::delete(Role::any()), - ], - 'projectInternalId' => $project->getInternalId(), - 'projectId' => $project->getId(), - 'domain' => $domain->get(), - 'tld' => $domain->getSuffix(), - 'registerable' => $domain->getRegisterable(), - 'verification' => false, - 'certificateId' => null, - 'registered' => true, - ]); - - $domain = $dbForConsole->createDocument('domains', $domain); - - $dbForConsole->deleteCachedDocument('projects', $project->getId()); - - $response - ->setStatusCode(Response::STATUS_CODE_CREATED) - ->dynamic($domain, Response::MODEL_DOMAIN); + $dbForConsole->deleteCachedDocument('projects', $project->getId()); + $response + ->setStatusCode(Response::STATUS_CODE_CREATED) + ->dynamic($domain, Response::MODEL_DOMAIN); }); App::post('/v1/domains/transfer/in') - ->desc("Transfer existing domain to Appwrite, and assign nameservers") + ->desc('Transfer existing domain to Appwrite, and assign nameservers') ->groups(['api', 'projects']) ->label('scope', 'projects.write') ->label('sdk.auth', [APP_AUTH_TYPE_ADMIN]) @@ -291,97 +281,91 @@ App::post('/v1/domains/transfer/in') ->inject('dbForConsole') ->inject('registrar') ->action(function ( - string $projectId, - string $domain, - string $firstname, - string $lastname, - string $phone, - string $email, - string $address1, - string $address2, - string $address3, - string $city, - string $state, - string $country, - string $postalcode, - string $org, - Response $response, - Database $dbForConsole, - Registrar $registrar + string $projectId, + string $domain, + string $firstname, + string $lastname, + string $phone, + string $email, + string $address1, + string $address2, + string $address3, + string $city, + string $state, + string $country, + string $postalcode, + string $org, + Response $response, + Database $dbForConsole, + Registrar $registrar ) { + $contact = new Contact( + $firstname, + $lastname, + $phone, + $email, + $address1, + $address2, + $address3, + $city, + $state, + $country, + $postalcode, + $org, + '' + ); - $contact = new Contact( - $firstname, - $lastname, - $phone, - $email, - $address1, - $address2, - $address3, - $city, - $state, - $country, - $postalcode, - $org, - '' - ); + try { + $registrar->transfer($domain, [$contact]); + } catch (Exception $e) { + throw new Exception(); + } - try { + $project = $dbForConsole->getDocument('projects', $projectId); - $registrar->transfer($domain, [$contact]); + if ($project->isEmpty()) { + throw new Exception(Exception::PROJECT_NOT_FOUND); + } - } catch (Exception $e) { + $document = $dbForConsole->findOne('domains', [ + Query::equal('domain', [$domain]), + Query::equal('projectInternalId', [$project->getInternalId()]), + ]); - throw new Exception(); + if ($document && ! $document->isEmpty()) { + throw new Exception(Exception::DOMAIN_ALREADY_EXISTS); + } - } + $domain = new Domain($domain); - $project = $dbForConsole->getDocument('projects', $projectId); + $domain = new Document([ + '$id' => ID::unique(), + '$permissions' => [ + Permission::read(Role::any()), + Permission::update(Role::any()), + Permission::delete(Role::any()), + ], + 'projectInternalId' => $project->getInternalId(), + 'projectId' => $project->getId(), + 'domain' => $domain->get(), + 'tld' => $domain->getSuffix(), + 'registerable' => $domain->getRegisterable(), + 'verification' => false, + 'certificateId' => null, + 'registered' => true, + ]); - if ($project->isEmpty()) { - throw new Exception(Exception::PROJECT_NOT_FOUND); - } + $domain = $dbForConsole->createDocument('domains', $domain); - $document = $dbForConsole->findOne('domains', [ - Query::equal('domain', [$domain]), - Query::equal('projectInternalId', [$project->getInternalId()]), - ]); - - if ($document && !$document->isEmpty()) { - throw new Exception(Exception::DOMAIN_ALREADY_EXISTS); - } - - $domain = new Domain($domain); - - $domain = new Document([ - '$id' => ID::unique(), - '$permissions' => [ - Permission::read(Role::any()), - Permission::update(Role::any()), - Permission::delete(Role::any()), - ], - 'projectInternalId' => $project->getInternalId(), - 'projectId' => $project->getId(), - 'domain' => $domain->get(), - 'tld' => $domain->getSuffix(), - 'registerable' => $domain->getRegisterable(), - 'verification' => false, - 'certificateId' => null, - 'registered' => true, - ]); - - $domain = $dbForConsole->createDocument('domains', $domain); - - $dbForConsole->deleteCachedDocument('projects', $project->getId()); - - $response - ->setStatusCode(Response::STATUS_CODE_CREATED) - ->dynamic($domain, Response::MODEL_DOMAIN); + $dbForConsole->deleteCachedDocument('projects', $project->getId()); + $response + ->setStatusCode(Response::STATUS_CODE_CREATED) + ->dynamic($domain, Response::MODEL_DOMAIN); }); App::post('/v1/domains/transfer/out') - ->desc("Start transfer process for domain and generate code for transfer to 3rd party registrar") + ->desc('Start transfer process for domain and generate code for transfer to 3rd party registrar') ->groups(['api', 'domains']) ->label('scope', 'projects.write') ->label('sdk.auth', [APP_AUTH_TYPE_ADMIN]) @@ -397,7 +381,7 @@ App::post('/v1/domains/transfer/out') }); App::get('/v1/domains') - ->desc("List domains") + ->desc('List domains') ->groups(['api', 'domains']) ->label('scope', 'projects.read') ->label('sdk.auth', [APP_AUTH_TYPE_ADMIN]) @@ -410,26 +394,25 @@ App::get('/v1/domains') ->inject('response') ->inject('dbForConsole') ->action(function (string $projectId, Response $response, Database $dbForConsole) { - $project = $dbForConsole->getDocument('projects', $projectId); + $project = $dbForConsole->getDocument('projects', $projectId); - if ($project->isEmpty()) { - throw new Exception(Exception::PROJECT_NOT_FOUND); - } + if ($project->isEmpty()) { + throw new Exception(Exception::PROJECT_NOT_FOUND); + } - $domains = $dbForConsole->find('domains', [ - Query::equal('projectInternalId', [$project->getInternalId()]), - Query::limit(5000), - ]); - - $response->dynamic(new Document([ - 'domains' => $domains, - 'total' => count($domains), - ]), Response::MODEL_DOMAIN_LIST); + $domains = $dbForConsole->find('domains', [ + Query::equal('projectInternalId', [$project->getInternalId()]), + Query::limit(5000), + ]); + $response->dynamic(new Document([ + 'domains' => $domains, + 'total' => count($domains), + ]), Response::MODEL_DOMAIN_LIST); }); App::get('/v1/domains/:domainId') - ->desc("Get domain") + ->desc('Get domain') ->groups(['api', 'domains']) ->label('scope', 'projects.read') ->label('sdk.auth', [APP_AUTH_TYPE_ADMIN]) @@ -443,27 +426,26 @@ App::get('/v1/domains/:domainId') ->inject('response') ->inject('dbForConsole') ->action(function (string $projectId, string $domainId, Response $response, Database $dbForConsole) { + $project = $dbForConsole->getDocument('projects', $projectId); - $project = $dbForConsole->getDocument('projects', $projectId); + if ($project->isEmpty()) { + throw new Exception(Exception::PROJECT_NOT_FOUND); + } - if ($project->isEmpty()) { - throw new Exception(Exception::PROJECT_NOT_FOUND); - } + $domain = $dbForConsole->findOne('domains', [ + Query::equal('_uid', [$domainId]), + Query::equal('projectInternalId', [$project->getInternalId()]), + ]); - $domain = $dbForConsole->findOne('domains', [ - Query::equal('_uid', [$domainId]), - Query::equal('projectInternalId', [$project->getInternalId()]), - ]); + if ($domain === false || $domain->isEmpty()) { + throw new Exception(Exception::DOMAIN_NOT_FOUND); + } - if ($domain === false || $domain->isEmpty()) { - throw new Exception(Exception::DOMAIN_NOT_FOUND); - } - - $response->dynamic($domain, Response::MODEL_DOMAIN); + $response->dynamic($domain, Response::MODEL_DOMAIN); }); App::patch('/v1/domains/:domainId/nameservers') - ->desc("Check namserver records and update them if needed") + ->desc('Check namserver records and update them if needed') ->groups(['api', 'domains']) ->label('scope', 'projects.write') ->label('sdk.auth', [APP_AUTH_TYPE_ADMIN]) @@ -476,11 +458,11 @@ App::patch('/v1/domains/:domainId/nameservers') ->inject('response') ->inject('user') ->action(function () { - ///Do we need/want? + ///Do we need/want? }); App::patch('/v1/domains/:domainId/project') - ->desc("Move domain to a different project") + ->desc('Move domain to a different project') ->groups(['api', 'domains']) ->label('scope', 'projects.write') ->label('sdk.auth', [APP_AUTH_TYPE_ADMIN]) @@ -493,11 +475,11 @@ App::patch('/v1/domains/:domainId/project') ->inject('response') ->inject('user') ->action(function () { - /// WAIT FOR TRANSFER SERVICE. + /// WAIT FOR TRANSFER SERVICE. }); App::delete('/v1/domains/:domainId') - ->desc("Remove a domain") + ->desc('Remove a domain') ->groups(['api', 'domains']) ->label('scope', 'projects.write') ->label('sdk.auth', [APP_AUTH_TYPE_ADMIN]) @@ -511,25 +493,24 @@ App::delete('/v1/domains/:domainId') ->inject('response') ->inject('dbForConsole') ->action(function (string $projectId, string $domainId, Response $response, Database $dbForConsole) { + $project = $dbForConsole->getDocument('projects', $projectId); - $project = $dbForConsole->getDocument('projects', $projectId); + if ($project->isEmpty()) { + throw new Exception(Exception::PROJECT_NOT_FOUND); + } - if ($project->isEmpty()) { - throw new Exception(Exception::PROJECT_NOT_FOUND); - } + $domain = $dbForConsole->findOne('domains', [ + Query::equal('_uid', [$domainId]), + Query::equal('projectInternalId', [$project->getInternalId()]), + ]); - $domain = $dbForConsole->findOne('domains', [ - Query::equal('_uid', [$domainId]), - Query::equal('projectInternalId', [$project->getInternalId()]), - ]); + if ($domain === false || $domain->isEmpty()) { + throw new Exception(Exception::DOMAIN_NOT_FOUND); + } - if ($domain === false || $domain->isEmpty()) { - throw new Exception(Exception::DOMAIN_NOT_FOUND); - } + if ($domain['registered'] === true) { + throw new Exception(); + } - if($domain['registered'] === true) { - throw new Exception(); - } - - $response->noContent(); + $response->noContent(); }); diff --git a/app/controllers/api/functions.php b/app/controllers/api/functions.php index 049d2cb850..25603949ce 100644 --- a/app/controllers/api/functions.php +++ b/app/controllers/api/functions.php @@ -8,44 +8,43 @@ use Appwrite\Event\Event; use Appwrite\Event\Func; use Appwrite\Event\Validator\Event as ValidatorEvent; use Appwrite\Extend\Exception; +use Appwrite\Task\Validator\Cron; +use Appwrite\Usage\Stats; use Appwrite\Utopia\Database\Validator\CustomId; +use Appwrite\Utopia\Database\Validator\Queries\Deployments; +use Appwrite\Utopia\Database\Validator\Queries\Executions; +use Appwrite\Utopia\Database\Validator\Queries\Functions; +use Appwrite\Utopia\Database\Validator\Queries\Variables; +use Appwrite\Utopia\Response; +use Cron\CronExpression; +use Executor\Executor; +use Utopia\App; +use Utopia\CLI\Console; +use Utopia\Config\Config; +use Utopia\Database\Database; +use Utopia\Database\DateTime; +use Utopia\Database\Document; +use Utopia\Database\Exception\Duplicate as DuplicateException; use Utopia\Database\Helpers\ID; use Utopia\Database\Helpers\Permission; use Utopia\Database\Helpers\Role; +use Utopia\Database\Query; +use Utopia\Database\Validator\Authorization; +use Utopia\Database\Validator\Roles; use Utopia\Database\Validator\UID; -use Appwrite\Usage\Stats; use Utopia\Storage\Device; use Utopia\Storage\Validator\File; use Utopia\Storage\Validator\FileExt; use Utopia\Storage\Validator\FileSize; use Utopia\Storage\Validator\Upload; -use Appwrite\Utopia\Response; use Utopia\Swoole\Request; -use Appwrite\Task\Validator\Cron; -use Appwrite\Utopia\Database\Validator\Queries\Deployments; -use Appwrite\Utopia\Database\Validator\Queries\Executions; -use Appwrite\Utopia\Database\Validator\Queries\Functions; -use Appwrite\Utopia\Database\Validator\Queries\Variables; -use Utopia\App; -use Utopia\Database\Database; -use Utopia\Database\Document; -use Utopia\Database\DateTime; -use Utopia\Database\Query; -use Utopia\Database\Validator\Authorization; use Utopia\Validator\ArrayList; -use Utopia\Validator\Assoc; -use Utopia\Validator\Text; -use Utopia\Validator\Range; -use Utopia\Validator\WhiteList; -use Utopia\Config\Config; -use Cron\CronExpression; -use Executor\Executor; -use Utopia\CLI\Console; -use Utopia\Database\Validator\Roles; use Utopia\Validator\Boolean; -use Utopia\Database\Exception\Duplicate as DuplicateException; +use Utopia\Validator\Range; +use Utopia\Validator\Text; +use Utopia\Validator\WhiteList; -include_once __DIR__ . '/../shared/api.php'; +include_once __DIR__.'/../shared/api.php'; App::post('/v1/functions') ->groups(['api', 'functions']) @@ -63,9 +62,9 @@ App::post('/v1/functions') ->label('sdk.response.model', Response::MODEL_FUNCTION) ->param('functionId', '', new CustomId(), 'Function ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can\'t start with a special char. Max length is 36 chars.') ->param('name', '', new Text(128), 'Function name. Max length: 128 chars.') - ->param('execute', [], new Roles(APP_LIMIT_ARRAY_PARAMS_SIZE), 'An array of strings with execution roles. By default no user is granted with any execute permissions. [learn more about permissions](https://appwrite.io/docs/permissions). Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' roles are allowed, each 64 characters long.') + ->param('execute', [], new Roles(APP_LIMIT_ARRAY_PARAMS_SIZE), 'An array of strings with execution roles. By default no user is granted with any execute permissions. [learn more about permissions](https://appwrite.io/docs/permissions). Maximum of '.APP_LIMIT_ARRAY_PARAMS_SIZE.' roles are allowed, each 64 characters long.') ->param('runtime', '', new WhiteList(array_keys(Config::getParam('runtimes')), true), 'Execution runtime.') - ->param('events', [], new ArrayList(new ValidatorEvent(), APP_LIMIT_ARRAY_PARAMS_SIZE), 'Events list. Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' events are allowed.', true) + ->param('events', [], new ArrayList(new ValidatorEvent(), APP_LIMIT_ARRAY_PARAMS_SIZE), 'Events list. Maximum of '.APP_LIMIT_ARRAY_PARAMS_SIZE.' events are allowed.', true) ->param('schedule', '', new Cron(), 'Schedule CRON syntax.', true) ->param('timeout', 15, new Range(1, (int) App::getEnv('_APP_FUNCTIONS_TIMEOUT', 900)), 'Function maximum execution time in seconds.', true) ->param('enabled', true, new Boolean(), 'Is function enabled?', true) @@ -75,9 +74,8 @@ App::post('/v1/functions') ->inject('user') ->inject('events') ->action(function (string $functionId, string $name, array $execute, string $runtime, array $events, string $schedule, int $timeout, bool $enabled, Response $response, Database $dbForProject, Document $project, Document $user, Event $eventsInstance) { - - $cron = !empty($schedule) ? new CronExpression($schedule) : null; - $next = !empty($schedule) ? DateTime::format($cron->getNextRunDate()) : null; + $cron = ! empty($schedule) ? new CronExpression($schedule) : null; + $next = ! empty($schedule) ? DateTime::format($cron->getNextRunDate()) : null; $functionId = ($functionId == 'unique()') ? ID::unique() : $functionId; $function = $dbForProject->createDocument('functions', new Document([ @@ -93,7 +91,7 @@ App::post('/v1/functions') 'schedulePrevious' => null, 'scheduleNext' => $next, 'timeout' => $timeout, - 'search' => implode(' ', [$functionId, $name, $runtime]) + 'search' => implode(' ', [$functionId, $name, $runtime]), ])); if ($next) { @@ -125,15 +123,14 @@ App::get('/v1/functions') ->label('sdk.response.code', Response::STATUS_CODE_OK) ->label('sdk.response.type', Response::CONTENT_TYPE_JSON) ->label('sdk.response.model', Response::MODEL_FUNCTION_LIST) - ->param('queries', [], new Functions(), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/databases#querying-documents). Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' queries are allowed, each ' . APP_LIMIT_ARRAY_ELEMENT_SIZE . ' characters long. You may filter on the following attributes: ' . implode(', ', Functions::ALLOWED_ATTRIBUTES), true) + ->param('queries', [], new Functions(), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/databases#querying-documents). Maximum of '.APP_LIMIT_ARRAY_PARAMS_SIZE.' queries are allowed, each '.APP_LIMIT_ARRAY_ELEMENT_SIZE.' characters long. You may filter on the following attributes: '.implode(', ', Functions::ALLOWED_ATTRIBUTES), true) ->param('search', '', new Text(256), 'Search term to filter your list results. Max length: 256 chars.', true) ->inject('response') ->inject('dbForProject') ->action(function (array $queries, string $search, Response $response, Database $dbForProject) { - $queries = Query::parseQueries($queries); - if (!empty($search)) { + if (! empty($search)) { $queries[] = Query::search('search', $search); } @@ -173,17 +170,17 @@ App::get('/v1/functions/runtimes') ->label('sdk.response.model', Response::MODEL_RUNTIME_LIST) ->inject('response') ->action(function (Response $response) { - $runtimes = Config::getParam('runtimes'); $runtimes = array_map(function ($key) use ($runtimes) { $runtimes[$key]['$id'] = $key; + return $runtimes[$key]; }, array_keys($runtimes)); $response->dynamic(new Document([ 'total' => count($runtimes), - 'runtimes' => $runtimes + 'runtimes' => $runtimes, ]), Response::MODEL_RUNTIME_LIST); }); @@ -226,7 +223,6 @@ App::get('/v1/functions/:functionId/usage') ->inject('response') ->inject('dbForProject') ->action(function (string $functionId, string $range, Response $response, Database $dbForProject) { - $function = $dbForProject->getDocument('functions', $functionId); if ($function->isEmpty()) { @@ -314,7 +310,7 @@ App::get('/v1/functions/:functionId/usage') 'buildsTotal' => $stats["builds.$functionId.compute.total"] ?? [], 'buildsFailure' => $stats["builds.$functionId.compute.failure"] ?? [], 'buildsSuccess' => $stats["builds.$functionId.compute.success"] ?? [], - 'buildsTime' => $stats["builds.$functionId.compute.time" ?? []] + 'buildsTime' => $stats["builds.$functionId.compute.time" ?? []], ]); } @@ -335,7 +331,6 @@ App::get('/v1/functions/usage') ->inject('response') ->inject('dbForProject') ->action(function (string $range, Response $response, Database $dbForProject) { - $usage = []; if (App::getEnv('_APP_USAGE_STATS', 'enabled') == 'enabled') { $periods = [ @@ -440,8 +435,8 @@ App::put('/v1/functions/:functionId') ->label('sdk.response.model', Response::MODEL_FUNCTION) ->param('functionId', '', new UID(), 'Function ID.') ->param('name', '', new Text(128), 'Function name. Max length: 128 chars.') - ->param('execute', [], new Roles(APP_LIMIT_ARRAY_PARAMS_SIZE), 'An array of strings with execution roles. By default no user is granted with any execute permissions. [learn more about permissions](https://appwrite.io/docs/permissions). Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' roles are allowed, each 64 characters long.') - ->param('events', [], new ArrayList(new ValidatorEvent(), APP_LIMIT_ARRAY_PARAMS_SIZE), 'Events list. Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' events are allowed.', true) + ->param('execute', [], new Roles(APP_LIMIT_ARRAY_PARAMS_SIZE), 'An array of strings with execution roles. By default no user is granted with any execute permissions. [learn more about permissions](https://appwrite.io/docs/permissions). Maximum of '.APP_LIMIT_ARRAY_PARAMS_SIZE.' roles are allowed, each 64 characters long.') + ->param('events', [], new ArrayList(new ValidatorEvent(), APP_LIMIT_ARRAY_PARAMS_SIZE), 'Events list. Maximum of '.APP_LIMIT_ARRAY_PARAMS_SIZE.' events are allowed.', true) ->param('schedule', '', new Cron(), 'Schedule CRON syntax.', true) ->param('timeout', 15, new Range(1, (int) App::getEnv('_APP_FUNCTIONS_TIMEOUT', 900)), 'Maximum execution time in seconds.', true) ->param('enabled', true, new Boolean(), 'Is function enabled?', true) @@ -451,15 +446,14 @@ App::put('/v1/functions/:functionId') ->inject('user') ->inject('events') ->action(function (string $functionId, string $name, array $execute, array $events, string $schedule, int $timeout, bool $enabled, Response $response, Database $dbForProject, Document $project, Document $user, Event $eventsInstance) { - $function = $dbForProject->getDocument('functions', $functionId); if ($function->isEmpty()) { throw new Exception(Exception::FUNCTION_NOT_FOUND); } - $cron = !empty($schedule) ? new CronExpression($schedule) : null; - $next = !empty($schedule) ? DateTime::format($cron->getNextRunDate()) : null; + $cron = ! empty($schedule) ? new CronExpression($schedule) : null; + $next = ! empty($schedule) ? DateTime::format($cron->getNextRunDate()) : null; $enabled ??= $function->getAttribute('enabled', true); @@ -512,7 +506,6 @@ App::patch('/v1/functions/:functionId/deployments/:deploymentId') ->inject('project') ->inject('events') ->action(function (string $functionId, string $deploymentId, Response $response, Database $dbForProject, Document $project, Event $events) { - $function = $dbForProject->getDocument('functions', $functionId); $deployment = $dbForProject->getDocument('deployments', $deploymentId); $build = $dbForProject->getDocument('builds', $deployment->getAttribute('buildId', '')); @@ -534,7 +527,7 @@ App::patch('/v1/functions/:functionId/deployments/:deploymentId') } $function = $dbForProject->updateDocument('functions', $function->getId(), new Document(array_merge($function->getArrayCopy(), [ - 'deployment' => $deployment->getId() + 'deployment' => $deployment->getId(), ]))); $events @@ -563,14 +556,13 @@ App::delete('/v1/functions/:functionId') ->inject('deletes') ->inject('events') ->action(function (string $functionId, Response $response, Database $dbForProject, Delete $deletes, Event $events) { - $function = $dbForProject->getDocument('functions', $functionId); if ($function->isEmpty()) { throw new Exception(Exception::FUNCTION_NOT_FOUND); } - if (!$dbForProject->deleteDocument('functions', $function->getId())) { + if (! $dbForProject->deleteDocument('functions', $function->getId())) { throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Failed to remove function from DB'); } @@ -611,7 +603,6 @@ App::post('/v1/functions/:functionId/deployments') ->inject('deviceFunctions') ->inject('deviceLocal') ->action(function (string $functionId, string $entrypoint, mixed $code, bool $activate, Request $request, Response $response, Database $dbForProject, Event $events, Document $project, Device $deviceFunctions, Device $deviceLocal) { - $function = $dbForProject->getDocument('functions', $functionId); if ($function->isEmpty()) { @@ -638,7 +629,7 @@ App::post('/v1/functions/:functionId/deployments') $fileTmpName = (\is_array($file['tmp_name']) && isset($file['tmp_name'][0])) ? $file['tmp_name'][0] : $file['tmp_name']; $fileSize = (\is_array($file['size']) && isset($file['size'][0])) ? $file['size'][0] : $file['size']; - if (!$fileExt->isValid($file['name'])) { // Check if file type is allowed + if (! $fileExt->isValid($file['name'])) { // Check if file type is allowed throw new Exception(Exception::STORAGE_FILE_TYPE_UNSUPPORTED); } @@ -647,7 +638,7 @@ App::post('/v1/functions/:functionId/deployments') $chunk = 1; $chunks = 1; - if (!empty($contentRange)) { + if (! empty($contentRange)) { $start = $request->getContentRangeStart(); $end = $request->getContentRangeEnd(); $fileSize = $request->getContentRangeSize(); @@ -666,22 +657,22 @@ App::post('/v1/functions/:functionId/deployments') } } - if (!$fileSizeValidator->isValid($fileSize)) { // Check if file size is exceeding allowed limit + if (! $fileSizeValidator->isValid($fileSize)) { // Check if file size is exceeding allowed limit throw new Exception(Exception::STORAGE_INVALID_FILE_SIZE); } - if (!$upload->isValid($fileTmpName)) { + if (! $upload->isValid($fileTmpName)) { throw new Exception(Exception::STORAGE_INVALID_FILE); } // Save to storage $fileSize ??= $deviceLocal->getFileSize($fileTmpName); - $path = $deviceFunctions->getPath($deploymentId . '.' . \pathinfo($fileName, PATHINFO_EXTENSION)); + $path = $deviceFunctions->getPath($deploymentId.'.'.\pathinfo($fileName, PATHINFO_EXTENSION)); $deployment = $dbForProject->getDocument('deployments', $deploymentId); $metadata = ['content_type' => $deviceLocal->getFileMimeType($fileTmpName)]; - if (!$deployment->isEmpty()) { + if (! $deployment->isEmpty()) { $chunks = $deployment->getAttribute('chunksTotal', 1); $metadata = $deployment->getAttribute('metadata', []); if ($chunk === -1) { @@ -703,7 +694,7 @@ App::post('/v1/functions/:functionId/deployments') $activeDeployments = $dbForProject->find('deployments', [ Query::equal('activate', [true]), Query::equal('resourceId', [$functionId]), - Query::equal('resourceType', ['functions']) + Query::equal('resourceType', ['functions']), ]); foreach ($activeDeployments as $activeDeployment) { @@ -791,12 +782,11 @@ App::get('/v1/functions/:functionId/deployments') ->label('sdk.response.type', Response::CONTENT_TYPE_JSON) ->label('sdk.response.model', Response::MODEL_DEPLOYMENT_LIST) ->param('functionId', '', new UID(), 'Function ID.') - ->param('queries', [], new Deployments(), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/databases#querying-documents). Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' queries are allowed, each ' . APP_LIMIT_ARRAY_ELEMENT_SIZE . ' characters long. You may filter on the following attributes: ' . implode(', ', Deployments::ALLOWED_ATTRIBUTES), true) + ->param('queries', [], new Deployments(), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/databases#querying-documents). Maximum of '.APP_LIMIT_ARRAY_PARAMS_SIZE.' queries are allowed, each '.APP_LIMIT_ARRAY_ELEMENT_SIZE.' characters long. You may filter on the following attributes: '.implode(', ', Deployments::ALLOWED_ATTRIBUTES), true) ->param('search', '', new Text(256), 'Search term to filter your list results. Max length: 256 chars.', true) ->inject('response') ->inject('dbForProject') ->action(function (string $functionId, array $queries, string $search, Response $response, Database $dbForProject) { - $function = $dbForProject->getDocument('functions', $functionId); if ($function->isEmpty()) { @@ -805,7 +795,7 @@ App::get('/v1/functions/:functionId/deployments') $queries = Query::parseQueries($queries); - if (!empty($search)) { + if (! empty($search)) { $queries[] = Query::search('search', $search); } @@ -863,7 +853,6 @@ App::get('/v1/functions/:functionId/deployments/:deploymentId') ->inject('response') ->inject('dbForProject') ->action(function (string $functionId, string $deploymentId, Response $response, Database $dbForProject) { - $function = $dbForProject->getDocument('functions', $functionId); if ($function->isEmpty()) { @@ -909,7 +898,6 @@ App::delete('/v1/functions/:functionId/deployments/:deploymentId') ->inject('events') ->inject('deviceFunctions') ->action(function (string $functionId, string $deploymentId, Response $response, Database $dbForProject, Delete $deletes, Event $events, Device $deviceFunctions) { - $function = $dbForProject->getDocument('functions', $functionId); if ($function->isEmpty()) { throw new Exception(Exception::FUNCTION_NOT_FOUND); @@ -925,7 +913,7 @@ App::delete('/v1/functions/:functionId/deployments/:deploymentId') } if ($deviceFunctions->delete($deployment->getAttribute('path', ''))) { - if (!$dbForProject->deleteDocument('deployments', $deployment->getId())) { + if (! $dbForProject->deleteDocument('deployments', $deployment->getId())) { throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Failed to remove deployment from DB'); } } @@ -968,7 +956,6 @@ App::post('/v1/functions/:functionId/deployments/:deploymentId/builds/:buildId') ->inject('project') ->inject('events') ->action(function (string $functionId, string $deploymentId, string $buildId, Response $response, Database $dbForProject, Document $project, Event $events) { - $function = $dbForProject->getDocument('functions', $functionId); $deployment = $dbForProject->getDocument('deployments', $deploymentId); @@ -1006,8 +993,6 @@ App::post('/v1/functions/:functionId/deployments/:deploymentId/builds/:buildId') $response->noContent(); }); - - App::post('/v1/functions/:functionId/executions') ->groups(['api', 'functions']) ->desc('Create Execution') @@ -1034,11 +1019,10 @@ App::post('/v1/functions/:functionId/executions') ->inject('usage') ->inject('mode') ->action(function (string $functionId, string $data, bool $async, Response $response, Document $project, Database $dbForProject, Document $user, Event $events, Stats $usage, string $mode) { - $function = Authorization::skip(fn () => $dbForProject->getDocument('functions', $functionId)); - if ($function->isEmpty() || !$function->getAttribute('enabled')) { - if (!($mode === APP_MODE_ADMIN && Auth::isPrivilegedUser(Authorization::getRoles()))) { + if ($function->isEmpty() || ! $function->getAttribute('enabled')) { + if (! ($mode === APP_MODE_ADMIN && Auth::isPrivilegedUser(Authorization::getRoles()))) { throw new Exception(Exception::FUNCTION_NOT_FOUND); } } @@ -1048,7 +1032,7 @@ App::post('/v1/functions/:functionId/executions') $runtime = (isset($runtimes[$function->getAttribute('runtime', '')])) ? $runtimes[$function->getAttribute('runtime', '')] : null; if (\is_null($runtime)) { - throw new Exception(Exception::FUNCTION_RUNTIME_UNSUPPORTED, 'Runtime "' . $function->getAttribute('runtime', '') . '" is not supported'); + throw new Exception(Exception::FUNCTION_RUNTIME_UNSUPPORTED, 'Runtime "'.$function->getAttribute('runtime', '').'" is not supported'); } $deployment = Authorization::skip(fn () => $dbForProject->getDocument('deployments', $function->getAttribute('deployment', ''))); @@ -1073,7 +1057,7 @@ App::post('/v1/functions/:functionId/executions') $validator = new Authorization('execute'); - if (!$validator->isValid($function->getAttribute('execute'))) { // Check if user has write access to execute function + if (! $validator->isValid($function->getAttribute('execute'))) { // Check if user has write access to execute function throw new Exception(Exception::USER_UNAUTHORIZED, $validator->getDescription()); } @@ -1082,7 +1066,7 @@ App::post('/v1/functions/:functionId/executions') /** @var Document $execution */ $execution = Authorization::skip(fn () => $dbForProject->createDocument('executions', new Document([ '$id' => $executionId, - '$permissions' => !$user->isEmpty() ? [Permission::read(Role::user($user->getId()))] : [], + '$permissions' => ! $user->isEmpty() ? [Permission::read(Role::user($user->getId()))] : [], 'functionId' => $function->getId(), 'deploymentId' => $deployment->getId(), 'trigger' => 'http', // http / schedule / event @@ -1095,7 +1079,7 @@ App::post('/v1/functions/:functionId/executions') ]))); $jwt = ''; // initialize - if (!$user->isEmpty()) { // If userId exists, generate a JWT for function + if (! $user->isEmpty()) { // If userId exists, generate a JWT for function $sessions = $user->getAttribute('sessions', []); $current = new Document(); @@ -1106,7 +1090,7 @@ App::post('/v1/functions/:functionId/executions') } } - if (!$current->isEmpty()) { + if (! $current->isEmpty()) { $jwtObj = new JWT(App::getEnv('_APP_OPENSSL_KEY_V1'), 'HS256', 900, 10); // Instantiate with key, algo, maxAge and leeway. $jwt = $jwtObj->encode([ 'userId' => $user->getId(), @@ -1140,6 +1124,7 @@ App::post('/v1/functions/:functionId/executions') $vars = array_reduce($function['vars'] ?? [], function (array $carry, Document $var) { $carry[$var->getAttribute('key')] = $var->getAttribute('value') ?? ''; + return $carry; }, []); @@ -1181,7 +1166,7 @@ App::post('/v1/functions/:functionId/executions') } catch (\Throwable $th) { $interval = (new \DateTime())->diff(new \DateTime($execution->getCreatedAt())); $execution - ->setAttribute('duration', (float)$interval->format('%s.%f')) + ->setAttribute('duration', (float) $interval->format('%s.%f')) ->setAttribute('status', 'failed') ->setAttribute('statusCode', $th->getCode()) ->setAttribute('stderr', $th->getMessage()); @@ -1201,7 +1186,7 @@ App::post('/v1/functions/:functionId/executions') $isPrivilegedUser = Auth::isPrivilegedUser($roles); $isAppUser = Auth::isAppUser($roles); - if (!$isPrivilegedUser && !$isAppUser) { + if (! $isPrivilegedUser && ! $isAppUser) { $execution->setAttribute('stdout', ''); $execution->setAttribute('stderr', ''); } @@ -1223,24 +1208,23 @@ App::get('/v1/functions/:functionId/executions') ->label('sdk.response.type', Response::CONTENT_TYPE_JSON) ->label('sdk.response.model', Response::MODEL_EXECUTION_LIST) ->param('functionId', '', new UID(), 'Function ID.') - ->param('queries', [], new Executions(), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/databases#querying-documents). Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' queries are allowed, each ' . APP_LIMIT_ARRAY_ELEMENT_SIZE . ' characters long. You may filter on the following attributes: ' . implode(', ', Executions::ALLOWED_ATTRIBUTES), true) + ->param('queries', [], new Executions(), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/databases#querying-documents). Maximum of '.APP_LIMIT_ARRAY_PARAMS_SIZE.' queries are allowed, each '.APP_LIMIT_ARRAY_ELEMENT_SIZE.' characters long. You may filter on the following attributes: '.implode(', ', Executions::ALLOWED_ATTRIBUTES), true) ->param('search', '', new Text(256), 'Search term to filter your list results. Max length: 256 chars.', true) ->inject('response') ->inject('dbForProject') ->inject('mode') ->action(function (string $functionId, array $queries, string $search, Response $response, Database $dbForProject, string $mode) { - $function = Authorization::skip(fn () => $dbForProject->getDocument('functions', $functionId)); - if ($function->isEmpty() || !$function->getAttribute('enabled')) { - if (!($mode === APP_MODE_ADMIN && Auth::isPrivilegedUser(Authorization::getRoles()))) { + if ($function->isEmpty() || ! $function->getAttribute('enabled')) { + if (! ($mode === APP_MODE_ADMIN && Auth::isPrivilegedUser(Authorization::getRoles()))) { throw new Exception(Exception::FUNCTION_NOT_FOUND); } } $queries = Query::parseQueries($queries); - if (!empty($search)) { + if (! empty($search)) { $queries[] = Query::search('search', $search); } @@ -1270,10 +1254,11 @@ App::get('/v1/functions/:functionId/executions') $roles = Authorization::getRoles(); $isPrivilegedUser = Auth::isPrivilegedUser($roles); $isAppUser = Auth::isAppUser($roles); - if (!$isPrivilegedUser && !$isAppUser) { + if (! $isPrivilegedUser && ! $isAppUser) { $results = array_map(function ($execution) { $execution->setAttribute('stdout', ''); $execution->setAttribute('stderr', ''); + return $execution; }, $results); } @@ -1301,11 +1286,10 @@ App::get('/v1/functions/:functionId/executions/:executionId') ->inject('dbForProject') ->inject('mode') ->action(function (string $functionId, string $executionId, Response $response, Database $dbForProject, string $mode) { - $function = Authorization::skip(fn () => $dbForProject->getDocument('functions', $functionId)); - if ($function->isEmpty() || !$function->getAttribute('enabled')) { - if (!($mode === APP_MODE_ADMIN && Auth::isPrivilegedUser(Authorization::getRoles()))) { + if ($function->isEmpty() || ! $function->getAttribute('enabled')) { + if (! ($mode === APP_MODE_ADMIN && Auth::isPrivilegedUser(Authorization::getRoles()))) { throw new Exception(Exception::FUNCTION_NOT_FOUND); } } @@ -1323,7 +1307,7 @@ App::get('/v1/functions/:functionId/executions/:executionId') $roles = Authorization::getRoles(); $isPrivilegedUser = Auth::isPrivilegedUser($roles); $isAppUser = Auth::isAppUser($roles); - if (!$isPrivilegedUser && !$isAppUser) { + if (! $isPrivilegedUser && ! $isAppUser) { $execution->setAttribute('stdout', ''); $execution->setAttribute('stderr', ''); } @@ -1347,7 +1331,7 @@ App::post('/v1/functions/:functionId/variables') ->label('sdk.response.type', Response::CONTENT_TYPE_JSON) ->label('sdk.response.model', Response::MODEL_VARIABLE) ->param('functionId', '', new UID(), 'Function unique ID.', false) - ->param('key', null, new Text(Database::LENGTH_KEY), 'Variable key. Max length: ' . Database::LENGTH_KEY . ' chars.', false) + ->param('key', null, new Text(Database::LENGTH_KEY), 'Variable key. Max length: '.Database::LENGTH_KEY.' chars.', false) ->param('value', null, new Text(8192), 'Variable value. Max length: 8192 chars.', false) ->inject('response') ->inject('dbForProject') @@ -1468,7 +1452,6 @@ App::put('/v1/functions/:functionId/variables/:variableId') ->inject('response') ->inject('dbForProject') ->action(function (string $functionId, string $variableId, string $key, ?string $value, Response $response, Database $dbForProject) { - $function = $dbForProject->getDocument('functions', $functionId); if ($function->isEmpty()) { @@ -1487,8 +1470,7 @@ App::put('/v1/functions/:functionId/variables/:variableId') $variable ->setAttribute('key', $key) ->setAttribute('value', $value ?? $variable->getAttribute('value')) - ->setAttribute('search', implode(' ', [$variableId, $function->getId(), $key])) - ; + ->setAttribute('search', implode(' ', [$variableId, $function->getId(), $key])); try { $dbForProject->updateDocument('variables', $variable->getId(), $variable); diff --git a/app/controllers/api/graphql.php b/app/controllers/api/graphql.php index bbc382d976..36b467df1a 100644 --- a/app/controllers/api/graphql.php +++ b/app/controllers/api/graphql.php @@ -42,11 +42,11 @@ App::get('/v1/graphql') 'query' => $query, ]; - if (!empty($operationName)) { + if (! empty($operationName)) { $query['operationName'] = $operationName; } - if (!empty($variables)) { + if (! empty($variables)) { $query['variables'] = \json_decode($variables, true); } @@ -150,10 +150,11 @@ App::post('/v1/graphql') /** * Execute a GraphQL request * - * @param GQLSchema $schema - * @param Adapter $promiseAdapter - * @param array $query + * @param GQLSchema $schema + * @param Adapter $promiseAdapter + * @param array $query * @return array + * * @throws Exception */ function execute( @@ -165,7 +166,7 @@ function execute( $maxComplexity = App::getEnv('_APP_GRAPHQL_MAX_COMPLEXITY', 250); $maxDepth = App::getEnv('_APP_GRAPHQL_MAX_DEPTH', 3); - if (!empty($query) && !isset($query[0])) { + if (! empty($query) && ! isset($query[0])) { $query = [$query]; } if (empty($query)) { @@ -224,7 +225,7 @@ function execute( /** * Parse an "application/graphql" type request * - * @param Request $request + * @param Request $request * @return array */ function parseGraphql(Request $request): array @@ -235,8 +236,8 @@ function parseGraphql(Request $request): array /** * Parse an "multipart/form-data" type request * - * @param array $query - * @param Request $request + * @param array $query + * @param Request $request * @return array */ function parseMultipart(array $query, Request $request): array @@ -248,7 +249,7 @@ function parseMultipart(array $query, Request $request): array foreach ($locations as $location) { $items = &$operations; foreach (\explode('.', $location) as $key) { - if (!isset($items[$key]) || !\is_array($items[$key])) { + if (! isset($items[$key]) || ! \is_array($items[$key])) { $items[$key] = []; } $items = &$items[$key]; @@ -276,7 +277,7 @@ function parseMultipart(array $query, Request $request): array function processResult($result, $debugFlags): array { // Only one query, return the result - if (!isset($result[1])) { + if (! isset($result[1])) { return $result[0]->toArray($debugFlags); } diff --git a/app/controllers/api/health.php b/app/controllers/api/health.php index 4384fcbcd5..04e43a2264 100644 --- a/app/controllers/api/health.php +++ b/app/controllers/api/health.php @@ -24,10 +24,9 @@ App::get('/v1/health') ->label('sdk.response.model', Response::MODEL_HEALTH_STATUS) ->inject('response') ->action(function (Response $response) { - $output = [ 'status' => 'pass', - 'ping' => 0 + 'ping' => 0, ]; $response->dynamic(new Document($output), Response::MODEL_HEALTH_STATUS); @@ -42,8 +41,7 @@ App::get('/v1/health/version') ->label('sdk.response.model', Response::MODEL_HEALTH_VERSION) ->inject('response') ->action(function (Response $response) { - - $response->dynamic(new Document([ 'version' => APP_VERSION_STABLE ]), Response::MODEL_HEALTH_VERSION); + $response->dynamic(new Document(['version' => APP_VERSION_STABLE]), Response::MODEL_HEALTH_VERSION); }); App::get('/v1/health/db') @@ -60,14 +58,13 @@ App::get('/v1/health/db') ->inject('response') ->inject('utopia') ->action(function (Response $response, App $utopia) { - $checkStart = \microtime(true); try { $db = $utopia->getResource('db'); /* @var $db PDO */ // Run a small test to check the connection - $statement = $db->prepare("SELECT 1;"); + $statement = $db->prepare('SELECT 1;'); $statement->closeCursor(); @@ -78,7 +75,7 @@ App::get('/v1/health/db') $output = [ 'status' => 'pass', - 'ping' => \round((\microtime(true) - $checkStart) / 1000) + 'ping' => \round((\microtime(true) - $checkStart) / 1000), ]; $response->dynamic(new Document($output), Response::MODEL_HEALTH_STATUS); @@ -98,18 +95,17 @@ App::get('/v1/health/cache') ->inject('response') ->inject('utopia') ->action(function (Response $response, App $utopia) { - $checkStart = \microtime(true); $redis = $utopia->getResource('cache'); - if (!$redis->ping(true)) { + if (! $redis->ping(true)) { throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Cache is not available'); } $output = [ 'status' => 'pass', - 'ping' => \round((\microtime(true) - $checkStart) / 1000) + 'ping' => \round((\microtime(true) - $checkStart) / 1000), ]; $response->dynamic(new Document($output), Response::MODEL_HEALTH_STATUS); @@ -128,7 +124,6 @@ App::get('/v1/health/time') ->label('sdk.response.model', Response::MODEL_HEALTH_TIME) ->inject('response') ->action(function (Response $response) { - /* * Code from: @see https://www.beliefmedia.com.au/query-ntp-time-server */ @@ -141,7 +136,7 @@ App::get('/v1/health/time') \socket_connect($sock, $host, 123); /* Send request */ - $msg = "\010" . \str_repeat("\0", 47); + $msg = "\010".\str_repeat("\0", 47); \socket_send($sock, $msg, \strlen($msg), 0); @@ -166,7 +161,7 @@ App::get('/v1/health/time') $output = [ 'remoteTime' => $timestamp, 'localTime' => \time(), - 'diff' => $diff + 'diff' => $diff, ]; $response->dynamic(new Document($output), Response::MODEL_HEALTH_TIME); @@ -185,8 +180,7 @@ App::get('/v1/health/queue/webhooks') ->label('sdk.response.model', Response::MODEL_HEALTH_QUEUE) ->inject('response') ->action(function (Response $response) { - - $response->dynamic(new Document([ 'size' => Resque::size(Event::WEBHOOK_QUEUE_NAME) ]), Response::MODEL_HEALTH_QUEUE); + $response->dynamic(new Document(['size' => Resque::size(Event::WEBHOOK_QUEUE_NAME)]), Response::MODEL_HEALTH_QUEUE); }, ['response']); App::get('/v1/health/queue/logs') @@ -202,8 +196,7 @@ App::get('/v1/health/queue/logs') ->label('sdk.response.model', Response::MODEL_HEALTH_QUEUE) ->inject('response') ->action(function (Response $response) { - - $response->dynamic(new Document([ 'size' => Resque::size(Event::AUDITS_QUEUE_NAME) ]), Response::MODEL_HEALTH_QUEUE); + $response->dynamic(new Document(['size' => Resque::size(Event::AUDITS_QUEUE_NAME)]), Response::MODEL_HEALTH_QUEUE); }, ['response']); App::get('/v1/health/queue/certificates') @@ -219,8 +212,7 @@ App::get('/v1/health/queue/certificates') ->label('sdk.response.model', Response::MODEL_HEALTH_QUEUE) ->inject('response') ->action(function (Response $response) { - - $response->dynamic(new Document([ 'size' => Resque::size(Event::CERTIFICATES_QUEUE_NAME) ]), Response::MODEL_HEALTH_QUEUE); + $response->dynamic(new Document(['size' => Resque::size(Event::CERTIFICATES_QUEUE_NAME)]), Response::MODEL_HEALTH_QUEUE); }, ['response']); App::get('/v1/health/queue/functions') @@ -236,8 +228,7 @@ App::get('/v1/health/queue/functions') ->label('sdk.response.model', Response::MODEL_HEALTH_QUEUE) ->inject('response') ->action(function (Response $response) { - - $response->dynamic(new Document([ 'size' => Resque::size(Event::FUNCTIONS_QUEUE_NAME) ]), Response::MODEL_HEALTH_QUEUE); + $response->dynamic(new Document(['size' => Resque::size(Event::FUNCTIONS_QUEUE_NAME)]), Response::MODEL_HEALTH_QUEUE); }, ['response']); App::get('/v1/health/storage/local') @@ -253,31 +244,30 @@ App::get('/v1/health/storage/local') ->label('sdk.response.model', Response::MODEL_HEALTH_STATUS) ->inject('response') ->action(function (Response $response) { - $checkStart = \microtime(true); foreach ( [ - 'Uploads' => APP_STORAGE_UPLOADS, - 'Cache' => APP_STORAGE_CACHE, - 'Config' => APP_STORAGE_CONFIG, - 'Certs' => APP_STORAGE_CERTIFICATES + 'Uploads' => APP_STORAGE_UPLOADS, + 'Cache' => APP_STORAGE_CACHE, + 'Config' => APP_STORAGE_CONFIG, + 'Certs' => APP_STORAGE_CERTIFICATES, ] as $key => $volume ) { $device = new Local($volume); - if (!\is_readable($device->getRoot())) { - throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Device ' . $key . ' dir is not readable'); + if (! \is_readable($device->getRoot())) { + throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Device '.$key.' dir is not readable'); } - if (!\is_writable($device->getRoot())) { - throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Device ' . $key . ' dir is not writable'); + if (! \is_writable($device->getRoot())) { + throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Device '.$key.' dir is not writable'); } } $output = [ 'status' => 'pass', - 'ping' => \round((\microtime(true) - $checkStart) / 1000) + 'ping' => \round((\microtime(true) - $checkStart) / 1000), ]; $response->dynamic(new Document($output), Response::MODEL_HEALTH_STATUS); @@ -296,10 +286,9 @@ App::get('/v1/health/anti-virus') ->label('sdk.response.model', Response::MODEL_HEALTH_ANTIVIRUS) ->inject('response') ->action(function (Response $response) { - $output = [ 'status' => '', - 'version' => '' + 'version' => '', ]; if (App::getEnv('_APP_STORAGE_ANTIVIRUS') === 'disabled') { // Check if scans are enabled @@ -334,7 +323,6 @@ App::get('/v1/health/stats') // Currently only used internally ->inject('register') ->inject('deviceFiles') ->action(function (Response $response, Registry $register, Device $deviceFiles) { - $cache = $register->get('cache'); $cacheStats = $cache->info(); @@ -342,7 +330,7 @@ App::get('/v1/health/stats') // Currently only used internally $response ->json([ 'storage' => [ - 'used' => Storage::human($deviceFiles->getDirectorySize($deviceFiles->getRoot() . '/')), + 'used' => Storage::human($deviceFiles->getDirectorySize($deviceFiles->getRoot().'/')), 'partitionTotal' => Storage::human($deviceFiles->getPartitionTotalSpace()), 'partitionFree' => Storage::human($deviceFiles->getPartitionFreeSpace()), ], diff --git a/app/controllers/api/locale.php b/app/controllers/api/locale.php index 9c958fb080..90bd6a94a8 100644 --- a/app/controllers/api/locale.php +++ b/app/controllers/api/locale.php @@ -1,7 +1,7 @@ getText('countries.' . strtolower($record['country']['iso_code']), $locale->getText('locale.country.unknown')); - $output['continent'] = $locale->getText('continents.' . strtolower($record['continent']['code']), $locale->getText('locale.country.unknown')); + $output['country'] = $locale->getText('countries.'.strtolower($record['country']['iso_code']), $locale->getText('locale.country.unknown')); + $output['continent'] = $locale->getText('continents.'.strtolower($record['continent']['code']), $locale->getText('locale.country.unknown')); $output['continentCode'] = $record['continent']['code']; $output['eu'] = (\in_array($record['country']['iso_code'], $eu)) ? true : false; @@ -62,9 +62,9 @@ App::get('/v1/locale') } $response - ->addHeader('Cache-Control', 'public, max-age=' . $time) - ->addHeader('Expires', \date('D, d M Y H:i:s', \time() + $time) . ' GMT') // 45 days cache - ; + ->addHeader('Cache-Control', 'public, max-age='.$time) + ->addHeader('Expires', \date('D, d M Y H:i:s', \time() + $time).' GMT') // 45 days cache +; $response->dynamic(new Document($output), Response::MODEL_LOCALE); }); @@ -89,7 +89,7 @@ App::get('/v1/locale/countries') foreach ($list as $value) { $output[] = new Document([ - 'name' => $locale->getText('countries.' . strtolower($value)), + 'name' => $locale->getText('countries.'.strtolower($value)), 'code' => $value, ]); } @@ -121,9 +121,9 @@ App::get('/v1/locale/countries/eu') $output = []; foreach ($eu as $code) { - if ($locale->getText('countries.' . strtolower($code), false) !== false) { + if ($locale->getText('countries.'.strtolower($code), false) !== false) { $output[] = new Document([ - 'name' => $locale->getText('countries.' . strtolower($code)), + 'name' => $locale->getText('countries.'.strtolower($code)), 'code' => $code, ]); } @@ -158,11 +158,11 @@ App::get('/v1/locale/countries/phones') \asort($list); foreach ($list as $code => $name) { - if ($locale->getText('countries.' . strtolower($code), false) !== false) { + if ($locale->getText('countries.'.strtolower($code), false) !== false) { $output[] = new Document([ - 'code' => '+' . $list[$code], + 'code' => '+'.$list[$code], 'countryCode' => $code, - 'countryName' => $locale->getText('countries.' . strtolower($code)), + 'countryName' => $locale->getText('countries.'.strtolower($code)), ]); } } @@ -190,7 +190,7 @@ App::get('/v1/locale/continents') foreach ($list as $value) { $output[] = new Document([ - 'name' => $locale->getText('continents.' . strtolower($value)), + 'name' => $locale->getText('continents.'.strtolower($value)), 'code' => $value, ]); } @@ -224,7 +224,6 @@ App::get('/v1/locale/currencies') $response->dynamic(new Document(['currencies' => $list, 'total' => \count($list)]), Response::MODEL_CURRENCY_LIST); }); - App::get('/v1/locale/languages') ->desc('List Languages') ->groups(['api', 'locale']) diff --git a/app/controllers/api/projects.php b/app/controllers/api/projects.php index deff177ab2..9a593fea1f 100644 --- a/app/controllers/api/projects.php +++ b/app/controllers/api/projects.php @@ -5,35 +5,35 @@ use Appwrite\Auth\Validator\Password; use Appwrite\Event\Certificate; use Appwrite\Event\Delete; use Appwrite\Event\Validator\Event; +use Appwrite\Extend\Exception; use Appwrite\Network\Validator\CNAME; -use Utopia\Validator\Domain as DomainValidator; use Appwrite\Network\Validator\Origin; -use Utopia\Validator\URL; use Appwrite\Utopia\Database\Validator\CustomId; +use Appwrite\Utopia\Database\Validator\Queries\Projects; use Appwrite\Utopia\Response; use Utopia\Abuse\Adapters\TimeLimit; use Utopia\App; use Utopia\Audit\Audit; use Utopia\Config\Config; use Utopia\Database\Database; +use Utopia\Database\DateTime; use Utopia\Database\Document; use Utopia\Database\Helpers\ID; -use Utopia\Database\DateTime; use Utopia\Database\Helpers\Permission; -use Utopia\Database\Query; use Utopia\Database\Helpers\Role; +use Utopia\Database\Query; use Utopia\Database\Validator\Authorization; use Utopia\Database\Validator\DatetimeValidator; use Utopia\Database\Validator\UID; use Utopia\Domains\Domain; use Utopia\Registry\Registry; -use Appwrite\Extend\Exception; -use Appwrite\Utopia\Database\Validator\Queries\Projects; use Utopia\Validator\ArrayList; use Utopia\Validator\Boolean; +use Utopia\Validator\Domain as DomainValidator; use Utopia\Validator\Hostname; use Utopia\Validator\Range; use Utopia\Validator\Text; +use Utopia\Validator\URL; use Utopia\Validator\WhiteList; App::init() @@ -58,7 +58,7 @@ App::post('/v1/projects') ->param('projectId', '', new CustomId(), 'Unique Id. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can\'t start with a special char. Max length is 36 chars.') ->param('name', null, new Text(128), 'Project name. Max length: 128 chars.') ->param('teamId', '', new UID(), 'Team unique ID.') - ->param('region', App::getEnv('_APP_REGION', 'default'), new Whitelist(array_keys(array_filter(Config::getParam('regions'), fn($config) => !$config['disabled']))), 'Project Region.', true) + ->param('region', App::getEnv('_APP_REGION', 'default'), new Whitelist(array_keys(array_filter(Config::getParam('regions'), fn ($config) => ! $config['disabled']))), 'Project Region.', true) ->param('description', '', new Text(256), 'Project description. Max length: 256 chars.', true) ->param('logo', '', new Text(1024), 'Project logo.', true) ->param('url', '', new URL(), 'Project URL.', true) @@ -72,7 +72,6 @@ App::post('/v1/projects') ->inject('dbForConsole') ->inject('dbForProject') ->action(function (string $projectId, string $name, string $teamId, string $region, string $description, string $logo, string $url, string $legalName, string $legalCountry, string $legalState, string $legalCity, string $legalAddress, string $legalTaxId, Response $response, Database $dbForConsole, Database $dbForProject) { - $team = $dbForConsole->getDocument('teams', $teamId); if ($team->isEmpty()) { @@ -153,7 +152,7 @@ App::post('/v1/projects') 'array' => $attribute['array'], 'filters' => $attribute['filters'], 'default' => $attribute['default'] ?? null, - 'format' => $attribute['format'] ?? '' + 'format' => $attribute['format'] ?? '', ]); } @@ -184,15 +183,14 @@ App::get('/v1/projects') ->label('sdk.response.code', Response::STATUS_CODE_OK) ->label('sdk.response.type', Response::CONTENT_TYPE_JSON) ->label('sdk.response.model', Response::MODEL_PROJECT_LIST) - ->param('queries', [], new Projects(), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/databases#querying-documents). Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' queries are allowed, each ' . APP_LIMIT_ARRAY_ELEMENT_SIZE . ' characters long. You may filter on the following attributes: ' . implode(', ', Projects::ALLOWED_ATTRIBUTES), true) + ->param('queries', [], new Projects(), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/databases#querying-documents). Maximum of '.APP_LIMIT_ARRAY_PARAMS_SIZE.' queries are allowed, each '.APP_LIMIT_ARRAY_ELEMENT_SIZE.' characters long. You may filter on the following attributes: '.implode(', ', Projects::ALLOWED_ATTRIBUTES), true) ->param('search', '', new Text(256), 'Search term to filter your list results. Max length: 256 chars.', true) ->inject('response') ->inject('dbForConsole') ->action(function (array $queries, string $search, Response $response, Database $dbForConsole) { - $queries = Query::parseQueries($queries); - if (!empty($search)) { + if (! empty($search)) { $queries[] = Query::search('search', $search); } @@ -233,7 +231,6 @@ App::get('/v1/projects/:projectId') ->inject('response') ->inject('dbForConsole') ->action(function (string $projectId, Response $response, Database $dbForConsole) { - $project = $dbForConsole->getDocument('projects', $projectId); if ($project->isEmpty()) { @@ -260,7 +257,6 @@ App::get('/v1/projects/:projectId/usage') ->inject('dbForProject') ->inject('register') ->action(function (string $projectId, string $range, Response $response, Database $dbForConsole, Database $dbForProject, Registry $register) { - $project = $dbForConsole->getDocument('projects', $projectId); if ($project->isEmpty()) { @@ -298,7 +294,7 @@ App::get('/v1/projects/:projectId/usage') 'databases.$all.count.total', 'documents.$all.count.total', 'executions.$all.compute.total', - 'buckets.$all.count.total' + 'buckets.$all.count.total', ]; $stats = []; @@ -381,7 +377,6 @@ App::patch('/v1/projects/:projectId') ->inject('response') ->inject('dbForConsole') ->action(function (string $projectId, string $name, string $description, string $logo, string $url, string $legalName, string $legalCountry, string $legalState, string $legalCity, string $legalAddress, string $legalTaxId, Response $response, Database $dbForConsole) { - $project = $dbForConsole->getDocument('projects', $projectId); if ($project->isEmpty()) { @@ -415,12 +410,11 @@ App::patch('/v1/projects/:projectId/service') ->label('sdk.response.type', Response::CONTENT_TYPE_JSON) ->label('sdk.response.model', Response::MODEL_PROJECT) ->param('projectId', '', new UID(), 'Project unique ID.') - ->param('service', '', new WhiteList(array_keys(array_filter(Config::getParam('services'), fn($element) => $element['optional'])), true), 'Service name.') + ->param('service', '', new WhiteList(array_keys(array_filter(Config::getParam('services'), fn ($element) => $element['optional'])), true), 'Service name.') ->param('status', null, new Boolean(), 'Service status.') ->inject('response') ->inject('dbForConsole') ->action(function (string $projectId, string $service, bool $status, Response $response, Database $dbForConsole) { - $project = $dbForConsole->getDocument('projects', $projectId); if ($project->isEmpty()) { @@ -453,7 +447,6 @@ App::patch('/v1/projects/:projectId/oauth2') ->inject('response') ->inject('dbForConsole') ->action(function (string $projectId, string $provider, ?string $appId, ?string $secret, ?bool $enabled, Response $response, Database $dbForConsole) { - $project = $dbForConsole->getDocument('projects', $projectId); if ($project->isEmpty()) { @@ -463,15 +456,15 @@ App::patch('/v1/projects/:projectId/oauth2') $providers = $project->getAttribute('authProviders', []); if ($appId !== null) { - $providers[$provider . 'Appid'] = $appId; + $providers[$provider.'Appid'] = $appId; } if ($secret !== null) { - $providers[$provider . 'Secret'] = $secret; + $providers[$provider.'Secret'] = $secret; } if ($enabled !== null) { - $providers[$provider . 'Enabled'] = $enabled; + $providers[$provider.'Enabled'] = $enabled; } $project = $dbForConsole->updateDocument('projects', $project->getId(), $project->setAttribute('authProviders', $providers)); @@ -494,7 +487,6 @@ App::patch('/v1/projects/:projectId/auth/limit') ->inject('response') ->inject('dbForConsole') ->action(function (string $projectId, int $limit, Response $response, Database $dbForConsole) { - $project = $dbForConsole->getDocument('projects', $projectId); if ($project->isEmpty()) { @@ -525,7 +517,6 @@ App::patch('/v1/projects/:projectId/auth/duration') ->inject('response') ->inject('dbForConsole') ->action(function (string $projectId, int $duration, Response $response, Database $dbForConsole) { - $project = $dbForConsole->getDocument('projects', $projectId); if ($project->isEmpty()) { @@ -552,12 +543,11 @@ App::patch('/v1/projects/:projectId/auth/:method') ->label('sdk.response.type', Response::CONTENT_TYPE_JSON) ->label('sdk.response.model', Response::MODEL_PROJECT) ->param('projectId', '', new UID(), 'Project unique ID.') - ->param('method', '', new WhiteList(\array_keys(Config::getParam('auth')), true), 'Auth Method. Possible values: ' . implode(',', \array_keys(Config::getParam('auth'))), false) + ->param('method', '', new WhiteList(\array_keys(Config::getParam('auth')), true), 'Auth Method. Possible values: '.implode(',', \array_keys(Config::getParam('auth'))), false) ->param('status', false, new Boolean(true), 'Set the status of this auth method.') ->inject('response') ->inject('dbForConsole') ->action(function (string $projectId, string $method, bool $status, Response $response, Database $dbForConsole) { - $project = $dbForConsole->getDocument('projects', $projectId); $auth = Config::getParam('auth')[$method] ?? []; $authKey = $auth['key'] ?? ''; @@ -586,11 +576,10 @@ App::patch('/v1/projects/:projectId/auth/max-sessions') ->label('sdk.response.type', Response::CONTENT_TYPE_JSON) ->label('sdk.response.model', Response::MODEL_PROJECT) ->param('projectId', '', new UID(), 'Project unique ID.') - ->param('limit', false, new Range(1, APP_LIMIT_USER_SESSIONS_MAX), 'Set the max number of users allowed in this project. Value allowed is between 1-' . APP_LIMIT_USER_SESSIONS_MAX . '. Default is ' . APP_LIMIT_USER_SESSIONS_DEFAULT) + ->param('limit', false, new Range(1, APP_LIMIT_USER_SESSIONS_MAX), 'Set the max number of users allowed in this project. Value allowed is between 1-'.APP_LIMIT_USER_SESSIONS_MAX.'. Default is '.APP_LIMIT_USER_SESSIONS_DEFAULT) ->inject('response') ->inject('dbForConsole') ->action(function (string $projectId, int $limit, Response $response, Database $dbForConsole) { - $project = $dbForConsole->getDocument('projects', $projectId); if ($project->isEmpty()) { @@ -622,8 +611,7 @@ App::delete('/v1/projects/:projectId') ->inject('dbForConsole') ->inject('deletes') ->action(function (string $projectId, string $password, Response $response, Document $user, Database $dbForConsole, Delete $deletes) { - - if (!Auth::passwordVerify($password, $user->getAttribute('password'), $user->getAttribute('hash'), $user->getAttribute('hashOptions'))) { // Double check user password + if (! Auth::passwordVerify($password, $user->getAttribute('password'), $user->getAttribute('hash'), $user->getAttribute('hashOptions'))) { // Double check user password throw new Exception(Exception::USER_INVALID_CREDENTIALS); } @@ -635,10 +623,9 @@ App::delete('/v1/projects/:projectId') $deletes ->setType(DELETE_TYPE_DOCUMENT) - ->setDocument($project) - ; + ->setDocument($project); - if (!$dbForConsole->deleteDocument('projects', $projectId)) { + if (! $dbForConsole->deleteDocument('projects', $projectId)) { throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Failed to remove project from DB'); } @@ -659,7 +646,7 @@ App::post('/v1/projects/:projectId/webhooks') ->label('sdk.response.model', Response::MODEL_WEBHOOK) ->param('projectId', '', new UID(), 'Project unique ID.') ->param('name', null, new Text(128), 'Webhook name. Max length: 128 chars.') - ->param('events', null, new ArrayList(new Event(), APP_LIMIT_ARRAY_PARAMS_SIZE), 'Events list. Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' events are allowed.') + ->param('events', null, new ArrayList(new Event(), APP_LIMIT_ARRAY_PARAMS_SIZE), 'Events list. Maximum of '.APP_LIMIT_ARRAY_PARAMS_SIZE.' events are allowed.') ->param('url', null, new URL(['http', 'https']), 'Webhook URL.') ->param('security', false, new Boolean(true), 'Certificate verification, false for disabled or true for enabled.') ->param('httpUser', '', new Text(256), 'Webhook HTTP user. Max length: 256 chars.', true) @@ -667,7 +654,6 @@ App::post('/v1/projects/:projectId/webhooks') ->inject('response') ->inject('dbForConsole') ->action(function (string $projectId, string $name, array $events, string $url, bool $security, string $httpUser, string $httpPass, Response $response, Database $dbForConsole) { - $project = $dbForConsole->getDocument('projects', $projectId); if ($project->isEmpty()) { @@ -717,7 +703,6 @@ App::get('/v1/projects/:projectId/webhooks') ->inject('response') ->inject('dbForConsole') ->action(function (string $projectId, Response $response, Database $dbForConsole) { - $project = $dbForConsole->getDocument('projects', $projectId); if ($project->isEmpty()) { @@ -750,7 +735,6 @@ App::get('/v1/projects/:projectId/webhooks/:webhookId') ->inject('response') ->inject('dbForConsole') ->action(function (string $projectId, string $webhookId, Response $response, Database $dbForConsole) { - $project = $dbForConsole->getDocument('projects', $projectId); if ($project->isEmpty()) { @@ -782,7 +766,7 @@ App::put('/v1/projects/:projectId/webhooks/:webhookId') ->param('projectId', '', new UID(), 'Project unique ID.') ->param('webhookId', '', new UID(), 'Webhook unique ID.') ->param('name', null, new Text(128), 'Webhook name. Max length: 128 chars.') - ->param('events', null, new ArrayList(new Event(), APP_LIMIT_ARRAY_PARAMS_SIZE), 'Events list. Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' events are allowed.') + ->param('events', null, new ArrayList(new Event(), APP_LIMIT_ARRAY_PARAMS_SIZE), 'Events list. Maximum of '.APP_LIMIT_ARRAY_PARAMS_SIZE.' events are allowed.') ->param('url', null, new URL(['http', 'https']), 'Webhook URL.') ->param('security', false, new Boolean(true), 'Certificate verification, false for disabled or true for enabled.') ->param('httpUser', '', new Text(256), 'Webhook HTTP user. Max length: 256 chars.', true) @@ -790,7 +774,6 @@ App::put('/v1/projects/:projectId/webhooks/:webhookId') ->inject('response') ->inject('dbForConsole') ->action(function (string $projectId, string $webhookId, string $name, array $events, string $url, bool $security, string $httpUser, string $httpPass, Response $response, Database $dbForConsole) { - $project = $dbForConsole->getDocument('projects', $projectId); if ($project->isEmpty()) { @@ -814,8 +797,7 @@ App::put('/v1/projects/:projectId/webhooks/:webhookId') ->setAttribute('url', $url) ->setAttribute('security', $security) ->setAttribute('httpUser', $httpUser) - ->setAttribute('httpPass', $httpPass) - ; + ->setAttribute('httpPass', $httpPass); $dbForConsole->updateDocument('webhooks', $webhook->getId(), $webhook); $dbForConsole->deleteCachedDocument('projects', $project->getId()); @@ -838,7 +820,6 @@ App::patch('/v1/projects/:projectId/webhooks/:webhookId/signature') ->inject('response') ->inject('dbForConsole') ->action(function (string $projectId, string $webhookId, Response $response, Database $dbForConsole) { - $project = $dbForConsole->getDocument('projects', $projectId); if ($project->isEmpty()) { @@ -876,7 +857,6 @@ App::delete('/v1/projects/:projectId/webhooks/:webhookId') ->inject('response') ->inject('dbForConsole') ->action(function (string $projectId, string $webhookId, Response $response, Database $dbForConsole) { - $project = $dbForConsole->getDocument('projects', $projectId); if ($project->isEmpty()) { @@ -913,12 +893,11 @@ App::post('/v1/projects/:projectId/keys') ->label('sdk.response.model', Response::MODEL_KEY) ->param('projectId', '', new UID(), 'Project unique ID.') ->param('name', null, new Text(128), 'Key name. Max length: 128 chars.') - ->param('scopes', null, new ArrayList(new WhiteList(array_keys(Config::getParam('scopes')), true), APP_LIMIT_ARRAY_PARAMS_SIZE), 'Key scopes list. Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' scopes are allowed.') + ->param('scopes', null, new ArrayList(new WhiteList(array_keys(Config::getParam('scopes')), true), APP_LIMIT_ARRAY_PARAMS_SIZE), 'Key scopes list. Maximum of '.APP_LIMIT_ARRAY_PARAMS_SIZE.' scopes are allowed.') ->param('expire', null, new DatetimeValidator(), 'Expiration time in ISO 8601 format. Use null for unlimited expiration.', true) ->inject('response') ->inject('dbForConsole') ->action(function (string $projectId, string $name, array $scopes, ?string $expire, Response $response, Database $dbForConsole) { - $project = $dbForConsole->getDocument('projects', $projectId); if ($project->isEmpty()) { @@ -965,7 +944,6 @@ App::get('/v1/projects/:projectId/keys') ->inject('response') ->inject('dbForConsole') ->action(function (string $projectId, Response $response, Database $dbForConsole) { - $project = $dbForConsole->getDocument('projects', $projectId); if ($project->isEmpty()) { @@ -998,7 +976,6 @@ App::get('/v1/projects/:projectId/keys/:keyId') ->inject('response') ->inject('dbForConsole') ->action(function (string $projectId, string $keyId, Response $response, Database $dbForConsole) { - $project = $dbForConsole->getDocument('projects', $projectId); if ($project->isEmpty()) { @@ -1030,12 +1007,11 @@ App::put('/v1/projects/:projectId/keys/:keyId') ->param('projectId', '', new UID(), 'Project unique ID.') ->param('keyId', '', new UID(), 'Key unique ID.') ->param('name', null, new Text(128), 'Key name. Max length: 128 chars.') - ->param('scopes', null, new ArrayList(new WhiteList(array_keys(Config::getParam('scopes')), true), APP_LIMIT_ARRAY_PARAMS_SIZE), 'Key scopes list. Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' events are allowed.') + ->param('scopes', null, new ArrayList(new WhiteList(array_keys(Config::getParam('scopes')), true), APP_LIMIT_ARRAY_PARAMS_SIZE), 'Key scopes list. Maximum of '.APP_LIMIT_ARRAY_PARAMS_SIZE.' events are allowed.') ->param('expire', null, new DatetimeValidator(), 'Expiration time in ISO 8601 format. Use null for unlimited expiration.', true) ->inject('response') ->inject('dbForConsole') ->action(function (string $projectId, string $keyId, string $name, array $scopes, ?string $expire, Response $response, Database $dbForConsole) { - $project = $dbForConsole->getDocument('projects', $projectId); if ($project->isEmpty()) { @@ -1054,8 +1030,7 @@ App::put('/v1/projects/:projectId/keys/:keyId') $key ->setAttribute('name', $name) ->setAttribute('scopes', $scopes) - ->setAttribute('expire', $expire) - ; + ->setAttribute('expire', $expire); $dbForConsole->updateDocument('keys', $key->getId(), $key); @@ -1078,7 +1053,6 @@ App::delete('/v1/projects/:projectId/keys/:keyId') ->inject('response') ->inject('dbForConsole') ->action(function (string $projectId, string $keyId, Response $response, Database $dbForConsole) { - $project = $dbForConsole->getDocument('projects', $projectId); if ($project->isEmpty()) { @@ -1141,7 +1115,7 @@ App::post('/v1/projects/:projectId/platforms') 'name' => $name, 'key' => $key, 'store' => $store, - 'hostname' => $hostname + 'hostname' => $hostname, ]); $platform = $dbForConsole->createDocument('platforms', $platform); @@ -1167,7 +1141,6 @@ App::get('/v1/projects/:projectId/platforms') ->inject('response') ->inject('dbForConsole') ->action(function (string $projectId, Response $response, Database $dbForConsole) { - $project = $dbForConsole->getDocument('projects', $projectId); if ($project->isEmpty()) { @@ -1200,7 +1173,6 @@ App::get('/v1/projects/:projectId/platforms/:platformId') ->inject('response') ->inject('dbForConsole') ->action(function (string $projectId, string $platformId, Response $response, Database $dbForConsole) { - $project = $dbForConsole->getDocument('projects', $projectId); if ($project->isEmpty()) { @@ -1257,8 +1229,7 @@ App::put('/v1/projects/:projectId/platforms/:platformId') ->setAttribute('name', $name) ->setAttribute('key', $key) ->setAttribute('store', $store) - ->setAttribute('hostname', $hostname) - ; + ->setAttribute('hostname', $hostname); $dbForConsole->updateDocument('platforms', $platform->getId(), $platform); @@ -1281,7 +1252,6 @@ App::delete('/v1/projects/:projectId/platforms/:platformId') ->inject('response') ->inject('dbForConsole') ->action(function (string $projectId, string $platformId, Response $response, Database $dbForConsole) { - $project = $dbForConsole->getDocument('projects', $projectId); if ($project->isEmpty()) { @@ -1321,7 +1291,6 @@ App::post('/v1/projects/:projectId/domains') ->inject('response') ->inject('dbForConsole') ->action(function (string $projectId, string $domain, Response $response, Database $dbForConsole) { - $project = $dbForConsole->getDocument('projects', $projectId); if ($project->isEmpty()) { @@ -1333,14 +1302,14 @@ App::post('/v1/projects/:projectId/domains') Query::equal('projectInternalId', [$project->getInternalId()]), ]); - if ($document && !$document->isEmpty()) { + if ($document && ! $document->isEmpty()) { throw new Exception(Exception::DOMAIN_ALREADY_EXISTS); } $target = new Domain(App::getEnv('_APP_DOMAIN_TARGET', '')); - if (!$target->isKnown() || $target->isTest()) { - throw new Exception(Exception::DOMAIN_TARGET_INVALID, 'Unreachable CNAME target (' . $target->get() . '). Please check the _APP_DOMAIN_TARGET environment variable of your Appwrite server.'); + if (! $target->isKnown() || $target->isTest()) { + throw new Exception(Exception::DOMAIN_TARGET_INVALID, 'Unreachable CNAME target ('.$target->get().'). Please check the _APP_DOMAIN_TARGET environment variable of your Appwrite server.'); } $domain = new Domain($domain); @@ -1385,7 +1354,6 @@ App::get('/v1/projects/:projectId/domains') ->inject('response') ->inject('dbForConsole') ->action(function (string $projectId, Response $response, Database $dbForConsole) { - $project = $dbForConsole->getDocument('projects', $projectId); if ($project->isEmpty()) { @@ -1418,7 +1386,6 @@ App::get('/v1/projects/:projectId/domains/:domainId') ->inject('response') ->inject('dbForConsole') ->action(function (string $projectId, string $domainId, Response $response, Database $dbForConsole) { - $project = $dbForConsole->getDocument('projects', $projectId); if ($project->isEmpty()) { @@ -1452,7 +1419,6 @@ App::patch('/v1/projects/:projectId/domains/:domainId/verification') ->inject('response') ->inject('dbForConsole') ->action(function (string $projectId, string $domainId, Response $response, Database $dbForConsole) { - $project = $dbForConsole->getDocument('projects', $projectId); if ($project->isEmpty()) { @@ -1470,8 +1436,8 @@ App::patch('/v1/projects/:projectId/domains/:domainId/verification') $target = new Domain(App::getEnv('_APP_DOMAIN_TARGET', '')); - if (!$target->isKnown() || $target->isTest()) { - throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Unreachable CNAME target (' . $target->get() . '), please use a domain with a public suffix.'); + if (! $target->isKnown() || $target->isTest()) { + throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Unreachable CNAME target ('.$target->get().'), please use a domain with a public suffix.'); } if ($domain->getAttribute('verification') === true) { @@ -1480,11 +1446,10 @@ App::patch('/v1/projects/:projectId/domains/:domainId/verification') $validator = new CNAME($target->get()); // Verify Domain with DNS records - if (!$validator->isValid($domain->getAttribute('domain', ''))) { + if (! $validator->isValid($domain->getAttribute('domain', ''))) { throw new Exception(Exception::DOMAIN_VERIFICATION_FAILED); } - $dbForConsole->updateDocument('domains', $domain->getId(), $domain->setAttribute('verification', true)); $dbForConsole->deleteCachedDocument('projects', $project->getId()); @@ -1512,7 +1477,6 @@ App::delete('/v1/projects/:projectId/domains/:domainId') ->inject('dbForConsole') ->inject('deletes') ->action(function (string $projectId, string $domainId, Response $response, Database $dbForConsole, Delete $deletes) { - $project = $dbForConsole->getDocument('projects', $projectId); if ($project->isEmpty()) { diff --git a/app/controllers/api/storage.php b/app/controllers/api/storage.php index 271f2af6b3..c28c9617ad 100644 --- a/app/controllers/api/storage.php +++ b/app/controllers/api/storage.php @@ -4,28 +4,28 @@ use Appwrite\Auth\Auth; use Appwrite\ClamAV\Network; use Appwrite\Event\Delete; use Appwrite\Event\Event; -use Appwrite\Utopia\Database\Validator\CustomId; +use Appwrite\Extend\Exception; use Appwrite\OpenSSL\OpenSSL; +use Appwrite\Utopia\Database\Validator\CustomId; +use Appwrite\Utopia\Database\Validator\Queries\Buckets; +use Appwrite\Utopia\Database\Validator\Queries\Files; use Appwrite\Utopia\Response; use Utopia\App; use Utopia\Config\Config; use Utopia\Database\Database; -use Utopia\Database\Document; use Utopia\Database\DateTime; -use Utopia\Database\Exception\Duplicate; +use Utopia\Database\Document; use Utopia\Database\Exception\Authorization as AuthorizationException; +use Utopia\Database\Exception\Duplicate; use Utopia\Database\Exception\Duplicate as DuplicateException; use Utopia\Database\Exception\Structure as StructureException; use Utopia\Database\Helpers\ID; use Utopia\Database\Helpers\Permission; -use Utopia\Database\Query; use Utopia\Database\Helpers\Role; +use Utopia\Database\Query; use Utopia\Database\Validator\Authorization; use Utopia\Database\Validator\Permissions; use Utopia\Database\Validator\UID; -use Appwrite\Extend\Exception; -use Appwrite\Utopia\Database\Validator\Queries\Buckets; -use Appwrite\Utopia\Database\Validator\Queries\Files; use Utopia\Image\Image; use Utopia\Storage\Compression\Algorithms\GZIP; use Utopia\Storage\Compression\Algorithms\Zstd; @@ -35,13 +35,13 @@ use Utopia\Storage\Validator\File; use Utopia\Storage\Validator\FileExt; use Utopia\Storage\Validator\FileSize; use Utopia\Storage\Validator\Upload; +use Utopia\Swoole\Request; use Utopia\Validator\ArrayList; use Utopia\Validator\Boolean; use Utopia\Validator\HexColor; use Utopia\Validator\Range; use Utopia\Validator\Text; use Utopia\Validator\WhiteList; -use Utopia\Swoole\Request; App::post('/v1/storage/buckets') ->desc('Create bucket') @@ -63,16 +63,15 @@ App::post('/v1/storage/buckets') ->param('permissions', null, new Permissions(APP_LIMIT_ARRAY_PARAMS_SIZE), 'An array of permission strings. By default, no user is granted with any permissions. [Learn more about permissions](/docs/permissions).', true) ->param('fileSecurity', false, new Boolean(true), 'Enables configuring permissions for individual file. A user needs one of file or bucket level permissions to access a file. [Learn more about permissions](/docs/permissions).', true) ->param('enabled', true, new Boolean(true), 'Is bucket enabled?', true) - ->param('maximumFileSize', (int) App::getEnv('_APP_STORAGE_LIMIT', 0), new Range(1, (int) App::getEnv('_APP_STORAGE_LIMIT', 0)), 'Maximum file size allowed in bytes. Maximum allowed value is ' . Storage::human(App::getEnv('_APP_STORAGE_LIMIT', 0), 0) . '. For self-hosted setups you can change the max limit by changing the `_APP_STORAGE_LIMIT` environment variable. [Learn more about storage environment variables](docs/environment-variables#storage)', true) - ->param('allowedFileExtensions', [], new ArrayList(new Text(64), APP_LIMIT_ARRAY_PARAMS_SIZE), 'Allowed file extensions. Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' extensions are allowed, each 64 characters long.', true) - ->param('compression', COMPRESSION_TYPE_NONE, new WhiteList([COMPRESSION_TYPE_NONE, COMPRESSION_TYPE_GZIP, COMPRESSION_TYPE_ZSTD]), 'Compression algorithm choosen for compression. Can be one of ' . COMPRESSION_TYPE_NONE . ', [' . COMPRESSION_TYPE_GZIP . '](https://en.wikipedia.org/wiki/Gzip), or [' . COMPRESSION_TYPE_ZSTD . '](https://en.wikipedia.org/wiki/Zstd), For file size above ' . Storage::human(APP_STORAGE_READ_BUFFER, 0) . ' compression is skipped even if it\'s enabled', true) - ->param('encryption', true, new Boolean(true), 'Is encryption enabled? For file size above ' . Storage::human(APP_STORAGE_READ_BUFFER, 0) . ' encryption is skipped even if it\'s enabled', true) - ->param('antivirus', true, new Boolean(true), 'Is virus scanning enabled? For file size above ' . Storage::human(APP_LIMIT_ANTIVIRUS, 0) . ' AntiVirus scanning is skipped even if it\'s enabled', true) + ->param('maximumFileSize', (int) App::getEnv('_APP_STORAGE_LIMIT', 0), new Range(1, (int) App::getEnv('_APP_STORAGE_LIMIT', 0)), 'Maximum file size allowed in bytes. Maximum allowed value is '.Storage::human(App::getEnv('_APP_STORAGE_LIMIT', 0), 0).'. For self-hosted setups you can change the max limit by changing the `_APP_STORAGE_LIMIT` environment variable. [Learn more about storage environment variables](docs/environment-variables#storage)', true) + ->param('allowedFileExtensions', [], new ArrayList(new Text(64), APP_LIMIT_ARRAY_PARAMS_SIZE), 'Allowed file extensions. Maximum of '.APP_LIMIT_ARRAY_PARAMS_SIZE.' extensions are allowed, each 64 characters long.', true) + ->param('compression', COMPRESSION_TYPE_NONE, new WhiteList([COMPRESSION_TYPE_NONE, COMPRESSION_TYPE_GZIP, COMPRESSION_TYPE_ZSTD]), 'Compression algorithm choosen for compression. Can be one of '.COMPRESSION_TYPE_NONE.', ['.COMPRESSION_TYPE_GZIP.'](https://en.wikipedia.org/wiki/Gzip), or ['.COMPRESSION_TYPE_ZSTD.'](https://en.wikipedia.org/wiki/Zstd), For file size above '.Storage::human(APP_STORAGE_READ_BUFFER, 0).' compression is skipped even if it\'s enabled', true) + ->param('encryption', true, new Boolean(true), 'Is encryption enabled? For file size above '.Storage::human(APP_STORAGE_READ_BUFFER, 0).' encryption is skipped even if it\'s enabled', true) + ->param('antivirus', true, new Boolean(true), 'Is virus scanning enabled? For file size above '.Storage::human(APP_LIMIT_ANTIVIRUS, 0).' AntiVirus scanning is skipped even if it\'s enabled', true) ->inject('response') ->inject('dbForProject') ->inject('events') ->action(function (string $bucketId, string $name, ?array $permissions, bool $fileSecurity, bool $enabled, int $maximumFileSize, array $allowedFileExtensions, string $compression, bool $encryption, bool $antivirus, Response $response, Database $dbForProject, Event $events) { - $bucketId = $bucketId === 'unique()' ? ID::unique() : $bucketId; // Map aggregate permissions into the multiple permissions they represent. @@ -97,7 +96,7 @@ App::post('/v1/storage/buckets') 'array' => $attribute['array'], 'filters' => $attribute['filters'], 'default' => $attribute['default'] ?? null, - 'format' => $attribute['format'] ?? '' + 'format' => $attribute['format'] ?? '', ]); } @@ -128,14 +127,13 @@ App::post('/v1/storage/buckets') $bucket = $dbForProject->getDocument('buckets', $bucketId); - $dbForProject->createCollection('bucket_' . $bucket->getInternalId(), $attributes, $indexes); + $dbForProject->createCollection('bucket_'.$bucket->getInternalId(), $attributes, $indexes); } catch (Duplicate) { throw new Exception(Exception::STORAGE_BUCKET_ALREADY_EXISTS); } $events - ->setParam('bucketId', $bucket->getId()) - ; + ->setParam('bucketId', $bucket->getId()); $response ->setStatusCode(Response::STATUS_CODE_CREATED) @@ -154,15 +152,14 @@ App::get('/v1/storage/buckets') ->label('sdk.response.code', Response::STATUS_CODE_OK) ->label('sdk.response.type', Response::CONTENT_TYPE_JSON) ->label('sdk.response.model', Response::MODEL_BUCKET_LIST) - ->param('queries', [], new Buckets(), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/databases#querying-documents). Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' queries are allowed, each ' . APP_LIMIT_ARRAY_ELEMENT_SIZE . ' characters long. You may filter on the following attributes: ' . implode(', ', Buckets::ALLOWED_ATTRIBUTES), true) + ->param('queries', [], new Buckets(), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/databases#querying-documents). Maximum of '.APP_LIMIT_ARRAY_PARAMS_SIZE.' queries are allowed, each '.APP_LIMIT_ARRAY_ELEMENT_SIZE.' characters long. You may filter on the following attributes: '.implode(', ', Buckets::ALLOWED_ATTRIBUTES), true) ->param('search', '', new Text(256), 'Search term to filter your list results. Max length: 256 chars.', true) ->inject('response') ->inject('dbForProject') ->action(function (array $queries, string $search, Response $response, Database $dbForProject) { - $queries = Query::parseQueries($queries); - if (!empty($search)) { + if (! empty($search)) { $queries[] = Query::search('search', $search); } @@ -205,7 +202,6 @@ App::get('/v1/storage/buckets/:bucketId') ->inject('response') ->inject('dbForProject') ->action(function (string $bucketId, Response $response, Database $dbForProject) { - $bucket = $dbForProject->getDocument('buckets', $bucketId); if ($bucket->isEmpty()) { @@ -235,11 +231,11 @@ App::put('/v1/storage/buckets/:bucketId') ->param('permissions', null, new Permissions(APP_LIMIT_ARRAY_PARAMS_SIZE), 'An array of permission strings. By default, the current permissions are inherited. [Learn more about permissions](/docs/permissions).', true) ->param('fileSecurity', false, new Boolean(true), 'Enables configuring permissions for individual file. A user needs one of file or bucket level permissions to access a file. [Learn more about permissions](/docs/permissions).', true) ->param('enabled', true, new Boolean(true), 'Is bucket enabled?', true) - ->param('maximumFileSize', null, new Range(1, (int) App::getEnv('_APP_STORAGE_LIMIT', 0)), 'Maximum file size allowed in bytes. Maximum allowed value is ' . Storage::human((int)App::getEnv('_APP_STORAGE_LIMIT', 0), 0) . '. For self hosted version you can change the limit by changing _APP_STORAGE_LIMIT environment variable. [Learn more about storage environment variables](docs/environment-variables#storage)', true) - ->param('allowedFileExtensions', [], new ArrayList(new Text(64), APP_LIMIT_ARRAY_PARAMS_SIZE), 'Allowed file extensions. Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' extensions are allowed, each 64 characters long.', true) - ->param('compression', COMPRESSION_TYPE_NONE, new WhiteList([COMPRESSION_TYPE_NONE, COMPRESSION_TYPE_GZIP, COMPRESSION_TYPE_ZSTD]), 'Compression algorithm choosen for compression. Can be one of ' . COMPRESSION_TYPE_NONE . ', [' . COMPRESSION_TYPE_GZIP . '](https://en.wikipedia.org/wiki/Gzip), or [' . COMPRESSION_TYPE_ZSTD . '](https://en.wikipedia.org/wiki/Zstd), For file size above ' . Storage::human(APP_STORAGE_READ_BUFFER, 0) . ' compression is skipped even if it\'s enabled', true) - ->param('encryption', true, new Boolean(true), 'Is encryption enabled? For file size above ' . Storage::human(APP_STORAGE_READ_BUFFER, 0) . ' encryption is skipped even if it\'s enabled', true) - ->param('antivirus', true, new Boolean(true), 'Is virus scanning enabled? For file size above ' . Storage::human(APP_LIMIT_ANTIVIRUS, 0) . ' AntiVirus scanning is skipped even if it\'s enabled', true) + ->param('maximumFileSize', null, new Range(1, (int) App::getEnv('_APP_STORAGE_LIMIT', 0)), 'Maximum file size allowed in bytes. Maximum allowed value is '.Storage::human((int) App::getEnv('_APP_STORAGE_LIMIT', 0), 0).'. For self hosted version you can change the limit by changing _APP_STORAGE_LIMIT environment variable. [Learn more about storage environment variables](docs/environment-variables#storage)', true) + ->param('allowedFileExtensions', [], new ArrayList(new Text(64), APP_LIMIT_ARRAY_PARAMS_SIZE), 'Allowed file extensions. Maximum of '.APP_LIMIT_ARRAY_PARAMS_SIZE.' extensions are allowed, each 64 characters long.', true) + ->param('compression', COMPRESSION_TYPE_NONE, new WhiteList([COMPRESSION_TYPE_NONE, COMPRESSION_TYPE_GZIP, COMPRESSION_TYPE_ZSTD]), 'Compression algorithm choosen for compression. Can be one of '.COMPRESSION_TYPE_NONE.', ['.COMPRESSION_TYPE_GZIP.'](https://en.wikipedia.org/wiki/Gzip), or ['.COMPRESSION_TYPE_ZSTD.'](https://en.wikipedia.org/wiki/Zstd), For file size above '.Storage::human(APP_STORAGE_READ_BUFFER, 0).' compression is skipped even if it\'s enabled', true) + ->param('encryption', true, new Boolean(true), 'Is encryption enabled? For file size above '.Storage::human(APP_STORAGE_READ_BUFFER, 0).' encryption is skipped even if it\'s enabled', true) + ->param('antivirus', true, new Boolean(true), 'Is virus scanning enabled? For file size above '.Storage::human(APP_LIMIT_ANTIVIRUS, 0).' AntiVirus scanning is skipped even if it\'s enabled', true) ->inject('response') ->inject('dbForProject') ->inject('events') @@ -276,8 +272,7 @@ App::put('/v1/storage/buckets/:bucketId') ->setAttribute('antivirus', $antivirus)); $events - ->setParam('bucketId', $bucket->getId()) - ; + ->setParam('bucketId', $bucket->getId()); $response->dynamic($bucket, Response::MODEL_BUCKET); }); @@ -308,7 +303,7 @@ App::delete('/v1/storage/buckets/:bucketId') throw new Exception(Exception::STORAGE_BUCKET_NOT_FOUND); } - if (!$dbForProject->deleteDocument('buckets', $bucketId)) { + if (! $dbForProject->deleteDocument('buckets', $bucketId)) { throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Failed to remove bucket from DB'); } @@ -318,8 +313,7 @@ App::delete('/v1/storage/buckets/:bucketId') $events ->setParam('bucketId', $bucket->getId()) - ->setPayload($response->output($bucket, Response::MODEL_BUCKET)) - ; + ->setPayload($response->output($bucket, Response::MODEL_BUCKET)); $response->noContent(); }); @@ -360,15 +354,14 @@ App::post('/v1/storage/buckets/:bucketId/files') ->inject('deviceLocal') ->inject('deletes') ->action(function (string $bucketId, string $fileId, mixed $file, ?array $permissions, Request $request, Response $response, Database $dbForProject, Document $user, Event $events, string $mode, Device $deviceFiles, Device $deviceLocal, Delete $deletes) { - $bucket = Authorization::skip(fn () => $dbForProject->getDocument('buckets', $bucketId)); - if ($bucket->isEmpty() || (!$bucket->getAttribute('enabled') && $mode !== APP_MODE_ADMIN)) { + if ($bucket->isEmpty() || (! $bucket->getAttribute('enabled') && $mode !== APP_MODE_ADMIN)) { throw new Exception(Exception::STORAGE_BUCKET_NOT_FOUND); } $validator = new Authorization(Database::PERMISSION_CREATE); - if (!$validator->isValid($bucket->getCreate())) { + if (! $validator->isValid($bucket->getCreate())) { throw new Exception(Exception::USER_UNAUTHORIZED); } @@ -384,7 +377,7 @@ App::post('/v1/storage/buckets/:bucketId/files') // Add permissions for current the user if none were provided. if (\is_null($permissions)) { $permissions = []; - if (!empty($user->getId())) { + if (! empty($user->getId())) { foreach ($allowedPermissions as $permission) { $permissions[] = (new Permission($permission, 'user', $user->getId()))->toString(); } @@ -393,7 +386,7 @@ App::post('/v1/storage/buckets/:bucketId/files') // Users can only manage their own roles, API keys and Admin users can manage any $roles = Authorization::getRoles(); - if (!Auth::isAppUser($roles) && !Auth::isPrivilegedUser($roles)) { + if (! Auth::isAppUser($roles) && ! Auth::isPrivilegedUser($roles)) { foreach (Database::PERMISSIONS as $type) { foreach ($permissions as $permission) { $permission = Permission::parse($permission); @@ -405,8 +398,8 @@ App::post('/v1/storage/buckets/:bucketId/files') $permission->getIdentifier(), $permission->getDimension() ))->toString(); - if (!Authorization::isRole($role)) { - throw new Exception(Exception::USER_UNAUTHORIZED, 'Permissions must be one of: (' . \implode(', ', $roles) . ')'); + if (! Authorization::isRole($role)) { + throw new Exception(Exception::USER_UNAUTHORIZED, 'Permissions must be one of: ('.\implode(', ', $roles).')'); } } } @@ -417,7 +410,6 @@ App::post('/v1/storage/buckets/:bucketId/files') throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Maximum bucket file size is larger than _APP_STORAGE_LIMIT'); } - $file = $request->getFiles('file'); // GraphQL multipart spec adds files with index keys @@ -439,7 +431,7 @@ App::post('/v1/storage/buckets/:bucketId/files') $chunk = 1; $chunks = 1; - if (!empty($contentRange)) { + if (! empty($contentRange)) { $start = $request->getContentRangeStart(); $end = $request->getContentRangeEnd(); $fileSize = $request->getContentRangeSize(); @@ -464,30 +456,30 @@ App::post('/v1/storage/buckets/:bucketId/files') // Check if file type is allowed $allowedFileExtensions = $bucket->getAttribute('allowedFileExtensions', []); $fileExt = new FileExt($allowedFileExtensions); - if (!empty($allowedFileExtensions) && !$fileExt->isValid($fileName)) { + if (! empty($allowedFileExtensions) && ! $fileExt->isValid($fileName)) { throw new Exception(Exception::STORAGE_FILE_TYPE_UNSUPPORTED, 'File extension not allowed'); } // Check if file size is exceeding allowed limit $fileSizeValidator = new FileSize($maximumFileSize); - if (!$fileSizeValidator->isValid($fileSize)) { + if (! $fileSizeValidator->isValid($fileSize)) { throw new Exception(Exception::STORAGE_INVALID_FILE_SIZE, 'File size not allowed'); } $upload = new Upload(); - if (!$upload->isValid($fileTmpName)) { + if (! $upload->isValid($fileTmpName)) { throw new Exception(Exception::STORAGE_INVALID_FILE); } // Save to storage $fileSize ??= $deviceLocal->getFileSize($fileTmpName); - $path = $deviceFiles->getPath($fileId . '.' . \pathinfo($fileName, PATHINFO_EXTENSION)); - $path = str_ireplace($deviceFiles->getRoot(), $deviceFiles->getRoot() . DIRECTORY_SEPARATOR . $bucket->getId(), $path); // Add bucket id to path after root + $path = $deviceFiles->getPath($fileId.'.'.\pathinfo($fileName, PATHINFO_EXTENSION)); + $path = str_ireplace($deviceFiles->getRoot(), $deviceFiles->getRoot().DIRECTORY_SEPARATOR.$bucket->getId(), $path); // Add bucket id to path after root - $file = $dbForProject->getDocument('bucket_' . $bucket->getInternalId(), $fileId); + $file = $dbForProject->getDocument('bucket_'.$bucket->getInternalId(), $fileId); $metadata = ['content_type' => $deviceLocal->getFileMimeType($fileTmpName)]; - if (!$file->isEmpty()) { + if (! $file->isEmpty()) { $chunks = $file->getAttribute('chunksTotal', 1); $metadata = $file->getAttribute('metadata', []); if ($chunk === -1) { @@ -507,7 +499,7 @@ App::post('/v1/storage/buckets/:bucketId/files') (int) App::getEnv('_APP_STORAGE_ANTIVIRUS_PORT', 3310) ); - if (!$antivirus->fileScan($path)) { + if (! $antivirus->fileScan($path)) { $deviceFiles->delete($path); throw new Exception(Exception::STORAGE_INVALID_FILE); } @@ -540,8 +532,8 @@ App::post('/v1/storage/buckets/:bucketId/files') $data = OpenSSL::encrypt($data, OpenSSL::CIPHER_AES_128_GCM, $key, 0, $iv, $tag); } - if (!empty($data)) { - if (!$deviceFiles->write($path, $data, $mimeType)) { + if (! empty($data)) { + if (! $deviceFiles->write($path, $data, $mimeType)) { throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Failed to save file'); } } @@ -585,7 +577,7 @@ App::post('/v1/storage/buckets/:bucketId/files') 'metadata' => $metadata, ]); - $file = $dbForProject->createDocument('bucket_' . $bucket->getInternalId(), $doc); + $file = $dbForProject->createDocument('bucket_'.$bucket->getInternalId(), $doc); } else { $file = $file ->setAttribute('$permissions', $permissions) @@ -600,7 +592,7 @@ App::post('/v1/storage/buckets/:bucketId/files') ->setAttribute('metadata', $metadata) ->setAttribute('chunksUploaded', $chunksUploaded); - $file = $dbForProject->updateDocument('bucket_' . $bucket->getInternalId(), $fileId, $file); + $file = $dbForProject->updateDocument('bucket_'.$bucket->getInternalId(), $fileId, $file); } } catch (AuthorizationException) { throw new Exception(Exception::USER_UNAUTHORIZED); @@ -630,13 +622,13 @@ App::post('/v1/storage/buckets/:bucketId/files') 'metadata' => $metadata, ]); - $file = $dbForProject->createDocument('bucket_' . $bucket->getInternalId(), $doc); + $file = $dbForProject->createDocument('bucket_'.$bucket->getInternalId(), $doc); } else { $file = $file ->setAttribute('chunksUploaded', $chunksUploaded) ->setAttribute('metadata', $metadata); - $file = $dbForProject->updateDocument('bucket_' . $bucket->getInternalId(), $fileId, $file); + $file = $dbForProject->updateDocument('bucket_'.$bucket->getInternalId(), $fileId, $file); } } catch (AuthorizationException) { throw new Exception(Exception::USER_UNAUTHORIZED); @@ -650,13 +642,11 @@ App::post('/v1/storage/buckets/:bucketId/files') $events ->setParam('bucketId', $bucket->getId()) ->setParam('fileId', $file->getId()) - ->setContext('bucket', $bucket) - ; + ->setContext('bucket', $bucket); $deletes ->setType(DELETE_TYPE_CACHE_BY_RESOURCE) - ->setResource('file/' . $file->getId()) - ; + ->setResource('file/'.$file->getId()); $metadata = null; // was causing leaks as it was passed by reference @@ -680,29 +670,28 @@ App::get('/v1/storage/buckets/:bucketId/files') ->label('sdk.response.type', Response::CONTENT_TYPE_JSON) ->label('sdk.response.model', Response::MODEL_FILE_LIST) ->param('bucketId', '', new UID(), 'Storage bucket unique ID. You can create a new storage bucket using the Storage service [server integration](/docs/server/storage#createBucket).') - ->param('queries', [], new Files(), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/databases#querying-documents). Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' queries are allowed, each ' . APP_LIMIT_ARRAY_ELEMENT_SIZE . ' characters long. You may filter on the following attributes: ' . implode(', ', Files::ALLOWED_ATTRIBUTES), true) + ->param('queries', [], new Files(), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/databases#querying-documents). Maximum of '.APP_LIMIT_ARRAY_PARAMS_SIZE.' queries are allowed, each '.APP_LIMIT_ARRAY_ELEMENT_SIZE.' characters long. You may filter on the following attributes: '.implode(', ', Files::ALLOWED_ATTRIBUTES), true) ->param('search', '', new Text(256), 'Search term to filter your list results. Max length: 256 chars.', true) ->inject('response') ->inject('dbForProject') ->inject('mode') ->action(function (string $bucketId, array $queries, string $search, Response $response, Database $dbForProject, string $mode) { - $bucket = Authorization::skip(fn () => $dbForProject->getDocument('buckets', $bucketId)); - if ($bucket->isEmpty() || (!$bucket->getAttribute('enabled') && $mode !== APP_MODE_ADMIN)) { + if ($bucket->isEmpty() || (! $bucket->getAttribute('enabled') && $mode !== APP_MODE_ADMIN)) { throw new Exception(Exception::STORAGE_BUCKET_NOT_FOUND); } $fileSecurity = $bucket->getAttribute('fileSecurity', false); $validator = new Authorization(Database::PERMISSION_READ); $valid = $validator->isValid($bucket->getRead()); - if (!$fileSecurity && !$valid) { + if (! $fileSecurity && ! $valid) { throw new Exception(Exception::USER_UNAUTHORIZED); } $queries = Query::parseQueries($queries); - if (!empty($search)) { + if (! empty($search)) { $queries[] = Query::search('search', $search); } @@ -713,10 +702,10 @@ App::get('/v1/storage/buckets/:bucketId/files') /** @var Query $cursor */ $fileId = $cursor->getValue(); - if ($fileSecurity && !$valid) { - $cursorDocument = $dbForProject->getDocument('bucket_' . $bucket->getInternalId(), $fileId); + if ($fileSecurity && ! $valid) { + $cursorDocument = $dbForProject->getDocument('bucket_'.$bucket->getInternalId(), $fileId); } else { - $cursorDocument = Authorization::skip(fn() => $dbForProject->getDocument('bucket_' . $bucket->getInternalId(), $fileId)); + $cursorDocument = Authorization::skip(fn () => $dbForProject->getDocument('bucket_'.$bucket->getInternalId(), $fileId)); } if ($cursorDocument->isEmpty()) { @@ -728,12 +717,12 @@ App::get('/v1/storage/buckets/:bucketId/files') $filterQueries = Query::groupByType($queries)['filters']; - if ($fileSecurity && !$valid) { - $files = $dbForProject->find('bucket_' . $bucket->getInternalId(), $queries); - $total = $dbForProject->count('bucket_' . $bucket->getInternalId(), $filterQueries, APP_LIMIT_COUNT); + if ($fileSecurity && ! $valid) { + $files = $dbForProject->find('bucket_'.$bucket->getInternalId(), $queries); + $total = $dbForProject->count('bucket_'.$bucket->getInternalId(), $filterQueries, APP_LIMIT_COUNT); } else { - $files = Authorization::skip(fn () => $dbForProject->find('bucket_' . $bucket->getInternalId(), $queries)); - $total = Authorization::skip(fn () => $dbForProject->count('bucket_' . $bucket->getInternalId(), $filterQueries, APP_LIMIT_COUNT)); + $files = Authorization::skip(fn () => $dbForProject->find('bucket_'.$bucket->getInternalId(), $queries)); + $total = Authorization::skip(fn () => $dbForProject->count('bucket_'.$bucket->getInternalId(), $filterQueries, APP_LIMIT_COUNT)); } $response->dynamic(new Document([ @@ -762,24 +751,23 @@ App::get('/v1/storage/buckets/:bucketId/files/:fileId') ->inject('dbForProject') ->inject('mode') ->action(function (string $bucketId, string $fileId, Response $response, Database $dbForProject, string $mode) { - $bucket = Authorization::skip(fn () => $dbForProject->getDocument('buckets', $bucketId)); - if ($bucket->isEmpty() || (!$bucket->getAttribute('enabled') && $mode !== APP_MODE_ADMIN)) { + if ($bucket->isEmpty() || (! $bucket->getAttribute('enabled') && $mode !== APP_MODE_ADMIN)) { throw new Exception(Exception::STORAGE_BUCKET_NOT_FOUND); } $fileSecurity = $bucket->getAttribute('fileSecurity', false); $validator = new Authorization(Database::PERMISSION_READ); $valid = $validator->isValid($bucket->getRead()); - if (!$fileSecurity && !$valid) { + if (! $fileSecurity && ! $valid) { throw new Exception(Exception::USER_UNAUTHORIZED); } - if ($fileSecurity && !$valid) { - $file = $dbForProject->getDocument('bucket_' . $bucket->getInternalId(), $fileId); + if ($fileSecurity && ! $valid) { + $file = $dbForProject->getDocument('bucket_'.$bucket->getInternalId(), $fileId); } else { - $file = Authorization::skip(fn() => $dbForProject->getDocument('bucket_' . $bucket->getInternalId(), $fileId)); + $file = Authorization::skip(fn () => $dbForProject->getDocument('bucket_'.$bucket->getInternalId(), $fileId)); } if ($file->isEmpty()) { @@ -810,7 +798,7 @@ App::get('/v1/storage/buckets/:bucketId/files/:fileId/preview') ->param('fileId', '', new UID(), 'File ID') ->param('width', 0, new Range(0, 4000), 'Resize preview image width, Pass an integer between 0 to 4000.', true) ->param('height', 0, new Range(0, 4000), 'Resize preview image height, Pass an integer between 0 to 4000.', true) - ->param('gravity', Image::GRAVITY_CENTER, new WhiteList(Image::getGravityTypes()), 'Image crop gravity. Can be one of ' . implode(",", Image::getGravityTypes()), true) + ->param('gravity', Image::GRAVITY_CENTER, new WhiteList(Image::getGravityTypes()), 'Image crop gravity. Can be one of '.implode(',', Image::getGravityTypes()), true) ->param('quality', 100, new Range(0, 100), 'Preview image quality. Pass an integer between 0 to 100. Defaults to 100.', true) ->param('borderWidth', 0, new Range(0, 100), 'Preview image border in pixels. Pass an integer between 0 to 100. Defaults to 0.', true) ->param('borderColor', '', new HexColor(), 'Preview image border color. Use a valid HEX color, no # is needed for prefix.', true) @@ -827,21 +815,20 @@ App::get('/v1/storage/buckets/:bucketId/files/:fileId/preview') ->inject('deviceFiles') ->inject('deviceLocal') ->action(function (string $bucketId, string $fileId, int $width, int $height, string $gravity, int $quality, int $borderWidth, string $borderColor, int $borderRadius, float $opacity, int $rotation, string $background, string $output, Request $request, Response $response, Document $project, Database $dbForProject, string $mode, Device $deviceFiles, Device $deviceLocal) { - - if (!\extension_loaded('imagick')) { + if (! \extension_loaded('imagick')) { throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Imagick extension is missing'); } $bucket = Authorization::skip(fn () => $dbForProject->getDocument('buckets', $bucketId)); - if ($bucket->isEmpty() || (!$bucket->getAttribute('enabled') && $mode !== APP_MODE_ADMIN)) { + if ($bucket->isEmpty() || (! $bucket->getAttribute('enabled') && $mode !== APP_MODE_ADMIN)) { throw new Exception(Exception::STORAGE_BUCKET_NOT_FOUND); } $fileSecurity = $bucket->getAttribute('fileSecurity', false); $validator = new Authorization(Database::PERMISSION_READ); $valid = $validator->isValid($bucket->getRead()); - if (!$fileSecurity && !$valid) { + if (! $fileSecurity && ! $valid) { throw new Exception(Exception::USER_UNAUTHORIZED); } @@ -853,10 +840,10 @@ App::get('/v1/storage/buckets/:bucketId/files/:fileId/preview') $outputs = Config::getParam('storage-outputs'); $fileLogos = Config::getParam('storage-logos'); - if ($fileSecurity && !$valid) { - $file = $dbForProject->getDocument('bucket_' . $bucket->getInternalId(), $fileId); + if ($fileSecurity && ! $valid) { + $file = $dbForProject->getDocument('bucket_'.$bucket->getInternalId(), $fileId); } else { - $file = Authorization::skip(fn() => $dbForProject->getDocument('bucket_' . $bucket->getInternalId(), $fileId)); + $file = Authorization::skip(fn () => $dbForProject->getDocument('bucket_'.$bucket->getInternalId(), $fileId)); } if ($file->isEmpty()) { @@ -868,8 +855,8 @@ App::get('/v1/storage/buckets/:bucketId/files/:fileId/preview') $algorithm = $file->getAttribute('algorithm', 'none'); $cipher = $file->getAttribute('openSSLCipher'); $mime = $file->getAttribute('mimeType'); - if (!\in_array($mime, $inputs) || $file->getAttribute('sizeActual') > (int) App::getEnv('_APP_STORAGE_PREVIEW_LIMIT', 20000000)) { - if (!\in_array($mime, $inputs)) { + if (! \in_array($mime, $inputs) || $file->getAttribute('sizeActual') > (int) App::getEnv('_APP_STORAGE_PREVIEW_LIMIT', 20000000)) { + if (! \in_array($mime, $inputs)) { $path = (\array_key_exists($mime, $fileLogos)) ? $fileLogos[$mime] : $fileLogos['default']; } else { // it was an image but the file size exceeded the limit @@ -883,7 +870,7 @@ App::get('/v1/storage/buckets/:bucketId/files/:fileId/preview') $deviceFiles = $deviceLocal; } - if (!$deviceFiles->exists($path)) { + if (! $deviceFiles->exists($path)) { throw new Exception(Exception::STORAGE_FILE_NOT_FOUND); } @@ -893,14 +880,13 @@ App::get('/v1/storage/buckets/:bucketId/files/:fileId/preview') $output = empty($type) ? (array_search($mime, $outputs) ?? 'jpg') : $type; } - $source = $deviceFiles->read($path); - if (!empty($cipher)) { // Decrypt + if (! empty($cipher)) { // Decrypt $source = OpenSSL::decrypt( $source, $file->getAttribute('openSSLCipher'), - App::getEnv('_APP_OPENSSL_KEY_V' . $file->getAttribute('openSSLVersion')), + App::getEnv('_APP_OPENSSL_KEY_V'.$file->getAttribute('openSSLVersion')), 0, \hex2bin($file->getAttribute('openSSLIV')), \hex2bin($file->getAttribute('openSSLTag')) @@ -922,23 +908,23 @@ App::get('/v1/storage/buckets/:bucketId/files/:fileId/preview') $image->crop((int) $width, (int) $height, $gravity); - if (!empty($opacity) || $opacity === 0) { + if (! empty($opacity) || $opacity === 0) { $image->setOpacity($opacity); } - if (!empty($background)) { - $image->setBackground('#' . $background); + if (! empty($background)) { + $image->setBackground('#'.$background); } - if (!empty($borderWidth)) { - $image->setBorder($borderWidth, '#' . $borderColor); + if (! empty($borderWidth)) { + $image->setBorder($borderWidth, '#'.$borderColor); } - if (!empty($borderRadius)) { + if (! empty($borderRadius)) { $image->setBorderRadius($borderRadius); } - if (!empty($rotation)) { + if (! empty($rotation)) { $image->setRotation(($rotation + 360) % 360); } @@ -947,10 +933,9 @@ App::get('/v1/storage/buckets/:bucketId/files/:fileId/preview') $contentType = (\array_key_exists($output, $outputs)) ? $outputs[$output] : $outputs['jpg']; $response - ->addHeader('Expires', \date('D, d M Y H:i:s', \time() + 60 * 60 * 24 * 30) . ' GMT') + ->addHeader('Expires', \date('D, d M Y H:i:s', \time() + 60 * 60 * 24 * 30).' GMT') ->setContentType($contentType) - ->file($data) - ; + ->file($data); unset($image); }); @@ -977,24 +962,23 @@ App::get('/v1/storage/buckets/:bucketId/files/:fileId/download') ->inject('mode') ->inject('deviceFiles') ->action(function (string $bucketId, string $fileId, Request $request, Response $response, Database $dbForProject, string $mode, Device $deviceFiles) { - $bucket = Authorization::skip(fn () => $dbForProject->getDocument('buckets', $bucketId)); - if ($bucket->isEmpty() || (!$bucket->getAttribute('enabled') && $mode !== APP_MODE_ADMIN)) { + if ($bucket->isEmpty() || (! $bucket->getAttribute('enabled') && $mode !== APP_MODE_ADMIN)) { throw new Exception(Exception::STORAGE_BUCKET_NOT_FOUND); } $fileSecurity = $bucket->getAttribute('fileSecurity', false); $validator = new Authorization(Database::PERMISSION_READ); $valid = $validator->isValid($bucket->getRead()); - if (!$fileSecurity && !$valid) { + if (! $fileSecurity && ! $valid) { throw new Exception(Exception::USER_UNAUTHORIZED); } - if ($fileSecurity && !$valid) { - $file = $dbForProject->getDocument('bucket_' . $bucket->getInternalId(), $fileId); + if ($fileSecurity && ! $valid) { + $file = $dbForProject->getDocument('bucket_'.$bucket->getInternalId(), $fileId); } else { - $file = Authorization::skip(fn() => $dbForProject->getDocument('bucket_' . $bucket->getInternalId(), $fileId)); + $file = Authorization::skip(fn () => $dbForProject->getDocument('bucket_'.$bucket->getInternalId(), $fileId)); } if ($file->isEmpty()) { @@ -1003,21 +987,20 @@ App::get('/v1/storage/buckets/:bucketId/files/:fileId/download') $path = $file->getAttribute('path', ''); - if (!$deviceFiles->exists($path)) { - throw new Exception(Exception::STORAGE_FILE_NOT_FOUND, 'File not found in ' . $path); + if (! $deviceFiles->exists($path)) { + throw new Exception(Exception::STORAGE_FILE_NOT_FOUND, 'File not found in '.$path); } $response ->setContentType($file->getAttribute('mimeType')) - ->addHeader('Expires', \date('D, d M Y H:i:s', \time() + (60 * 60 * 24 * 45)) . ' GMT') // 45 days cache + ->addHeader('Expires', \date('D, d M Y H:i:s', \time() + (60 * 60 * 24 * 45)).' GMT') // 45 days cache ->addHeader('X-Peak', \memory_get_peak_usage()) - ->addHeader('Content-Disposition', 'attachment; filename="' . $file->getAttribute('name', '') . '"') - ; + ->addHeader('Content-Disposition', 'attachment; filename="'.$file->getAttribute('name', '').'"'); $size = $file->getAttribute('sizeOriginal', 0); $rangeHeader = $request->getHeader('range'); - if (!empty($rangeHeader)) { + if (! empty($rangeHeader)) { $start = $request->getRangeStart(); $end = $request->getRangeEnd(); $unit = $request->getRangeUnit(); @@ -1032,18 +1015,18 @@ App::get('/v1/storage/buckets/:bucketId/files/:fileId/download') $response ->addHeader('Accept-Ranges', 'bytes') - ->addHeader('Content-Range', 'bytes ' . $start . '-' . $end . '/' . $size) + ->addHeader('Content-Range', 'bytes '.$start.'-'.$end.'/'.$size) ->addHeader('Content-Length', $end - $start + 1) ->setStatusCode(Response::STATUS_CODE_PARTIALCONTENT); } $source = ''; - if (!empty($file->getAttribute('openSSLCipher'))) { // Decrypt + if (! empty($file->getAttribute('openSSLCipher'))) { // Decrypt $source = $deviceFiles->read($path); $source = OpenSSL::decrypt( $source, $file->getAttribute('openSSLCipher'), - App::getEnv('_APP_OPENSSL_KEY_V' . $file->getAttribute('openSSLVersion')), + App::getEnv('_APP_OPENSSL_KEY_V'.$file->getAttribute('openSSLVersion')), 0, \hex2bin($file->getAttribute('openSSLIV')), \hex2bin($file->getAttribute('openSSLTag')) @@ -1067,14 +1050,14 @@ App::get('/v1/storage/buckets/:bucketId/files/:fileId/download') break; } - if (!empty($source)) { - if (!empty($rangeHeader)) { + if (! empty($source)) { + if (! empty($rangeHeader)) { $response->send(substr($source, $start, ($end - $start + 1))); } $response->send($source); } - if (!empty($rangeHeader)) { + if (! empty($rangeHeader)) { $response->send($deviceFiles->read($path, $start, ($end - $start + 1))); } @@ -1117,24 +1100,23 @@ App::get('/v1/storage/buckets/:bucketId/files/:fileId/view') ->inject('mode') ->inject('deviceFiles') ->action(function (string $bucketId, string $fileId, Response $response, Request $request, Database $dbForProject, string $mode, Device $deviceFiles) { - $bucket = Authorization::skip(fn () => $dbForProject->getDocument('buckets', $bucketId)); - if ($bucket->isEmpty() || (!$bucket->getAttribute('enabled') && $mode !== APP_MODE_ADMIN)) { + if ($bucket->isEmpty() || (! $bucket->getAttribute('enabled') && $mode !== APP_MODE_ADMIN)) { throw new Exception(Exception::STORAGE_BUCKET_NOT_FOUND); } $fileSecurity = $bucket->getAttribute('fileSecurity', false); $validator = new Authorization(Database::PERMISSION_READ); $valid = $validator->isValid($bucket->getRead()); - if (!$fileSecurity && !$valid) { + if (! $fileSecurity && ! $valid) { throw new Exception(Exception::USER_UNAUTHORIZED); } - if ($fileSecurity && !$valid) { - $file = $dbForProject->getDocument('bucket_' . $bucket->getInternalId(), $fileId); + if ($fileSecurity && ! $valid) { + $file = $dbForProject->getDocument('bucket_'.$bucket->getInternalId(), $fileId); } else { - $file = Authorization::skip(fn() => $dbForProject->getDocument('bucket_' . $bucket->getInternalId(), $fileId)); + $file = Authorization::skip(fn () => $dbForProject->getDocument('bucket_'.$bucket->getInternalId(), $fileId)); } if ($file->isEmpty()) { @@ -1145,8 +1127,8 @@ App::get('/v1/storage/buckets/:bucketId/files/:fileId/view') $path = $file->getAttribute('path', ''); - if (!$deviceFiles->exists($path)) { - throw new Exception(Exception::STORAGE_FILE_NOT_FOUND, 'File not found in ' . $path); + if (! $deviceFiles->exists($path)) { + throw new Exception(Exception::STORAGE_FILE_NOT_FOUND, 'File not found in '.$path); } $contentType = 'text/plain'; @@ -1159,15 +1141,14 @@ App::get('/v1/storage/buckets/:bucketId/files/:fileId/view') ->setContentType($contentType) ->addHeader('Content-Security-Policy', 'script-src none;') ->addHeader('X-Content-Type-Options', 'nosniff') - ->addHeader('Content-Disposition', 'inline; filename="' . $file->getAttribute('name', '') . '"') - ->addHeader('Expires', \date('D, d M Y H:i:s', \time() + (60 * 60 * 24 * 45)) . ' GMT') // 45 days cache - ->addHeader('X-Peak', \memory_get_peak_usage()) - ; + ->addHeader('Content-Disposition', 'inline; filename="'.$file->getAttribute('name', '').'"') + ->addHeader('Expires', \date('D, d M Y H:i:s', \time() + (60 * 60 * 24 * 45)).' GMT') // 45 days cache + ->addHeader('X-Peak', \memory_get_peak_usage()); $size = $file->getAttribute('sizeOriginal', 0); $rangeHeader = $request->getHeader('range'); - if (!empty($rangeHeader)) { + if (! empty($rangeHeader)) { $start = $request->getRangeStart(); $end = $request->getRangeEnd(); $unit = $request->getRangeUnit(); @@ -1188,12 +1169,12 @@ App::get('/v1/storage/buckets/:bucketId/files/:fileId/view') } $source = ''; - if (!empty($file->getAttribute('openSSLCipher'))) { // Decrypt + if (! empty($file->getAttribute('openSSLCipher'))) { // Decrypt $source = $deviceFiles->read($path); $source = OpenSSL::decrypt( $source, $file->getAttribute('openSSLCipher'), - App::getEnv('_APP_OPENSSL_KEY_V' . $file->getAttribute('openSSLVersion')), + App::getEnv('_APP_OPENSSL_KEY_V'.$file->getAttribute('openSSLVersion')), 0, \hex2bin($file->getAttribute('openSSLIV')), \hex2bin($file->getAttribute('openSSLTag')) @@ -1217,14 +1198,14 @@ App::get('/v1/storage/buckets/:bucketId/files/:fileId/view') break; } - if (!empty($source)) { - if (!empty($rangeHeader)) { + if (! empty($source)) { + if (! empty($rangeHeader)) { $response->send(substr($source, $start, ($end - $start + 1))); } $response->send($source); } - if (!empty($rangeHeader)) { + if (! empty($rangeHeader)) { $response->send($deviceFiles->read($path, $start, ($end - $start + 1))); } @@ -1275,22 +1256,21 @@ App::put('/v1/storage/buckets/:bucketId/files/:fileId') ->inject('mode') ->inject('events') ->action(function (string $bucketId, string $fileId, ?array $permissions, Response $response, Database $dbForProject, Document $user, string $mode, Event $events) { - $bucket = Authorization::skip(fn () => $dbForProject->getDocument('buckets', $bucketId)); - if ($bucket->isEmpty() || (!$bucket->getAttribute('enabled') && $mode !== APP_MODE_ADMIN)) { + if ($bucket->isEmpty() || (! $bucket->getAttribute('enabled') && $mode !== APP_MODE_ADMIN)) { throw new Exception(Exception::STORAGE_BUCKET_NOT_FOUND); } $fileSecurity = $bucket->getAttributes('fileSecurity', false); $validator = new Authorization(Database::PERMISSION_UPDATE); $valid = $validator->isValid($bucket->getUpdate()); - if (!$fileSecurity && !$valid) { + if (! $fileSecurity && ! $valid) { throw new Exception(Exception::USER_UNAUTHORIZED); } // Read permission should not be required for update - $file = Authorization::skip(fn() => $dbForProject->getDocument('bucket_' . $bucket->getInternalId(), $fileId)); + $file = Authorization::skip(fn () => $dbForProject->getDocument('bucket_'.$bucket->getInternalId(), $fileId)); if ($file->isEmpty()) { throw new Exception(Exception::STORAGE_FILE_NOT_FOUND); @@ -1305,7 +1285,7 @@ App::put('/v1/storage/buckets/:bucketId/files/:fileId') // Users can only manage their own roles, API keys and Admin users can manage any $roles = Authorization::getRoles(); - if (!Auth::isAppUser($roles) && !Auth::isPrivilegedUser($roles) && !\is_null($permissions)) { + if (! Auth::isAppUser($roles) && ! Auth::isPrivilegedUser($roles) && ! \is_null($permissions)) { foreach (Database::PERMISSIONS as $type) { foreach ($permissions as $permission) { $permission = Permission::parse($permission); @@ -1317,8 +1297,8 @@ App::put('/v1/storage/buckets/:bucketId/files/:fileId') $permission->getIdentifier(), $permission->getDimension() ))->toString(); - if (!Authorization::isRole($role)) { - throw new Exception(Exception::USER_UNAUTHORIZED, 'Permissions must be one of: (' . \implode(', ', $roles) . ')'); + if (! Authorization::isRole($role)) { + throw new Exception(Exception::USER_UNAUTHORIZED, 'Permissions must be one of: ('.\implode(', ', $roles).')'); } } } @@ -1330,21 +1310,20 @@ App::put('/v1/storage/buckets/:bucketId/files/:fileId') $file->setAttribute('$permissions', $permissions); - if ($fileSecurity && !$valid) { + if ($fileSecurity && ! $valid) { try { - $file = $dbForProject->updateDocument('bucket_' . $bucket->getInternalId(), $fileId, $file); + $file = $dbForProject->updateDocument('bucket_'.$bucket->getInternalId(), $fileId, $file); } catch (AuthorizationException) { throw new Exception(Exception::USER_UNAUTHORIZED); } } else { - $file = Authorization::skip(fn() => $dbForProject->updateDocument('bucket_' . $bucket->getInternalId(), $fileId, $file)); + $file = Authorization::skip(fn () => $dbForProject->updateDocument('bucket_'.$bucket->getInternalId(), $fileId, $file)); } $events ->setParam('bucketId', $bucket->getId()) ->setParam('fileId', $file->getId()) - ->setContext('bucket', $bucket) - ; + ->setContext('bucket', $bucket); $response->dynamic($file, Response::MODEL_FILE); }); @@ -1379,26 +1358,26 @@ App::delete('/v1/storage/buckets/:bucketId/files/:fileId') ->action(function (string $bucketId, string $fileId, Response $response, Database $dbForProject, Event $events, string $mode, Device $deviceFiles, Delete $deletes) { $bucket = Authorization::skip(fn () => $dbForProject->getDocument('buckets', $bucketId)); - if ($bucket->isEmpty() || (!$bucket->getAttribute('enabled') && $mode !== APP_MODE_ADMIN)) { + if ($bucket->isEmpty() || (! $bucket->getAttribute('enabled') && $mode !== APP_MODE_ADMIN)) { throw new Exception(Exception::STORAGE_BUCKET_NOT_FOUND); } $fileSecurity = $bucket->getAttributes('fileSecurity', false); $validator = new Authorization(Database::PERMISSION_DELETE); $valid = $validator->isValid($bucket->getDelete()); - if (!$fileSecurity && !$valid) { + if (! $fileSecurity && ! $valid) { throw new Exception(Exception::USER_UNAUTHORIZED); } // Read permission should not be required for delete - $file = Authorization::skip(fn() => $dbForProject->getDocument('bucket_' . $bucket->getInternalId(), $fileId)); + $file = Authorization::skip(fn () => $dbForProject->getDocument('bucket_'.$bucket->getInternalId(), $fileId)); if ($file->isEmpty()) { throw new Exception(Exception::STORAGE_FILE_NOT_FOUND); } // Make sure we don't delete the file before the document permission check occurs - if ($fileSecurity && !$valid && !$validator->isValid($file->getDelete())) { + if ($fileSecurity && ! $valid && ! $validator->isValid($file->getDelete())) { throw new Exception(Exception::USER_UNAUTHORIZED); } @@ -1415,20 +1394,19 @@ App::delete('/v1/storage/buckets/:bucketId/files/:fileId') if ($deviceDeleted) { $deletes ->setType(DELETE_TYPE_CACHE_BY_RESOURCE) - ->setResource('file/' . $fileId) - ; + ->setResource('file/'.$fileId); - if ($fileSecurity && !$valid) { + if ($fileSecurity && ! $valid) { try { - $deleted = $dbForProject->deleteDocument('bucket_' . $bucket->getInternalId(), $fileId); + $deleted = $dbForProject->deleteDocument('bucket_'.$bucket->getInternalId(), $fileId); } catch (AuthorizationException) { throw new Exception(Exception::USER_UNAUTHORIZED); } } else { - $deleted = Authorization::skip(fn() => $dbForProject->deleteDocument('bucket_' . $bucket->getInternalId(), $fileId)); + $deleted = Authorization::skip(fn () => $dbForProject->deleteDocument('bucket_'.$bucket->getInternalId(), $fileId)); } - if (!$deleted) { + if (! $deleted) { throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Failed to remove file from DB'); } } else { @@ -1439,8 +1417,7 @@ App::delete('/v1/storage/buckets/:bucketId/files/:fileId') ->setParam('bucketId', $bucket->getId()) ->setParam('fileId', $file->getId()) ->setContext('bucket', $bucket) - ->setPayload($response->output($file, Response::MODEL_FILE)) - ; + ->setPayload($response->output($file, Response::MODEL_FILE)); $response->noContent(); }); @@ -1459,7 +1436,6 @@ App::get('/v1/storage/usage') ->inject('response') ->inject('dbForProject') ->action(function (string $range, Response $response, Database $dbForProject) { - $usage = []; if (App::getEnv('_APP_USAGE_STATS', 'enabled') === 'enabled') { $periods = [ @@ -1570,7 +1546,6 @@ App::get('/v1/storage/:bucketId/usage') ->inject('response') ->inject('dbForProject') ->action(function (string $bucketId, string $range, Response $response, Database $dbForProject) { - $bucket = $dbForProject->getDocument('buckets', $bucketId); if ($bucket->isEmpty()) { diff --git a/app/controllers/api/teams.php b/app/controllers/api/teams.php index a6a49fd798..65bfab7827 100644 --- a/app/controllers/api/teams.php +++ b/app/controllers/api/teams.php @@ -7,7 +7,6 @@ use Appwrite\Event\Event; use Appwrite\Event\Mail; use Appwrite\Extend\Exception; use Appwrite\Network\Validator\Email; -use Utopia\Validator\Host; use Appwrite\Template\Template; use Appwrite\Utopia\Database\Validator\CustomId; use Appwrite\Utopia\Database\Validator\Queries; @@ -23,22 +22,21 @@ use Utopia\Audit\Audit; use Utopia\CLI\Console; use Utopia\Config\Config; use Utopia\Database\Database; +use Utopia\Database\DateTime; use Utopia\Database\Document; use Utopia\Database\Exception\Authorization as AuthorizationException; use Utopia\Database\Exception\Duplicate; use Utopia\Database\Helpers\ID; use Utopia\Database\Helpers\Permission; -use Utopia\Database\Query; -use Utopia\Database\DateTime; use Utopia\Database\Helpers\Role; +use Utopia\Database\Query; use Utopia\Database\Validator\Authorization; use Utopia\Database\Validator\Key; use Utopia\Database\Validator\UID; use Utopia\Locale\Locale; -use Utopia\Validator\Text; -use Utopia\Validator\Range; use Utopia\Validator\ArrayList; -use Utopia\Validator\WhiteList; +use Utopia\Validator\Host; +use Utopia\Validator\Text; App::post('/v1/teams') ->desc('Create Team') @@ -56,18 +54,17 @@ App::post('/v1/teams') ->label('sdk.response.model', Response::MODEL_TEAM) ->param('teamId', '', new CustomId(), 'Team ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can\'t start with a special char. Max length is 36 chars.') ->param('name', null, new Text(128), 'Team name. Max length: 128 chars.') - ->param('roles', ['owner'], new ArrayList(new Key(), APP_LIMIT_ARRAY_PARAMS_SIZE), 'Array of strings. Use this param to set the roles in the team for the user who created it. The default role is **owner**. A role can be any string. Learn more about [roles and permissions](/docs/permissions). Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' roles are allowed, each 32 characters long.', true) + ->param('roles', ['owner'], new ArrayList(new Key(), APP_LIMIT_ARRAY_PARAMS_SIZE), 'Array of strings. Use this param to set the roles in the team for the user who created it. The default role is **owner**. A role can be any string. Learn more about [roles and permissions](/docs/permissions). Maximum of '.APP_LIMIT_ARRAY_PARAMS_SIZE.' roles are allowed, each 32 characters long.', true) ->inject('response') ->inject('user') ->inject('dbForProject') ->inject('events') ->action(function (string $teamId, string $name, array $roles, Response $response, Document $user, Database $dbForProject, Event $events) { - $isPrivilegedUser = Auth::isPrivilegedUser(Authorization::getRoles()); $isAppUser = Auth::isAppUser(Authorization::getRoles()); $teamId = $teamId == 'unique()' ? ID::unique() : $teamId; - $team = Authorization::skip(fn() => $dbForProject->createDocument('teams', new Document([ + $team = Authorization::skip(fn () => $dbForProject->createDocument('teams', new Document([ '$id' => $teamId, '$permissions' => [ Permission::read(Role::team($teamId)), @@ -79,8 +76,8 @@ App::post('/v1/teams') 'search' => implode(' ', [$teamId, $name]), ]))); - if (!$isPrivilegedUser && !$isAppUser) { // Don't add user on server mode - if (!\in_array('owner', $roles)) { + if (! $isPrivilegedUser && ! $isAppUser) { // Don't add user on server mode + if (! \in_array('owner', $roles)) { $roles[] = 'owner'; } @@ -104,7 +101,7 @@ App::post('/v1/teams') 'joined' => DateTime::now(), 'confirm' => true, 'secret' => '', - 'search' => implode(' ', [$membershipId, $user->getId()]) + 'search' => implode(' ', [$membershipId, $user->getId()]), ]); $membership = $dbForProject->createDocument('memberships', $membership); @@ -113,7 +110,7 @@ App::post('/v1/teams') $events->setParam('teamId', $team->getId()); - if (!empty($user->getId())) { + if (! empty($user->getId())) { $events->setParam('userId', $user->getId()); } @@ -134,15 +131,14 @@ App::get('/v1/teams') ->label('sdk.response.type', Response::CONTENT_TYPE_JSON) ->label('sdk.response.model', Response::MODEL_TEAM_LIST) ->label('sdk.offline.model', '/teams') - ->param('queries', [], new Teams(), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/databases#querying-documents). Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' queries are allowed, each ' . APP_LIMIT_ARRAY_ELEMENT_SIZE . ' characters long. You may filter on the following attributes: ' . implode(', ', Teams::ALLOWED_ATTRIBUTES), true) + ->param('queries', [], new Teams(), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/databases#querying-documents). Maximum of '.APP_LIMIT_ARRAY_PARAMS_SIZE.' queries are allowed, each '.APP_LIMIT_ARRAY_ELEMENT_SIZE.' characters long. You may filter on the following attributes: '.implode(', ', Teams::ALLOWED_ATTRIBUTES), true) ->param('search', '', new Text(256), 'Search term to filter your list results. Max length: 256 chars.', true) ->inject('response') ->inject('dbForProject') ->action(function (array $queries, string $search, Response $response, Database $dbForProject) { - $queries = Query::parseQueries($queries); - if (!empty($search)) { + if (! empty($search)) { $queries[] = Query::search('search', $search); } @@ -189,7 +185,6 @@ App::get('/v1/teams/:teamId') ->inject('response') ->inject('dbForProject') ->action(function (string $teamId, Response $response, Database $dbForProject) { - $team = $dbForProject->getDocument('teams', $teamId); if ($team->isEmpty()) { @@ -221,7 +216,6 @@ App::put('/v1/teams/:teamId') ->inject('dbForProject') ->inject('events') ->action(function (string $teamId, string $name, Response $response, Database $dbForProject, Event $events) { - $team = $dbForProject->getDocument('teams', $teamId); if ($team->isEmpty()) { @@ -256,7 +250,6 @@ App::delete('/v1/teams/:teamId') ->inject('events') ->inject('deletes') ->action(function (string $teamId, Response $response, Database $dbForProject, Event $events, Delete $deletes) { - $team = $dbForProject->getDocument('teams', $teamId); if ($team->isEmpty()) { @@ -270,12 +263,12 @@ App::delete('/v1/teams/:teamId') // TODO delete all members individually from the user object foreach ($memberships as $membership) { - if (!$dbForProject->deleteDocument('memberships', $membership->getId())) { + if (! $dbForProject->deleteDocument('memberships', $membership->getId())) { throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Failed to remove membership for team from DB'); } } - if (!$dbForProject->deleteDocument('teams', $teamId)) { + if (! $dbForProject->deleteDocument('teams', $teamId)) { throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Failed to remove team from DB'); } @@ -285,8 +278,7 @@ App::delete('/v1/teams/:teamId') $events ->setParam('teamId', $team->getId()) - ->setPayload($response->output($team, Response::MODEL_TEAM)) - ; + ->setPayload($response->output($team, Response::MODEL_TEAM)); $response->noContent(); }); @@ -310,8 +302,8 @@ App::post('/v1/teams/:teamId/memberships') ->label('abuse-limit', 10) ->param('teamId', '', new UID(), 'Team ID.') ->param('email', '', new Email(), 'Email of the new team member.') - ->param('roles', [], new ArrayList(new Key(), APP_LIMIT_ARRAY_PARAMS_SIZE), 'Array of strings. Use this param to set the user roles in the team. A role can be any string. Learn more about [roles and permissions](/docs/permissions). Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' roles are allowed, each 32 characters long.') - ->param('url', '', fn($clients) => new Host($clients), 'URL to redirect the user back to your app from the invitation email. Only URLs from hostnames in your project platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API.', false, ['clients']) // TODO add our own built-in confirm page + ->param('roles', [], new ArrayList(new Key(), APP_LIMIT_ARRAY_PARAMS_SIZE), 'Array of strings. Use this param to set the user roles in the team. A role can be any string. Learn more about [roles and permissions](/docs/permissions). Maximum of '.APP_LIMIT_ARRAY_PARAMS_SIZE.' roles are allowed, each 32 characters long.') + ->param('url', '', fn ($clients) => new Host($clients), 'URL to redirect the user back to your app from the invitation email. Only URLs from hostnames in your project platform list are allowed. This requirement helps to prevent an [open redirect](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html) attack against your project API.', false, ['clients']) // TODO add our own built-in confirm page ->param('name', '', new Text(128), 'Name of the new team member. Max length: 128 chars.', true) ->inject('response') ->inject('project') @@ -321,11 +313,10 @@ App::post('/v1/teams/:teamId/memberships') ->inject('mails') ->inject('events') ->action(function (string $teamId, string $email, array $roles, string $url, string $name, Response $response, Document $project, Document $user, Database $dbForProject, Locale $locale, Mail $mails, Event $events) { - $isPrivilegedUser = Auth::isPrivilegedUser(Authorization::getRoles()); $isAppUser = Auth::isAppUser(Authorization::getRoles()); - if (!$isPrivilegedUser && !$isAppUser && empty(App::getEnv('_APP_SMTP_HOST'))) { + if (! $isPrivilegedUser && ! $isAppUser && empty(App::getEnv('_APP_SMTP_HOST'))) { throw new Exception(Exception::GENERAL_SMTP_DISABLED); } @@ -352,7 +343,7 @@ App::post('/v1/teams/:teamId/memberships') try { $userId = ID::unique(); - $invitee = Authorization::skip(fn() => $dbForProject->createDocument('users', new Document([ + $invitee = Authorization::skip(fn () => $dbForProject->createDocument('users', new Document([ '$id' => $userId, '$permissions' => [ Permission::read(Role::any()), @@ -379,16 +370,16 @@ App::post('/v1/teams/:teamId/memberships') 'sessions' => null, 'tokens' => null, 'memberships' => null, - 'search' => implode(' ', [$userId, $email, $name]) + 'search' => implode(' ', [$userId, $email, $name]), ]))); } catch (Duplicate $th) { throw new Exception(Exception::USER_ALREADY_EXISTS); } } - $isOwner = Authorization::isRole('team:' . $team->getId() . '/owner'); + $isOwner = Authorization::isRole('team:'.$team->getId().'/owner'); - if (!$isOwner && !$isPrivilegedUser && !$isAppUser) { // Not owner, not admin, not app (server) + if (! $isOwner && ! $isPrivilegedUser && ! $isAppUser) { // Not owner, not admin, not app (server) throw new Exception(Exception::USER_UNAUTHORIZED, 'User is not allowed to send invitations for this team'); } @@ -413,17 +404,17 @@ App::post('/v1/teams/:teamId/memberships') 'joined' => ($isPrivilegedUser || $isAppUser) ? DateTime::now() : null, 'confirm' => ($isPrivilegedUser || $isAppUser), 'secret' => Auth::hash($secret), - 'search' => implode(' ', [$membershipId, $invitee->getId()]) + 'search' => implode(' ', [$membershipId, $invitee->getId()]), ]); if ($isPrivilegedUser || $isAppUser) { // Allow admin to create membership try { - $membership = Authorization::skip(fn() => $dbForProject->createDocument('memberships', $membership)); + $membership = Authorization::skip(fn () => $dbForProject->createDocument('memberships', $membership)); } catch (Duplicate $th) { throw new Exception(Exception::TEAM_INVITE_ALREADY_EXISTS); } $team->setAttribute('total', $team->getAttribute('total', 0) + 1); - $team = Authorization::skip(fn() => $dbForProject->updateDocument('teams', $team->getId(), $team)); + $team = Authorization::skip(fn () => $dbForProject->updateDocument('teams', $team->getId(), $team)); $dbForProject->deleteCachedDocument('users', $invitee->getId()); } else { @@ -438,24 +429,24 @@ App::post('/v1/teams/:teamId/memberships') $url['query'] = Template::mergeQuery(((isset($url['query'])) ? $url['query'] : ''), ['membershipId' => $membership->getId(), 'userId' => $invitee->getId(), 'secret' => $secret, 'teamId' => $teamId]); $url = Template::unParseURL($url); - if (!$isPrivilegedUser && !$isAppUser) { // No need of confirmation when in admin or app mode + if (! $isPrivilegedUser && ! $isAppUser) { // No need of confirmation when in admin or app mode $projectName = $project->isEmpty() ? 'Console' : $project->getAttribute('name', '[APP-NAME]'); $from = $project->isEmpty() || $project->getId() === 'console' ? '' : \sprintf($locale->getText('emails.sender'), $projectName); - $body = Template::fromFile(__DIR__ . '/../../config/locale/templates/email-base.tpl'); - $subject = \sprintf($locale->getText("emails.invitation.subject"), $team->getAttribute('name'), $projectName); + $body = Template::fromFile(__DIR__.'/../../config/locale/templates/email-base.tpl'); + $subject = \sprintf($locale->getText('emails.invitation.subject'), $team->getAttribute('name'), $projectName); $body->setParam('{{owner}}', $user->getAttribute('name')); $body->setParam('{{team}}', $team->getAttribute('name')); $body ->setParam('{{subject}}', $subject) - ->setParam('{{hello}}', $locale->getText("emails.invitation.hello")) + ->setParam('{{hello}}', $locale->getText('emails.invitation.hello')) ->setParam('{{name}}', $user->getAttribute('name')) - ->setParam('{{body}}', $locale->getText("emails.invitation.body")) + ->setParam('{{body}}', $locale->getText('emails.invitation.body')) ->setParam('{{redirect}}', $url) - ->setParam('{{footer}}', $locale->getText("emails.invitation.footer")) - ->setParam('{{thanks}}', $locale->getText("emails.invitation.thanks")) - ->setParam('{{signature}}', $locale->getText("emails.invitation.signature")) + ->setParam('{{footer}}', $locale->getText('emails.invitation.footer')) + ->setParam('{{thanks}}', $locale->getText('emails.invitation.thanks')) + ->setParam('{{signature}}', $locale->getText('emails.invitation.signature')) ->setParam('{{project}}', $projectName) ->setParam('{{direction}}', $locale->getText('settings.direction')) ->setParam('{{bg-body}}', '#f7f7f7') @@ -470,14 +461,12 @@ App::post('/v1/teams/:teamId/memberships') ->setFrom($from) ->setRecipient($invitee->getAttribute('email')) ->setName($invitee->getAttribute('name')) - ->trigger() - ; + ->trigger(); } $events ->setParam('teamId', $team->getId()) - ->setParam('membershipId', $membership->getId()) - ; + ->setParam('membershipId', $membership->getId()); $response ->setStatusCode(Response::STATUS_CODE_CREATED) @@ -503,12 +492,11 @@ App::get('/v1/teams/:teamId/memberships') ->label('sdk.response.model', Response::MODEL_MEMBERSHIP_LIST) ->label('sdk.offline.model', '/teams/{teamId}/memberships') ->param('teamId', '', new UID(), 'Team ID.') - ->param('queries', [], new Memberships(), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/databases#querying-documents). Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' queries are allowed, each ' . APP_LIMIT_ARRAY_ELEMENT_SIZE . ' characters long. You may filter on the following attributes: ' . implode(', ', Memberships::ALLOWED_ATTRIBUTES), true) + ->param('queries', [], new Memberships(), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/databases#querying-documents). Maximum of '.APP_LIMIT_ARRAY_PARAMS_SIZE.' queries are allowed, each '.APP_LIMIT_ARRAY_ELEMENT_SIZE.' characters long. You may filter on the following attributes: '.implode(', ', Memberships::ALLOWED_ATTRIBUTES), true) ->param('search', '', new Text(256), 'Search term to filter your list results. Max length: 256 chars.', true) ->inject('response') ->inject('dbForProject') ->action(function (string $teamId, array $queries, string $search, Response $response, Database $dbForProject) { - $team = $dbForProject->getDocument('teams', $teamId); if ($team->isEmpty()) { @@ -517,7 +505,7 @@ App::get('/v1/teams/:teamId/memberships') $queries = Query::parseQueries($queries); - if (!empty($search)) { + if (! empty($search)) { $queries[] = Query::search('search', $search); } @@ -552,7 +540,7 @@ App::get('/v1/teams/:teamId/memberships') max: APP_LIMIT_COUNT ); - $memberships = array_filter($memberships, fn(Document $membership) => !empty($membership->getAttribute('userId'))); + $memberships = array_filter($memberships, fn (Document $membership) => ! empty($membership->getAttribute('userId'))); $memberships = array_map(function ($membership) use ($dbForProject, $team) { $user = $dbForProject->getDocument('users', $membership->getAttribute('userId')); @@ -560,8 +548,7 @@ App::get('/v1/teams/:teamId/memberships') $membership ->setAttribute('teamName', $team->getAttribute('name')) ->setAttribute('userName', $user->getAttribute('name')) - ->setAttribute('userEmail', $user->getAttribute('email')) - ; + ->setAttribute('userEmail', $user->getAttribute('email')); return $membership; }, $memberships); @@ -590,7 +577,6 @@ App::get('/v1/teams/:teamId/memberships/:membershipId') ->inject('response') ->inject('dbForProject') ->action(function (string $teamId, string $membershipId, Response $response, Database $dbForProject) { - $team = $dbForProject->getDocument('teams', $teamId); if ($team->isEmpty()) { @@ -608,8 +594,7 @@ App::get('/v1/teams/:teamId/memberships/:membershipId') $membership ->setAttribute('teamName', $team->getAttribute('name')) ->setAttribute('userName', $user->getAttribute('name')) - ->setAttribute('userEmail', $user->getAttribute('email')) - ; + ->setAttribute('userEmail', $user->getAttribute('email')); $response->dynamic($membership, Response::MODEL_MEMBERSHIP); }); @@ -630,14 +615,13 @@ App::patch('/v1/teams/:teamId/memberships/:membershipId') ->label('sdk.response.model', Response::MODEL_MEMBERSHIP) ->param('teamId', '', new UID(), 'Team ID.') ->param('membershipId', '', new UID(), 'Membership ID.') - ->param('roles', [], new ArrayList(new Key(), APP_LIMIT_ARRAY_PARAMS_SIZE), 'An array of strings. Use this param to set the user\'s roles in the team. A role can be any string. Learn more about [roles and permissions](https://appwrite.io/docs/permissions). Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' roles are allowed, each 32 characters long.') + ->param('roles', [], new ArrayList(new Key(), APP_LIMIT_ARRAY_PARAMS_SIZE), 'An array of strings. Use this param to set the user\'s roles in the team. A role can be any string. Learn more about [roles and permissions](https://appwrite.io/docs/permissions). Maximum of '.APP_LIMIT_ARRAY_PARAMS_SIZE.' roles are allowed, each 32 characters long.') ->inject('request') ->inject('response') ->inject('user') ->inject('dbForProject') ->inject('events') ->action(function (string $teamId, string $membershipId, array $roles, Request $request, Response $response, Document $user, Database $dbForProject, Event $events) { - $team = $dbForProject->getDocument('teams', $teamId); if ($team->isEmpty()) { throw new Exception(Exception::TEAM_NOT_FOUND); @@ -655,9 +639,9 @@ App::patch('/v1/teams/:teamId/memberships/:membershipId') $isPrivilegedUser = Auth::isPrivilegedUser(Authorization::getRoles()); $isAppUser = Auth::isAppUser(Authorization::getRoles()); - $isOwner = Authorization::isRole('team:' . $team->getId() . '/owner'); + $isOwner = Authorization::isRole('team:'.$team->getId().'/owner'); - if (!$isOwner && !$isPrivilegedUser && !$isAppUser) { // Not owner, not admin, not app (server) + if (! $isOwner && ! $isPrivilegedUser && ! $isAppUser) { // Not owner, not admin, not app (server) throw new Exception(Exception::USER_UNAUTHORIZED, 'User is not allowed to modify roles'); } @@ -724,7 +708,7 @@ App::patch('/v1/teams/:teamId/memberships/:membershipId/status') throw new Exception(Exception::TEAM_MEMBERSHIP_MISMATCH); } - $team = Authorization::skip(fn() => $dbForProject->getDocument('teams', $teamId)); + $team = Authorization::skip(fn () => $dbForProject->getDocument('teams', $teamId)); if ($team->isEmpty()) { throw new Exception(Exception::TEAM_NOT_FOUND); @@ -735,7 +719,7 @@ App::patch('/v1/teams/:teamId/memberships/:membershipId/status') } if ($userId !== $membership->getAttribute('userId')) { - throw new Exception(Exception::TEAM_INVITE_MISMATCH, 'Invite does not belong to current user (' . $user->getAttribute('email') . ')'); + throw new Exception(Exception::TEAM_INVITE_MISMATCH, 'Invite does not belong to current user ('.$user->getAttribute('email').')'); } if ($user->isEmpty()) { @@ -743,7 +727,7 @@ App::patch('/v1/teams/:teamId/memberships/:membershipId/status') } if ($membership->getAttribute('userId') !== $user->getId()) { - throw new Exception(Exception::TEAM_INVITE_MISMATCH, 'Invite does not belong to current user (' . $user->getAttribute('email') . ')'); + throw new Exception(Exception::TEAM_INVITE_MISMATCH, 'Invite does not belong to current user ('.$user->getAttribute('email').')'); } if ($membership->getAttribute('confirm') === true) { @@ -752,10 +736,9 @@ App::patch('/v1/teams/:teamId/memberships/:membershipId/status') $membership // Attach user to team ->setAttribute('joined', DateTime::now()) - ->setAttribute('confirm', true) - ; + ->setAttribute('confirm', true); - $user = Authorization::skip(fn() => $dbForProject->updateDocument('users', $user->getId(), $user->setAttribute('emailVerification', true))); + $user = Authorization::skip(fn () => $dbForProject->updateDocument('users', $user->getId(), $user->setAttribute('emailVerification', true))); // Log user in @@ -793,23 +776,20 @@ App::patch('/v1/teams/:teamId/memberships/:membershipId/status') $dbForProject->deleteCachedDocument('users', $user->getId()); - $team = Authorization::skip(fn() => $dbForProject->updateDocument('teams', $team->getId(), $team->setAttribute('total', $team->getAttribute('total', 0) + 1))); + $team = Authorization::skip(fn () => $dbForProject->updateDocument('teams', $team->getId(), $team->setAttribute('total', $team->getAttribute('total', 0) + 1))); $events ->setParam('teamId', $team->getId()) - ->setParam('membershipId', $membership->getId()) - ; + ->setParam('membershipId', $membership->getId()); - if (!Config::getParam('domainVerification')) { + if (! Config::getParam('domainVerification')) { $response - ->addHeader('X-Fallback-Cookies', \json_encode([Auth::$cookieName => Auth::encodeSession($user->getId(), $secret)])) - ; + ->addHeader('X-Fallback-Cookies', \json_encode([Auth::$cookieName => Auth::encodeSession($user->getId(), $secret)])); } $response - ->addCookie(Auth::$cookieName . '_legacy', Auth::encodeSession($user->getId(), $secret), (new \DateTime($expire))->getTimestamp(), '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, null) - ->addCookie(Auth::$cookieName, Auth::encodeSession($user->getId(), $secret), (new \DateTime($expire))->getTimestamp(), '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, Config::getParam('cookieSamesite')) - ; + ->addCookie(Auth::$cookieName.'_legacy', Auth::encodeSession($user->getId(), $secret), (new \DateTime($expire))->getTimestamp(), '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, null) + ->addCookie(Auth::$cookieName, Auth::encodeSession($user->getId(), $secret), (new \DateTime($expire))->getTimestamp(), '/', Config::getParam('cookieDomain'), ('https' == $protocol), true, Config::getParam('cookieSamesite')); $response->dynamic( $membership @@ -839,7 +819,6 @@ App::delete('/v1/teams/:teamId/memberships/:membershipId') ->inject('dbForProject') ->inject('events') ->action(function (string $teamId, string $membershipId, Response $response, Database $dbForProject, Event $events) { - $membership = $dbForProject->getDocument('memberships', $membershipId); if ($membership->isEmpty()) { @@ -874,14 +853,13 @@ App::delete('/v1/teams/:teamId/memberships/:membershipId') if ($membership->getAttribute('confirm')) { // Count only confirmed members $team->setAttribute('total', \max($team->getAttribute('total', 0) - 1, 0)); - Authorization::skip(fn() => $dbForProject->updateDocument('teams', $team->getId(), $team)); + Authorization::skip(fn () => $dbForProject->updateDocument('teams', $team->getId(), $team)); } $events ->setParam('teamId', $team->getId()) ->setParam('membershipId', $membership->getId()) - ->setPayload($response->output($membership, Response::MODEL_MEMBERSHIP)) - ; + ->setPayload($response->output($membership, Response::MODEL_MEMBERSHIP)); $response->noContent(); }); @@ -904,7 +882,6 @@ App::get('/v1/teams/:teamId/logs') ->inject('locale') ->inject('geodb') ->action(function (string $teamId, array $queries, Response $response, Database $dbForProject, Locale $locale, Reader $geodb) { - $team = $dbForProject->getDocument('teams', $teamId); if ($team->isEmpty()) { @@ -917,13 +894,13 @@ App::get('/v1/teams/:teamId/logs') $offset = $grouped['offset'] ?? 0; $audit = new Audit($dbForProject); - $resource = 'team/' . $team->getId(); + $resource = 'team/'.$team->getId(); $logs = $audit->getLogsByResource($resource, $limit, $offset); $output = []; foreach ($logs as $i => &$log) { - $log['userAgent'] = (!empty($log['userAgent'])) ? $log['userAgent'] : 'UNKNOWN'; + $log['userAgent'] = (! empty($log['userAgent'])) ? $log['userAgent'] : 'UNKNOWN'; $detector = new Detector($log['userAgent']); $detector->skipBotDetection(); // OPTIONAL: If called, bot detection will completely be skipped (bots will be detected as regular devices then) @@ -951,14 +928,14 @@ App::get('/v1/teams/:teamId/logs') 'clientEngineVersion' => $client['clientEngineVersion'], 'deviceName' => $device['deviceName'], 'deviceBrand' => $device['deviceBrand'], - 'deviceModel' => $device['deviceModel'] + 'deviceModel' => $device['deviceModel'], ]); $record = $geodb->get($log['ip']); if ($record) { - $output[$i]['countryCode'] = $locale->getText('countries.' . strtolower($record['country']['iso_code']), false) ? \strtolower($record['country']['iso_code']) : '--'; - $output[$i]['countryName'] = $locale->getText('countries.' . strtolower($record['country']['iso_code']), $locale->getText('locale.country.unknown')); + $output[$i]['countryCode'] = $locale->getText('countries.'.strtolower($record['country']['iso_code']), false) ? \strtolower($record['country']['iso_code']) : '--'; + $output[$i]['countryName'] = $locale->getText('countries.'.strtolower($record['country']['iso_code']), $locale->getText('locale.country.unknown')); } else { $output[$i]['countryCode'] = '--'; $output[$i]['countryName'] = $locale->getText('locale.country.unknown'); diff --git a/app/controllers/api/users.php b/app/controllers/api/users.php index 2a84c06675..d520795db0 100644 --- a/app/controllers/api/users.php +++ b/app/controllers/api/users.php @@ -6,6 +6,7 @@ use Appwrite\Auth\Validator\Phone; use Appwrite\Detector\Detector; use Appwrite\Event\Delete; use Appwrite\Event\Event; +use Appwrite\Extend\Exception; use Appwrite\Network\Validator\Email; use Appwrite\Utopia\Database\Validator\CustomId; use Appwrite\Utopia\Database\Validator\Queries; @@ -13,34 +14,33 @@ use Appwrite\Utopia\Database\Validator\Queries\Users; use Appwrite\Utopia\Database\Validator\Query\Limit; use Appwrite\Utopia\Database\Validator\Query\Offset; use Appwrite\Utopia\Response; +use MaxMind\Db\Reader; use Utopia\App; use Utopia\Audit\Audit; use Utopia\Config\Config; +use Utopia\Database\Database; +use Utopia\Database\DateTime; +use Utopia\Database\Document; +use Utopia\Database\Exception\Duplicate; use Utopia\Database\Helpers\ID; use Utopia\Database\Helpers\Permission; use Utopia\Database\Helpers\Role; -use Utopia\Locale\Locale; -use Appwrite\Extend\Exception; -use Utopia\Database\Document; -use Utopia\Database\DateTime; -use Utopia\Database\Exception\Duplicate; -use Utopia\Database\Validator\UID; -use Utopia\Database\Database; use Utopia\Database\Query; use Utopia\Database\Validator\Authorization; +use Utopia\Database\Validator\UID; +use Utopia\Locale\Locale; use Utopia\Validator\Assoc; -use Utopia\Validator\WhiteList; -use Utopia\Validator\Text; use Utopia\Validator\Boolean; -use MaxMind\Db\Reader; use Utopia\Validator\Integer; +use Utopia\Validator\Text; +use Utopia\Validator\WhiteList; /** TODO: Remove function when we move to using utopia/platform */ function createUser(string $hash, mixed $hashOptions, string $userId, ?string $email, ?string $password, ?string $phone, string $name, Database $dbForProject, Event $events): Document { $hashOptionsObject = (\is_string($hashOptions)) ? \json_decode($hashOptions, true) : $hashOptions; // Cast to JSON array - if (!empty($email)) { + if (! empty($email)) { $email = \strtolower($email); } @@ -61,10 +61,10 @@ function createUser(string $hash, mixed $hashOptions, string $userId, ?string $e 'phone' => $phone, 'phoneVerification' => false, 'status' => true, - 'password' => (!empty($password)) ? ($hash === 'plaintext' ? Auth::passwordHash($password, $hash, $hashOptionsObject) : $password) : null, + 'password' => (! empty($password)) ? ($hash === 'plaintext' ? Auth::passwordHash($password, $hash, $hashOptionsObject) : $password) : null, 'hash' => $hash === 'plaintext' ? Auth::DEFAULT_ALGO : $hash, 'hashOptions' => $hash === 'plaintext' ? Auth::DEFAULT_ALGO_OPTIONS : $hashOptionsObject + ['type' => $hash], - 'passwordUpdate' => (!empty($password)) ? DateTime::now() : null, + 'passwordUpdate' => (! empty($password)) ? DateTime::now() : null, 'registration' => DateTime::now(), 'reset' => false, 'name' => $name, @@ -72,7 +72,7 @@ function createUser(string $hash, mixed $hashOptions, string $userId, ?string $e 'sessions' => null, 'tokens' => null, 'memberships' => null, - 'search' => implode(' ', [$userId, $email, $phone, $name]) + 'search' => implode(' ', [$userId, $email, $phone, $name]), ])); } catch (Duplicate $th) { throw new Exception(Exception::USER_ALREADY_EXISTS); @@ -230,8 +230,8 @@ App::post('/v1/users/sha') ->action(function (string $userId, string $email, string $password, string $passwordVersion, string $name, Response $response, Database $dbForProject, Event $events) { $options = '{}'; - if (!empty($passwordVersion)) { - $options = '{"version":"' . $passwordVersion . '"}'; + if (! empty($passwordVersion)) { + $options = '{"version":"'.$passwordVersion.'"}'; } $user = createUser('sha', $options, $userId, $email, $password, null, $name, $dbForProject, $events); @@ -304,7 +304,7 @@ App::post('/v1/users/scrypt') 'costCpu' => $passwordCpu, 'costMemory' => $passwordMemory, 'costParallel' => $passwordParallel, - 'length' => $passwordLength + 'length' => $passwordLength, ]; $user = createUser('scrypt', \json_encode($options), $userId, $email, $password, null, $name, $dbForProject, $events); @@ -340,7 +340,7 @@ App::post('/v1/users/scrypt-modified') ->inject('dbForProject') ->inject('events') ->action(function (string $userId, string $email, string $password, string $passwordSalt, string $passwordSaltSeparator, string $passwordSignerKey, string $name, Response $response, Database $dbForProject, Event $events) { - $user = createUser('scryptMod', '{"signerKey":"' . $passwordSignerKey . '","saltSeparator":"' . $passwordSaltSeparator . '","salt":"' . $passwordSalt . '"}', $userId, $email, $password, null, $name, $dbForProject, $events); + $user = createUser('scryptMod', '{"signerKey":"'.$passwordSignerKey.'","saltSeparator":"'.$passwordSaltSeparator.'","salt":"'.$passwordSalt.'"}', $userId, $email, $password, null, $name, $dbForProject, $events); $response ->setStatusCode(Response::STATUS_CODE_CREATED) @@ -359,15 +359,14 @@ App::get('/v1/users') ->label('sdk.response.code', Response::STATUS_CODE_OK) ->label('sdk.response.type', Response::CONTENT_TYPE_JSON) ->label('sdk.response.model', Response::MODEL_USER_LIST) - ->param('queries', [], new Users(), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/databases#querying-documents). Maximum of ' . APP_LIMIT_ARRAY_PARAMS_SIZE . ' queries are allowed, each ' . APP_LIMIT_ARRAY_ELEMENT_SIZE . ' characters long. You may filter on the following attributes: ' . implode(', ', Users::ALLOWED_ATTRIBUTES), true) + ->param('queries', [], new Users(), 'Array of query strings generated using the Query class provided by the SDK. [Learn more about queries](https://appwrite.io/docs/databases#querying-documents). Maximum of '.APP_LIMIT_ARRAY_PARAMS_SIZE.' queries are allowed, each '.APP_LIMIT_ARRAY_ELEMENT_SIZE.' characters long. You may filter on the following attributes: '.implode(', ', Users::ALLOWED_ATTRIBUTES), true) ->param('search', '', new Text(256), 'Search term to filter your list results. Max length: 256 chars.', true) ->inject('response') ->inject('dbForProject') ->action(function (array $queries, string $search, Response $response, Database $dbForProject) { - $queries = Query::parseQueries($queries); - if (!empty($search)) { + if (! empty($search)) { $queries[] = Query::search('search', $search); } @@ -410,7 +409,6 @@ App::get('/v1/users/:userId') ->inject('response') ->inject('dbForProject') ->action(function (string $userId, Response $response, Database $dbForProject) { - $user = $dbForProject->getDocument('users', $userId); if ($user->isEmpty()) { @@ -436,7 +434,6 @@ App::get('/v1/users/:userId/prefs') ->inject('response') ->inject('dbForProject') ->action(function (string $userId, Response $response, Database $dbForProject) { - $user = $dbForProject->getDocument('users', $userId); if ($user->isEmpty()) { @@ -465,7 +462,6 @@ App::get('/v1/users/:userId/sessions') ->inject('dbForProject') ->inject('locale') ->action(function (string $userId, Response $response, Database $dbForProject, Locale $locale) { - $user = $dbForProject->getDocument('users', $userId); if ($user->isEmpty()) { @@ -476,8 +472,7 @@ App::get('/v1/users/:userId/sessions') foreach ($sessions as $key => $session) { /** @var Document $session */ - - $countryName = $locale->getText('countries.' . strtolower($session->getAttribute('countryCode')), $locale->getText('locale.country.unknown')); + $countryName = $locale->getText('countries.'.strtolower($session->getAttribute('countryCode')), $locale->getText('locale.country.unknown')); $session->setAttribute('countryName', $countryName); $session->setAttribute('current', false); @@ -506,7 +501,6 @@ App::get('/v1/users/:userId/memberships') ->inject('response') ->inject('dbForProject') ->action(function (string $userId, Response $response, Database $dbForProject) { - $user = $dbForProject->getDocument('users', $userId); if ($user->isEmpty()) { @@ -549,7 +543,6 @@ App::get('/v1/users/:userId/logs') ->inject('locale') ->inject('geodb') ->action(function (string $userId, array $queries, Response $response, Database $dbForProject, Locale $locale, Reader $geodb) { - $user = $dbForProject->getDocument('users', $userId); if ($user->isEmpty()) { @@ -568,7 +561,7 @@ App::get('/v1/users/:userId/logs') $output = []; foreach ($logs as $i => &$log) { - $log['userAgent'] = (!empty($log['userAgent'])) ? $log['userAgent'] : 'UNKNOWN'; + $log['userAgent'] = (! empty($log['userAgent'])) ? $log['userAgent'] : 'UNKNOWN'; $detector = new Detector($log['userAgent']); $detector->skipBotDetection(); // OPTIONAL: If called, bot detection will completely be skipped (bots will be detected as regular devices then) @@ -592,14 +585,14 @@ App::get('/v1/users/:userId/logs') 'clientEngineVersion' => $client['clientEngineVersion'], 'deviceName' => $device['deviceName'], 'deviceBrand' => $device['deviceBrand'], - 'deviceModel' => $device['deviceModel'] + 'deviceModel' => $device['deviceModel'], ]); $record = $geodb->get($log['ip']); if ($record) { - $output[$i]['countryCode'] = $locale->getText('countries.' . strtolower($record['country']['iso_code']), false) ? \strtolower($record['country']['iso_code']) : '--'; - $output[$i]['countryName'] = $locale->getText('countries.' . strtolower($record['country']['iso_code']), $locale->getText('locale.country.unknown')); + $output[$i]['countryCode'] = $locale->getText('countries.'.strtolower($record['country']['iso_code']), false) ? \strtolower($record['country']['iso_code']) : '--'; + $output[$i]['countryName'] = $locale->getText('countries.'.strtolower($record['country']['iso_code']), $locale->getText('locale.country.unknown')); } else { $output[$i]['countryCode'] = '--'; $output[$i]['countryName'] = $locale->getText('locale.country.unknown'); @@ -634,7 +627,6 @@ App::patch('/v1/users/:userId/status') ->inject('dbForProject') ->inject('events') ->action(function (string $userId, bool $status, Response $response, Database $dbForProject, Event $events) { - $user = $dbForProject->getDocument('users', $userId); if ($user->isEmpty()) { @@ -670,7 +662,6 @@ App::patch('/v1/users/:userId/verification') ->inject('dbForProject') ->inject('events') ->action(function (string $userId, bool $emailVerification, Response $response, Database $dbForProject, Event $events) { - $user = $dbForProject->getDocument('users', $userId); if ($user->isEmpty()) { @@ -706,7 +697,6 @@ App::patch('/v1/users/:userId/verification/phone') ->inject('dbForProject') ->inject('events') ->action(function (string $userId, bool $phoneVerification, Response $response, Database $dbForProject, Event $events) { - $user = $dbForProject->getDocument('users', $userId); if ($user->isEmpty()) { @@ -743,7 +733,6 @@ App::patch('/v1/users/:userId/name') ->inject('dbForProject') ->inject('events') ->action(function (string $userId, string $name, Response $response, Database $dbForProject, Event $events) { - $user = $dbForProject->getDocument('users', $userId); if ($user->isEmpty()) { @@ -753,7 +742,6 @@ App::patch('/v1/users/:userId/name') $user ->setAttribute('name', $name) ->setAttribute('search', \implode(' ', [$user->getId(), $user->getAttribute('email', ''), $name, $user->getAttribute('phone', '')])); - ; $user = $dbForProject->updateDocument('users', $user->getId(), $user); @@ -784,7 +772,6 @@ App::patch('/v1/users/:userId/password') ->inject('dbForProject') ->inject('events') ->action(function (string $userId, string $password, Response $response, Database $dbForProject, Event $events) { - $user = $dbForProject->getDocument('users', $userId); if ($user->isEmpty()) { @@ -826,7 +813,6 @@ App::patch('/v1/users/:userId/email') ->inject('dbForProject') ->inject('events') ->action(function (string $userId, string $email, Response $response, Database $dbForProject, Event $events) { - $user = $dbForProject->getDocument('users', $userId); if ($user->isEmpty()) { @@ -872,7 +858,6 @@ App::patch('/v1/users/:userId/phone') ->inject('dbForProject') ->inject('events') ->action(function (string $userId, string $number, Response $response, Database $dbForProject, Event $events) { - $user = $dbForProject->getDocument('users', $userId); if ($user->isEmpty()) { @@ -883,7 +868,6 @@ App::patch('/v1/users/:userId/phone') ->setAttribute('phone', $number) ->setAttribute('phoneVerification', false) ->setAttribute('search', implode(' ', [$user->getId(), $user->getAttribute('name', ''), $user->getAttribute('email', ''), $number])); - ; try { $user = $dbForProject->updateDocument('users', $user->getId(), $user); @@ -918,7 +902,6 @@ App::patch('/v1/users/:userId/verification') ->inject('dbForProject') ->inject('events') ->action(function (string $userId, bool $emailVerification, Response $response, Database $dbForProject, Event $events) { - $user = $dbForProject->getDocument('users', $userId); if ($user->isEmpty()) { @@ -951,7 +934,6 @@ App::patch('/v1/users/:userId/prefs') ->inject('dbForProject') ->inject('events') ->action(function (string $userId, array $prefs, Response $response, Database $dbForProject, Event $events) { - $user = $dbForProject->getDocument('users', $userId); if ($user->isEmpty()) { @@ -986,7 +968,6 @@ App::delete('/v1/users/:userId/sessions/:sessionId') ->inject('dbForProject') ->inject('events') ->action(function (string $userId, string $sessionId, Response $response, Database $dbForProject, Event $events) { - $user = $dbForProject->getDocument('users', $userId); if ($user->isEmpty()) { @@ -1029,7 +1010,6 @@ App::delete('/v1/users/:userId/sessions') ->inject('dbForProject') ->inject('events') ->action(function (string $userId, Response $response, Database $dbForProject, Event $events) { - $user = $dbForProject->getDocument('users', $userId); if ($user->isEmpty()) { @@ -1073,7 +1053,6 @@ App::delete('/v1/users/:userId') ->inject('events') ->inject('deletes') ->action(function (string $userId, Response $response, Database $dbForProject, Event $events, Delete $deletes) { - $user = $dbForProject->getDocument('users', $userId); if ($user->isEmpty()) { @@ -1107,12 +1086,11 @@ App::get('/v1/users/usage') ->label('sdk.response.type', Response::CONTENT_TYPE_JSON) ->label('sdk.response.model', Response::MODEL_USAGE_USERS) ->param('range', '30d', new WhiteList(['24h', '7d', '30d', '90d'], true), 'Date range.', true) - ->param('provider', '', new WhiteList(\array_merge(['email', 'anonymous'], \array_map(fn ($value) => "oauth-" . $value, \array_keys(Config::getParam('providers', [])))), true), 'Provider Name.', true) + ->param('provider', '', new WhiteList(\array_merge(['email', 'anonymous'], \array_map(fn ($value) => 'oauth-'.$value, \array_keys(Config::getParam('providers', [])))), true), 'Provider Name.', true) ->inject('response') ->inject('dbForProject') ->inject('register') ->action(function (string $range, string $provider, Response $response, Database $dbForProject) { - $usage = []; if (App::getEnv('_APP_USAGE_STATS', 'enabled') == 'enabled') { $periods = [ @@ -1194,7 +1172,7 @@ App::get('/v1/users/usage') 'usersDelete' => $stats['users.$all.requests.delete'] ?? [], 'sessionsCreate' => $stats['sessions.$all.requests.create'] ?? [], 'sessionsProviderCreate' => $stats["sessions.$provider.requests.create"] ?? [], - 'sessionsDelete' => $stats['sessions.$all.requests.delete' ?? []] + 'sessionsDelete' => $stats['sessions.$all.requests.delete' ?? []], ]); } diff --git a/app/controllers/general.php b/app/controllers/general.php index 99af4681b8..4db5a14f09 100644 --- a/app/controllers/general.php +++ b/app/controllers/general.php @@ -1,38 +1,38 @@ getHostname(); $domains = Config::getParam('domains', []); - if (!array_key_exists($domain, $domains)) { - $domain = new Domain(!empty($domain) ? $domain : ''); + if (! array_key_exists($domain, $domains)) { + $domain = new Domain(! empty($domain) ? $domain : ''); - if (empty($domain->get()) || !$domain->isKnown() || $domain->isTest()) { + if (empty($domain->get()) || ! $domain->isKnown() || $domain->isTest()) { $domains[$domain->get()] = false; - Console::warning($domain->get() . ' is not a publicly accessible domain. Skipping SSL certificate generation.'); + Console::warning($domain->get().' is not a publicly accessible domain. Skipping SSL certificate generation.'); } elseif (str_starts_with($request->getURI(), '/.well-known/acme-challenge')) { Console::warning('Skipping SSL certificates generation on ACME challenge.'); } else { @@ -95,7 +95,7 @@ App::init() $envDomain = App::getEnv('_APP_DOMAIN', ''); $mainDomain = null; - if (!empty($envDomain) && $envDomain !== 'localhost') { + if (! empty($envDomain) && $envDomain !== 'localhost') { $mainDomain = $envDomain; } else { $domainDocument = $dbForConsole->findOne('domains', [Query::orderAsc('_id')]); @@ -103,13 +103,13 @@ App::init() } if ($mainDomain !== $domain->get()) { - Console::warning($domain->get() . ' is not a main domain. Skipping SSL certificate generation.'); + Console::warning($domain->get().' is not a main domain. Skipping SSL certificate generation.'); } else { $domainDocument = $dbForConsole->findOne('domains', [ - Query::equal('domain', [$domain->get()]) + Query::equal('domain', [$domain->get()]), ]); - if (!$domainDocument) { + if (! $domainDocument) { $domainDocument = new Document([ 'domain' => $domain->get(), 'tld' => $domain->getSuffix(), @@ -120,7 +120,7 @@ App::init() $domainDocument = $dbForConsole->createDocument('domains', $domainDocument); - Console::info('Issuing a TLS certificate for the main domain (' . $domain->get() . ') in a few seconds...'); + Console::info('Issuing a TLS certificate for the main domain ('.$domain->get().') in a few seconds...'); (new Certificate()) ->setDomain($domainDocument) @@ -143,7 +143,7 @@ App::init() throw new AppwriteException(AppwriteException::PROJECT_NOT_FOUND); } - if (!empty($route->getLabel('sdk.auth', [])) && $project->isEmpty() && ($route->getLabel('scope', '') !== 'public')) { + if (! empty($route->getLabel('sdk.auth', [])) && $project->isEmpty() && ($route->getLabel('scope', '') !== 'public')) { throw new AppwriteException(AppwriteException::PROJECT_UNKNOWN); } @@ -158,14 +158,14 @@ App::init() $refDomainOrigin = $origin; } - $refDomain = (!empty($protocol) ? $protocol : $request->getProtocol()) . '://' . $refDomainOrigin . (!empty($port) ? ':' . $port : ''); + $refDomain = (! empty($protocol) ? $protocol : $request->getProtocol()).'://'.$refDomainOrigin.(! empty($port) ? ':'.$port : ''); - $refDomain = (!$route->getLabel('origin', false)) // This route is publicly accessible + $refDomain = (! $route->getLabel('origin', false)) // This route is publicly accessible ? $refDomain - : (!empty($protocol) ? $protocol : $request->getProtocol()) . '://' . $origin . (!empty($port) ? ':' . $port : ''); + : (! empty($protocol) ? $protocol : $request->getProtocol()).'://'.$origin.(! empty($port) ? ':'.$port : ''); $selfDomain = new Domain($request->getHostname()); - $endDomain = new Domain((string)$origin); + $endDomain = new Domain((string) $origin); Config::setParam( 'domainVerification', @@ -175,11 +175,11 @@ App::init() Config::setParam('cookieDomain', ( $request->getHostname() === 'localhost' || - $request->getHostname() === 'localhost:' . $request->getPort() || + $request->getHostname() === 'localhost:'.$request->getPort() || (\filter_var($request->getHostname(), FILTER_VALIDATE_IP) !== false) ) ? null - : '.' . $request->getHostname()); + : '.'.$request->getHostname()); /* * Response format @@ -221,12 +221,12 @@ App::init() throw new AppwriteException(AppwriteException::GENERAL_PROTOCOL_UNSUPPORTED, 'Method unsupported over HTTP.'); } - return $response->redirect('https://' . $request->getHostname() . $request->getURI()); + return $response->redirect('https://'.$request->getHostname().$request->getURI()); } } if ($request->getProtocol() === 'https') { - $response->addHeader('Strict-Transport-Security', 'max-age=' . (60 * 60 * 24 * 126)); // 126 days + $response->addHeader('Strict-Transport-Security', 'max-age='.(60 * 60 * 24 * 126)); // 126 days } $response @@ -236,8 +236,7 @@ App::init() ->addHeader('Access-Control-Allow-Headers', 'Origin, Cookie, Set-Cookie, X-Requested-With, Content-Type, Access-Control-Allow-Origin, Access-Control-Request-Headers, Accept, X-Appwrite-Project, X-Appwrite-Key, X-Appwrite-Locale, X-Appwrite-Mode, X-Appwrite-JWT, X-Appwrite-Response-Format, X-SDK-Version, X-SDK-Name, X-SDK-Language, X-SDK-Platform, X-SDK-GraphQL, X-Appwrite-ID, Content-Range, Range, Cache-Control, Expires, Pragma') ->addHeader('Access-Control-Expose-Headers', 'X-Fallback-Cookies') ->addHeader('Access-Control-Allow-Origin', $refDomain) - ->addHeader('Access-Control-Allow-Credentials', 'true') - ; + ->addHeader('Access-Control-Allow-Credentials', 'true'); /* * Validate Client Domain - Check to avoid CSRF attack @@ -248,7 +247,7 @@ App::init() $originValidator = new Origin(\array_merge($project->getAttribute('platforms', []), $console->getAttribute('platforms', []))); if ( - !$originValidator->isValid($origin) + ! $originValidator->isValid($origin) && \in_array($request->getMethod(), [Request::METHOD_POST, Request::METHOD_PUT, Request::METHOD_PATCH, Request::METHOD_DELETE]) && $route->getLabel('origin', false) !== '*' && empty($request->getHeader('x-appwrite-key', '')) @@ -288,7 +287,7 @@ App::init() $authKey = $request->getHeader('x-appwrite-key', ''); - if (!empty($authKey)) { // API Key authentication + if (! empty($authKey)) { // API Key authentication // Check if given key match project API keys $key = $project->find('secret', $authKey, 'keys'); @@ -300,7 +299,7 @@ App::init() $user = new Document([ '$id' => '', 'status' => true, - 'email' => 'app.' . $project->getId() . '@service.' . $request->getHostname(), + 'email' => 'app.'.$project->getId().'@service.'.$request->getHostname(), 'password' => '', 'name' => $project->getAttribute('name', 'Untitled'), ]); @@ -309,8 +308,8 @@ App::init() $scopes = \array_merge($roles[$role]['scopes'], $key->getAttribute('scopes', [])); $expire = $key->getAttribute('expire'); - if (!empty($expire) && $expire < DateTime::formatTz(DateTime::now())) { - throw new AppwriteException(AppwriteException:: PROJECT_KEY_EXPIRED); + if (! empty($expire) && $expire < DateTime::formatTz(DateTime::now())) { + throw new AppwriteException(AppwriteException::PROJECT_KEY_EXPIRED); } Authorization::setRole(Auth::USER_ROLE_APPS); @@ -327,7 +326,7 @@ App::init() $sdk = $request->getHeader('x-sdk-name', 'UNKNOWN'); if ($sdkValidator->isValid($sdk)) { $sdks = $key->getAttribute('sdks', []); - if (!in_array($sdk, $sdks)) { + if (! in_array($sdk, $sdks)) { array_push($sdks, $sdk); $key->setAttribute('sdks', $sdks); @@ -347,22 +346,22 @@ App::init() } $service = $route->getLabel('sdk.namespace', ''); - if (!empty($service)) { + if (! empty($service)) { if ( array_key_exists($service, $project->getAttribute('services', [])) - && !$project->getAttribute('services', [])[$service] - && !(Auth::isPrivilegedUser(Authorization::getRoles()) || Auth::isAppUser(Authorization::getRoles())) + && ! $project->getAttribute('services', [])[$service] + && ! (Auth::isPrivilegedUser(Authorization::getRoles()) || Auth::isAppUser(Authorization::getRoles())) ) { throw new AppwriteException(AppwriteException::GENERAL_SERVICE_DISABLED); } } - if (!\in_array($scope, $scopes)) { + if (! \in_array($scope, $scopes)) { if ($project->isEmpty()) { // Check if permission is denied because project is missing throw new AppwriteException(AppwriteException::PROJECT_NOT_FOUND); } - throw new AppwriteException(AppwriteException::GENERAL_UNAUTHORIZED_SCOPE, $user->getAttribute('email', 'User') . ' (role: ' . \strtolower($roles[$role]['label']) . ') missing scope (' . $scope . ')'); + throw new AppwriteException(AppwriteException::GENERAL_UNAUTHORIZED_SCOPE, $user->getAttribute('email', 'User').' (role: '.\strtolower($roles[$role]['label']).') missing scope ('.$scope.')'); } if (false === $user->getAttribute('status')) { // Account is blocked @@ -378,7 +377,6 @@ App::options() ->inject('request') ->inject('response') ->action(function (Request $request, Response $response) { - $origin = $request->getOrigin(); $response @@ -400,7 +398,6 @@ App::error() ->inject('logger') ->inject('loggerBreadcrumbs') ->action(function (Throwable $error, App $utopia, Request $request, Response $response, Document $project, ?Logger $logger, array $loggerBreadcrumbs) { - $version = App::getEnv('_APP_VERSION', 'UNKNOWN'); $route = $utopia->match($request); @@ -415,11 +412,11 @@ App::error() $log = new Utopia\Logger\Log(); - if (isset($user) && !$user->isEmpty()) { + if (isset($user) && ! $user->isEmpty()) { $log->setUser(new User($user->getId())); } - $log->setNamespace("http"); + $log->setNamespace('http'); $log->setServer(\gethostname()); $log->setVersion($version); $log->setType(Log::TYPE_ERROR); @@ -431,7 +428,7 @@ App::error() $log->addTag('code', $error->getCode()); $log->addTag('projectId', $project->getId()); $log->addTag('hostname', $request->getHostname()); - $log->addTag('locale', (string)$request->getParam('locale', $request->getHeader('x-appwrite-locale', ''))); + $log->addTag('locale', (string) $request->getParam('locale', $request->getHeader('x-appwrite-locale', ''))); $log->addExtra('file', $error->getFile()); $log->addExtra('line', $error->getLine()); @@ -439,7 +436,7 @@ App::error() $log->addExtra('detailedTrace', $error->getTrace()); $log->addExtra('roles', Authorization::$roles); - $action = $route->getLabel("sdk.namespace", "UNKNOWN_NAMESPACE") . '.' . $route->getLabel("sdk.method", "UNKNOWN_METHOD"); + $action = $route->getLabel('sdk.namespace', 'UNKNOWN_NAMESPACE').'.'.$route->getLabel('sdk.method', 'UNKNOWN_METHOD'); $log->setAction($action); $isProduction = App::getEnv('_APP_ENV', 'development') === 'production'; @@ -450,7 +447,7 @@ App::error() } $responseCode = $logger->addLog($log); - Console::info('Log pushed with status code: ' . $responseCode); + Console::info('Log pushed with status code: '.$responseCode); } } @@ -461,17 +458,17 @@ App::error() $trace = $error->getTrace(); if (php_sapi_name() === 'cli') { - Console::error('[Error] Timestamp: ' . date('c', time())); + Console::error('[Error] Timestamp: '.date('c', time())); if ($route) { - Console::error('[Error] Method: ' . $route->getMethod()); - Console::error('[Error] URL: ' . $route->getPath()); + Console::error('[Error] Method: '.$route->getMethod()); + Console::error('[Error] URL: '.$route->getPath()); } - Console::error('[Error] Type: ' . get_class($error)); - Console::error('[Error] Message: ' . $message); - Console::error('[Error] File: ' . $file); - Console::error('[Error] Line: ' . $line); + Console::error('[Error] Type: '.get_class($error)); + Console::error('[Error] Message: '.$message); + Console::error('[Error] File: '.$file); + Console::error('[Error] Line: '.$line); } /** Handle Utopia Errors */ @@ -488,7 +485,7 @@ App::error() } /** Wrap all exceptions inside Appwrite\Extend\Exception */ - if (!($error instanceof AppwriteException)) { + if (! ($error instanceof AppwriteException)) { $error = new AppwriteException(AppwriteException::GENERAL_UNKNOWN, $message, $code, $error); } @@ -533,8 +530,7 @@ App::error() ->addHeader('Cache-Control', 'no-cache, no-store, must-revalidate') ->addHeader('Expires', '0') ->addHeader('Pragma', 'no-cache') - ->setStatusCode($code) - ; + ->setStatusCode($code); $template = ($route) ? $route->getLabel('error', null) : null; @@ -542,14 +538,13 @@ App::error() $layout = new View($template); $layout - ->setParam('title', $project->getAttribute('name') . ' - Error') + ->setParam('title', $project->getAttribute('name').' - Error') ->setParam('development', App::isDevelopment()) ->setParam('projectName', $project->getAttribute('name')) ->setParam('projectURL', $project->getAttribute('url')) ->setParam('message', $error->getMessage()) ->setParam('code', $code) - ->setParam('trace', $trace) - ; + ->setParam('trace', $trace); $response->html($layout->render()); } @@ -566,7 +561,7 @@ App::get('/robots.txt') ->label('docs', false) ->inject('response') ->action(function (Response $response) { - $template = new View(__DIR__ . '/../views/general/robots.phtml'); + $template = new View(__DIR__.'/../views/general/robots.phtml'); $response->text($template->render(false)); }); @@ -576,7 +571,7 @@ App::get('/humans.txt') ->label('docs', false) ->inject('response') ->action(function (Response $response) { - $template = new View(__DIR__ . '/../views/general/humans.phtml'); + $template = new View(__DIR__.'/../views/general/humans.phtml'); $response->text($template->render(false)); }); @@ -595,42 +590,42 @@ App::get('/.well-known/acme-challenge') ...Text::ALPHABET_LOWER, ...Text::ALPHABET_UPPER, '-', - '_' + '_', ]); - if (!$validator->isValid($token) || \count($uriChunks) !== 4) { + if (! $validator->isValid($token) || \count($uriChunks) !== 4) { throw new AppwriteException(AppwriteException::GENERAL_ARGUMENT_INVALID, 'Invalid challenge token.'); } $base = \realpath(APP_STORAGE_CERTIFICATES); - $absolute = \realpath($base . '/.well-known/acme-challenge/' . $token); + $absolute = \realpath($base.'/.well-known/acme-challenge/'.$token); - if (!$base) { + if (! $base) { throw new AppwriteException(AppwriteException::GENERAL_SERVER_ERROR, 'Storage error'); } - if (!$absolute) { + if (! $absolute) { throw new AppwriteException(AppwriteException::GENERAL_ROUTE_NOT_FOUND, 'Unknown path'); } - if (!\substr($absolute, 0, \strlen($base)) === $base) { + if (! \substr($absolute, 0, \strlen($base)) === $base) { throw new AppwriteException(AppwriteException::GENERAL_UNAUTHORIZED_SCOPE, 'Invalid path'); } - if (!\file_exists($absolute)) { + if (! \file_exists($absolute)) { throw new AppwriteException(AppwriteException::GENERAL_ROUTE_NOT_FOUND, 'Unknown path'); } $content = @\file_get_contents($absolute); - if (!$content) { + if (! $content) { throw new AppwriteException(AppwriteException::GENERAL_SERVER_ERROR, 'Failed to get contents'); } $response->text($content); }); -include_once __DIR__ . '/shared/api.php'; +include_once __DIR__.'/shared/api.php'; foreach (Config::getParam('services', []) as $service) { include_once $service['controller']; diff --git a/app/controllers/mock.php b/app/controllers/mock.php index 3e1d63d6ee..0db4366dbb 100644 --- a/app/controllers/mock.php +++ b/app/controllers/mock.php @@ -3,18 +3,17 @@ global $utopia, $request, $response; use Appwrite\Extend\Exception; -use Utopia\Database\Document; -use Utopia\Validator\Host; use Appwrite\Utopia\Request; use Appwrite\Utopia\Response; -use Appwrite\Utopia\Response\Model; use Utopia\App; +use Utopia\Database\Document; +use Utopia\Database\Helpers\ID; +use Utopia\Storage\Validator\File; use Utopia\Validator\ArrayList; +use Utopia\Validator\Host; use Utopia\Validator\Integer; use Utopia\Validator\Text; -use Utopia\Storage\Validator\File; use Utopia\Validator\WhiteList; -use Utopia\Database\Helpers\ID; App::get('/v1/mock/tests/foo') ->desc('Get Foo') @@ -220,9 +219,9 @@ App::get('/v1/mock/tests/general/headers') 'x-sdk-version' => $request->getHeader('x-sdk-version'), ]; $res = array_map(function ($key, $value) { - return $key . ': ' . $value; + return $key.': '.$value; }, array_keys($res), $res); - $res = implode("; ", $res); + $res = implode('; ', $res); $response->dynamic(new Document(['result' => $res]), Response::MODEL_MOCK); }); @@ -241,14 +240,12 @@ App::get('/v1/mock/tests/general/download') ->label('sdk.mock', true) ->inject('response') ->action(function (Response $response) { - $response ->setContentType('text/plain') ->addHeader('Content-Disposition', 'attachment; filename="test.txt"') - ->addHeader('Expires', \date('D, d M Y H:i:s', \time() + (60 * 60 * 24 * 45)) . ' GMT') // 45 days cache + ->addHeader('Expires', \date('D, d M Y H:i:s', \time() + (60 * 60 * 24 * 45)).' GMT') // 45 days cache ->addHeader('X-Peak', \memory_get_peak_usage()) - ->send("GET:/v1/mock/tests/general/download:passed") - ; + ->send('GET:/v1/mock/tests/general/download:passed'); }); App::post('/v1/mock/tests/general/upload') @@ -271,14 +268,13 @@ App::post('/v1/mock/tests/general/upload') ->inject('request') ->inject('response') ->action(function (string $x, int $y, array $z, mixed $file, Request $request, Response $response) { - $file = $request->getFiles('file'); $contentRange = $request->getHeader('content-range'); $chunkSize = 5 * 1024 * 1024; // 5MB - if (!empty($contentRange)) { + if (! empty($contentRange)) { $start = $request->getContentRangeStart(); $end = $request->getContentRangeEnd(); $size = $request->getContentRangeSize(); @@ -293,7 +289,7 @@ App::post('/v1/mock/tests/general/upload') throw new Exception(Exception::GENERAL_MOCK, 'Invalid content-range header'); } - if ($start === 0 && !empty($id)) { + if ($start === 0 && ! empty($id)) { throw new Exception(Exception::GENERAL_MOCK, 'First chunked request cannot have id header'); } @@ -317,7 +313,7 @@ App::post('/v1/mock/tests/general/upload') $response->json([ '$id' => ID::custom('newfileid'), 'chunksTotal' => $file['size'] / $chunkSize, - 'chunksUploaded' => $start / $chunkSize + 'chunksUploaded' => $start / $chunkSize, ]); } } else { @@ -330,7 +326,7 @@ App::post('/v1/mock/tests/general/upload') } if ($file['size'] !== 38756) { - throw new Exception(Exception::GENERAL_MOCK, 'Wrong file size'); + throw new Exception(Exception::GENERAL_MOCK, 'Wrong file size'); } if (\md5(\file_get_contents($file['tmp_name'])) !== 'd80e7e6999a3eb2ae0d631a96fe135a4') { @@ -353,7 +349,6 @@ App::get('/v1/mock/tests/general/redirect') ->label('sdk.mock', true) ->inject('response') ->action(function (Response $response) { - $response->redirect('/v1/mock/tests/general/redirect/done'); }); @@ -387,7 +382,6 @@ App::get('/v1/mock/tests/general/set-cookie') ->inject('response') ->inject('request') ->action(function (Response $response, Request $request) { - $response->addCookie('cookieName', 'cookieValue', \time() + 31536000, '/', $request->getHostname(), true, true); }); @@ -405,7 +399,6 @@ App::get('/v1/mock/tests/general/get-cookie') ->label('sdk.mock', true) ->inject('request') ->action(function (Request $request) { - if ($request->getCookie('cookieName', '') !== 'cookieValue') { throw new Exception(Exception::GENERAL_MOCK, 'Missing cookie value'); } @@ -424,7 +417,6 @@ App::get('/v1/mock/tests/general/empty') ->label('sdk.mock', true) ->inject('response') ->action(function (Response $response) { - $response->noContent(); }); @@ -450,9 +442,9 @@ App::get('/v1/mock/tests/general/headers') 'x-sdk-version' => $request->getHeader('x-sdk-version'), ]; $res = array_map(function ($key, $value) { - return $key . ': ' . $value; + return $key.': '.$value; }, array_keys($res), $res); - $res = implode("; ", $res); + $res = implode('; ', $res); $response->dynamic(new Document(['result' => $res]), Response::MODEL_MOCK); }); @@ -503,11 +495,9 @@ App::get('/v1/mock/tests/general/502-error') ->label('sdk.mock', true) ->inject('response') ->action(function (Response $response) { - $response ->setStatusCode(502) - ->text('This is a text error') - ; + ->text('This is a text error'); }); App::get('/v1/mock/tests/general/oauth2') @@ -522,8 +512,7 @@ App::get('/v1/mock/tests/general/oauth2') ->param('state', '', new Text(1024), 'OAuth2 state.') ->inject('response') ->action(function (string $client_id, string $redirectURI, string $scope, string $state, Response $response) { - - $response->redirect($redirectURI . '?' . \http_build_query(['code' => 'abcdef', 'state' => $state])); + $response->redirect($redirectURI.'?'.\http_build_query(['code' => 'abcdef', 'state' => $state])); }); App::get('/v1/mock/tests/general/oauth2/token') @@ -540,7 +529,6 @@ App::get('/v1/mock/tests/general/oauth2/token') ->param('refresh_token', '', new Text(100), 'OAuth2 refresh token.', true) ->inject('response') ->action(function (string $client_id, string $client_secret, string $grantType, string $redirectURI, string $code, string $refreshToken, Response $response) { - if ($client_id != '1') { throw new Exception(Exception::GENERAL_MOCK, 'Invalid client ID'); } @@ -552,7 +540,7 @@ App::get('/v1/mock/tests/general/oauth2/token') $responseJson = [ 'access_token' => '123456', 'refresh_token' => 'tuvwxyz', - 'expires_in' => 14400 + 'expires_in' => 14400, ]; if ($grantType === 'authorization_code') { @@ -580,7 +568,6 @@ App::get('/v1/mock/tests/general/oauth2/user') ->param('token', '', new Text(100), 'OAuth2 Access Token.') ->inject('response') ->action(function (string $token, Response $response) { - if ($token != '123456') { throw new Exception(Exception::GENERAL_MOCK, 'Invalid token'); } @@ -599,7 +586,6 @@ App::get('/v1/mock/tests/general/oauth2/success') ->label('docs', false) ->inject('response') ->action(function (Response $response) { - $response->json([ 'result' => 'success', ]); @@ -612,7 +598,6 @@ App::get('/v1/mock/tests/general/oauth2/failure') ->label('docs', false) ->inject('response') ->action(function (Response $response) { - $response ->setStatusCode(Response::STATUS_CODE_BAD_REQUEST) ->json([ @@ -626,23 +611,22 @@ App::shutdown() ->inject('response') ->inject('request') ->action(function (App $utopia, Response $response, Request $request) { - $result = []; - $route = $utopia->match($request); - $path = APP_STORAGE_CACHE . '/tests.json'; - $tests = (\file_exists($path)) ? \json_decode(\file_get_contents($path), true) : []; + $route = $utopia->match($request); + $path = APP_STORAGE_CACHE.'/tests.json'; + $tests = (\file_exists($path)) ? \json_decode(\file_get_contents($path), true) : []; - if (!\is_array($tests)) { + if (! \is_array($tests)) { throw new Exception(Exception::GENERAL_MOCK, 'Failed to read results', 500); } - $result[$route->getMethod() . ':' . $route->getPath()] = true; + $result[$route->getMethod().':'.$route->getPath()] = true; $tests = \array_merge($tests, $result); - if (!\file_put_contents($path, \json_encode($tests), LOCK_EX)) { + if (! \file_put_contents($path, \json_encode($tests), LOCK_EX)) { throw new Exception(Exception::GENERAL_MOCK, 'Failed to save results', 500); } - $response->dynamic(new Document(['result' => $route->getMethod() . ':' . $route->getPath() . ':passed']), Response::MODEL_MOCK); + $response->dynamic(new Document(['result' => $route->getMethod().':'.$route->getPath().':passed']), Response::MODEL_MOCK); }); diff --git a/app/controllers/shared/api.php b/app/controllers/shared/api.php index 5655874c65..e5ff47a419 100644 --- a/app/controllers/shared/api.php +++ b/app/controllers/shared/api.php @@ -5,15 +5,14 @@ use Appwrite\Event\Audit; use Appwrite\Event\Database as EventDatabase; use Appwrite\Event\Delete; use Appwrite\Event\Event; -use Appwrite\Event\Mail; use Appwrite\Extend\Exception; use Appwrite\Messaging\Adapter\Realtime; use Appwrite\Usage\Stats; -use Appwrite\Utopia\Response; use Appwrite\Utopia\Request; -use Utopia\App; +use Appwrite\Utopia\Response; use Utopia\Abuse\Abuse; use Utopia\Abuse\Adapters\TimeLimit; +use Utopia\App; use Utopia\Cache\Adapter\Filesystem; use Utopia\Cache\Cache; use Utopia\CLI\Console; @@ -36,7 +35,7 @@ $parseLabel = function (string $label, array $responsePayload, array $requestPar $replace = $parts[1] ?? ''; $params = match ($namespace) { - 'user' => (array)$user, + 'user' => (array) $user, 'request' => $requestParams, default => $responsePayload, }; @@ -45,6 +44,7 @@ $parseLabel = function (string $label, array $responsePayload, array $requestPar $label = \str_replace($find, $params[$replace], $label); } } + return $label; }; @@ -104,7 +104,6 @@ App::init() ->inject('dbForProject') ->inject('mode') ->action(function (App $utopia, Request $request, Response $response, Document $project, Document $user, Event $events, Audit $audits, Stats $usage, Delete $deletes, EventDatabase $database, Database $dbForProject, string $mode) use ($databaseListener) { - $route = $utopia->match($request); if ($project->isEmpty() && $route->getLabel('abuse-limit', 0) > 0) { // Abuse limit requires an active project scope @@ -117,7 +116,7 @@ App::init() $abuseKeyLabel = $route->getLabel('abuse-key', 'url:{url},ip:{ip}'); $timeLimitArray = []; - $abuseKeyLabel = (!is_array($abuseKeyLabel)) ? [$abuseKeyLabel] : $abuseKeyLabel; + $abuseKeyLabel = (! is_array($abuseKeyLabel)) ? [$abuseKeyLabel] : $abuseKeyLabel; foreach ($abuseKeyLabel as $abuseKey) { $timeLimit = new TimeLimit($abuseKey, $route->getLabel('abuse-limit', 0), $route->getLabel('abuse-time', 3600), $dbForProject); @@ -125,7 +124,7 @@ App::init() ->setParam('{userId}', $user->getId()) ->setParam('{userAgent}', $request->getUserAgent('')) ->setParam('{ip}', $request->getIP()) - ->setParam('{url}', $request->getHostname() . $route->getPath()) + ->setParam('{url}', $request->getHostname().$route->getPath()) ->setParam('{method}', $request->getMethod()); $timeLimitArray[] = $timeLimit; } @@ -138,8 +137,8 @@ App::init() foreach ($timeLimitArray as $timeLimit) { foreach ($request->getParams() as $key => $value) { // Set request params as potential abuse keys - if (!empty($value)) { - $timeLimit->setParam('{param-' . $key . '}', (\is_array($value)) ? \json_encode($value) : $value); + if (! empty($value)) { + $timeLimit->setParam('{param-'.$key.'}', (\is_array($value)) ? \json_encode($value) : $value); } } @@ -153,25 +152,24 @@ App::init() $response ->addHeader('X-RateLimit-Limit', $limit) ->addHeader('X-RateLimit-Remaining', $remaining) - ->addHeader('X-RateLimit-Reset', $time) - ; + ->addHeader('X-RateLimit-Reset', $time); } $enabled = App::getEnv('_APP_OPTIONS_ABUSE', 'enabled') !== 'disabled'; if ( $enabled // Abuse is enabled - && !$isAppUser // User is not API key - && !$isPrivilegedUser // User is not an admin + && ! $isAppUser // User is not API key + && ! $isPrivilegedUser // User is not an admin && $abuse->check() // Route is rate-limited ) { throw new Exception(Exception::GENERAL_RATE_LIMIT_EXCEEDED); } } - /* - * Background Jobs - */ + /* + * Background Jobs + */ $events ->setEvent($route->getLabel('event', '')) ->setProject($project) @@ -203,14 +201,14 @@ App::init() $useCache = $route->getLabel('cache', false); if ($useCache) { - $key = md5($request->getURI() . implode('*', $request->getParams())) . '*' . APP_CACHE_BUSTER; + $key = md5($request->getURI().implode('*', $request->getParams())).'*'.APP_CACHE_BUSTER; $cache = new Cache( - new Filesystem(APP_STORAGE_CACHE . DIRECTORY_SEPARATOR . 'app-' . $project->getId()) + new Filesystem(APP_STORAGE_CACHE.DIRECTORY_SEPARATOR.'app-'.$project->getId()) ); $timestamp = 60 * 60 * 24 * 30; $data = $cache->load($key, $timestamp); - if (!empty($data)) { + if (! empty($data)) { $data = json_decode($data, true); $parts = explode('/', $data['resourceType']); $type = $parts[0] ?? null; @@ -220,24 +218,24 @@ App::init() $bucket = Authorization::skip(fn () => $dbForProject->getDocument('buckets', $bucketId)); - if ($bucket->isEmpty() || (!$bucket->getAttribute('enabled') && $mode !== APP_MODE_ADMIN)) { + if ($bucket->isEmpty() || (! $bucket->getAttribute('enabled') && $mode !== APP_MODE_ADMIN)) { throw new Exception(Exception::STORAGE_BUCKET_NOT_FOUND); } $fileSecurity = $bucket->getAttribute('fileSecurity', false); $validator = new Authorization(Database::PERMISSION_READ); $valid = $validator->isValid($bucket->getRead()); - if (!$fileSecurity && !$valid) { + if (! $fileSecurity && ! $valid) { throw new Exception(Exception::USER_UNAUTHORIZED); } $parts = explode('/', $data['resource']); $fileId = $parts[1] ?? null; - if ($fileSecurity && !$valid) { - $file = $dbForProject->getDocument('bucket_' . $bucket->getInternalId(), $fileId); + if ($fileSecurity && ! $valid) { + $file = $dbForProject->getDocument('bucket_'.$bucket->getInternalId(), $fileId); } else { - $file = Authorization::skip(fn() => $dbForProject->getDocument('bucket_' . $bucket->getInternalId(), $fileId)); + $file = Authorization::skip(fn () => $dbForProject->getDocument('bucket_'.$bucket->getInternalId(), $fileId)); } if ($file->isEmpty()) { @@ -246,11 +244,10 @@ App::init() } $response - ->addHeader('Expires', \date('D, d M Y H:i:s', \time() + $timestamp) . ' GMT') + ->addHeader('Expires', \date('D, d M Y H:i:s', \time() + $timestamp).' GMT') ->addHeader('X-Appwrite-Cache', 'hit') ->setContentType($data['contentType']) - ->send(base64_decode($data['payload'])) - ; + ->send(base64_decode($data['payload'])); $route->setIsActive(false); } else { @@ -265,7 +262,6 @@ App::init() ->inject('request') ->inject('project') ->action(function (App $utopia, Request $request, Document $project) { - $route = $utopia->match($request); $isPrivilegedUser = Auth::isPrivilegedUser(Authorization::getRoles()); @@ -366,10 +362,9 @@ App::shutdown() ->inject('mode') ->inject('dbForProject') ->action(function (App $utopia, Request $request, Response $response, Document $project, Event $events, Audit $audits, Stats $usage, Delete $deletes, EventDatabase $database, string $mode, Database $dbForProject) use ($parseLabel) { - $responsePayload = $response->getPayload(); - if (!empty($events->getEvent())) { + if (! empty($events->getEvent())) { if (empty($events->getPayload())) { $events->setPayload($responsePayload); } @@ -418,7 +413,7 @@ App::shutdown() roles: $target['roles'], options: [ 'permissionsChanged' => $target['permissionsChanged'], - 'userId' => $events->getParam('userId') + 'userId' => $events->getParam('userId'), ] ); } @@ -432,27 +427,27 @@ App::shutdown() * Audit labels */ $pattern = $route->getLabel('audits.resource', null); - if (!empty($pattern)) { + if (! empty($pattern)) { $resource = $parseLabel($pattern, $responsePayload, $requestParams, $user); - if (!empty($resource) && $resource !== $pattern) { + if (! empty($resource) && $resource !== $pattern) { $audits->setResource($resource); } } $pattern = $route->getLabel('audits.userId', null); - if (!empty($pattern)) { + if (! empty($pattern)) { $userId = $parseLabel($pattern, $responsePayload, $requestParams, $user); $user = $dbForProject->getDocument('users', $userId); $audits->setUser($user); } - if (!empty($audits->getResource()) && !empty($audits->getUser()->getId())) { + if (! empty($audits->getResource()) && ! empty($audits->getUser()->getId())) { /** * audits.payload is switched to default true * in order to auto audit payload for all endpoints */ $pattern = $route->getLabel('audits.payload', true); - if (!empty($pattern)) { + if (! empty($pattern)) { $audits->setPayload($responsePayload); } @@ -462,11 +457,11 @@ App::shutdown() $audits->trigger(); } - if (!empty($deletes->getType())) { + if (! empty($deletes->getType())) { $deletes->trigger(); } - if (!empty($database->getType())) { + if (! empty($database->getType())) { $database->trigger(); } @@ -478,35 +473,35 @@ App::shutdown() $resource = $resourceType = null; $data = $response->getPayload(); - if (!empty($data['payload'])) { + if (! empty($data['payload'])) { $pattern = $route->getLabel('cache.resource', null); - if (!empty($pattern)) { + if (! empty($pattern)) { $resource = $parseLabel($pattern, $responsePayload, $requestParams, $user); } $pattern = $route->getLabel('cache.resourceType', null); - if (!empty($pattern)) { + if (! empty($pattern)) { $resourceType = $parseLabel($pattern, $responsePayload, $requestParams, $user); } - $key = md5($request->getURI() . implode('*', $request->getParams())) . '*' . APP_CACHE_BUSTER; + $key = md5($request->getURI().implode('*', $request->getParams())).'*'.APP_CACHE_BUSTER; $data = json_encode([ - 'resourceType' => $resourceType, - 'resource' => $resource, - 'contentType' => $response->getContentType(), - 'payload' => base64_encode($data['payload']), - ]) ; + 'resourceType' => $resourceType, + 'resource' => $resource, + 'contentType' => $response->getContentType(), + 'payload' => base64_encode($data['payload']), + ]); $signature = md5($data); - $cacheLog = $dbForProject->getDocument('cache', $key); + $cacheLog = $dbForProject->getDocument('cache', $key); $accessedAt = $cacheLog->getAttribute('accessedAt', ''); $now = DateTime::now(); if ($cacheLog->isEmpty()) { Authorization::skip(fn () => $dbForProject->createDocument('cache', new Document([ - '$id' => $key, - 'resource' => $resource, - 'accessedAt' => $now, - 'signature' => $signature, + '$id' => $key, + 'resource' => $resource, + 'accessedAt' => $now, + 'signature' => $signature, ]))); } elseif (DateTime::formatTz(DateTime::addSeconds(new \DateTime(), -APP_CACHE_UPDATE)) > $accessedAt) { $cacheLog->setAttribute('accessedAt', $now); @@ -515,7 +510,7 @@ App::shutdown() if ($signature !== $cacheLog->getAttribute('signature')) { $cache = new Cache( - new Filesystem(APP_STORAGE_CACHE . DIRECTORY_SEPARATOR . 'app-' . $project->getId()) + new Filesystem(APP_STORAGE_CACHE.DIRECTORY_SEPARATOR.'app-'.$project->getId()) ); $cache->save($key, $data); } @@ -525,12 +520,12 @@ App::shutdown() if ( App::getEnv('_APP_USAGE_STATS', 'enabled') == 'enabled' && $project->getId() - && !empty($route->getLabel('sdk.namespace', null)) + && ! empty($route->getLabel('sdk.namespace', null)) ) { // Don't calculate console usage on admin mode $metric = $route->getLabel('usage.metric', ''); $usageParams = $route->getLabel('usage.params', []); - if (!empty($metric)) { + if (! empty($metric)) { $usage->setParam($metric, 1); foreach ($usageParams as $param) { $param = $parseLabel($param, $responsePayload, $requestParams, $user); @@ -544,7 +539,7 @@ App::shutdown() $fileSize = 0; $file = $request->getFiles('file'); - if (!empty($file)) { + if (! empty($file)) { $fileSize = (\is_array($file['size']) && isset($file['size'][0])) ? $file['size'][0] : $file['size']; } diff --git a/app/controllers/web/console.php b/app/controllers/web/console.php index 8115f09285..52f43539fd 100644 --- a/app/controllers/web/console.php +++ b/app/controllers/web/console.php @@ -14,6 +14,6 @@ App::get('/console') ->label('scope', 'home') ->inject('response') ->action(function (Response $response) { - $fallback = file_get_contents(__DIR__ . '/../../../console/index.html'); + $fallback = file_get_contents(__DIR__.'/../../../console/index.html'); $response->html($fallback); }); diff --git a/app/controllers/web/home.php b/app/controllers/web/home.php index da1307e5ea..920e5e5268 100644 --- a/app/controllers/web/home.php +++ b/app/controllers/web/home.php @@ -24,14 +24,14 @@ App::get('/versions') continue; } - if (isset($language['enabled']) && !$language['enabled']) { + if (isset($language['enabled']) && ! $language['enabled']) { continue; } $platformKey = $platform['key'] ?? ''; $languageKey = $language['key'] ?? ''; $version = $language['version'] ?? ''; - $versions[$platformKey . '-' . $languageKey] = $version; + $versions[$platformKey.'-'.$languageKey] = $version; } } diff --git a/app/executor.php b/app/executor.php index 0a0116047c..887c4fa5ef 100644 --- a/app/executor.php +++ b/app/executor.php @@ -1,6 +1,6 @@ column('id', Swoole\Table::TYPE_STRING, 256); $activeRuntimes->column('created', Swoole\Table::TYPE_INT, 8); @@ -58,10 +57,10 @@ $orchestrationPool = new ConnectionPool(function () { $dockerUser = App::getEnv('DOCKERHUB_PULL_USERNAME', null); $dockerPass = App::getEnv('DOCKERHUB_PULL_PASSWORD', null); $orchestration = new Orchestration(new DockerCLI($dockerUser, $dockerPass)); + return $orchestration; }, 10); - /** * Create logger instance */ @@ -69,8 +68,8 @@ $providerName = App::getEnv('_APP_LOGGING_PROVIDER', ''); $providerConfig = App::getEnv('_APP_LOGGING_CONFIG', ''); $logger = null; -if (!empty($providerName) && !empty($providerConfig) && Logger::hasProvider($providerName)) { - $classname = '\\Utopia\\Logger\\Adapter\\' . \ucfirst($providerName); +if (! empty($providerName) && ! empty($providerConfig) && Logger::hasProvider($providerName)) { + $classname = '\\Utopia\\Logger\\Adapter\\'.\ucfirst($providerName); $adapter = new $classname($providerConfig); $logger = new Logger($adapter); } @@ -83,7 +82,7 @@ function logError(Throwable $error, string $action, Utopia\Route $route = null) $version = App::getEnv('_APP_VERSION', 'UNKNOWN'); $log = new Log(); - $log->setNamespace("executor"); + $log->setNamespace('executor'); $log->setServer(\gethostname()); $log->setVersion($version); $log->setType(Log::TYPE_ERROR); @@ -108,13 +107,13 @@ function logError(Throwable $error, string $action, Utopia\Route $route = null) $log->setEnvironment($isProduction ? Log::ENVIRONMENT_PRODUCTION : Log::ENVIRONMENT_STAGING); $responseCode = $logger->addLog($log); - Console::info('Executor log pushed with status code: ' . $responseCode); + Console::info('Executor log pushed with status code: '.$responseCode); } - Console::error('[Error] Type: ' . get_class($error)); - Console::error('[Error] Message: ' . $error->getMessage()); - Console::error('[Error] File: ' . $error->getFile()); - Console::error('[Error] Line: ' . $error->getLine()); + Console::error('[Error] Type: '.get_class($error)); + Console::error('[Error] Message: '.$error->getMessage()); + Console::error('[Error] File: '.$error->getFile()); + Console::error('[Error] Line: '.$error->getLine()); } function getStorageDevice($root): Device @@ -129,6 +128,7 @@ function getStorageDevice($root): Device $s3Region = App::getEnv('_APP_STORAGE_S3_REGION', ''); $s3Bucket = App::getEnv('_APP_STORAGE_S3_BUCKET', ''); $s3Acl = 'private'; + return new S3($root, $s3AccessKey, $s3SecretKey, $s3Bucket, $s3Region, $s3Acl); case Storage::DEVICE_DO_SPACES: $doSpacesAccessKey = App::getEnv('_APP_STORAGE_DO_SPACES_ACCESS_KEY', ''); @@ -136,6 +136,7 @@ function getStorageDevice($root): Device $doSpacesRegion = App::getEnv('_APP_STORAGE_DO_SPACES_REGION', ''); $doSpacesBucket = App::getEnv('_APP_STORAGE_DO_SPACES_BUCKET', ''); $doSpacesAcl = 'private'; + return new DOSpaces($root, $doSpacesAccessKey, $doSpacesSecretKey, $doSpacesBucket, $doSpacesRegion, $doSpacesAcl); case Storage::DEVICE_BACKBLAZE: $backblazeAccessKey = App::getEnv('_APP_STORAGE_BACKBLAZE_ACCESS_KEY', ''); @@ -143,6 +144,7 @@ function getStorageDevice($root): Device $backblazeRegion = App::getEnv('_APP_STORAGE_BACKBLAZE_REGION', ''); $backblazeBucket = App::getEnv('_APP_STORAGE_BACKBLAZE_BUCKET', ''); $backblazeAcl = 'private'; + return new Backblaze($root, $backblazeAccessKey, $backblazeSecretKey, $backblazeBucket, $backblazeRegion, $backblazeAcl); case Storage::DEVICE_LINODE: $linodeAccessKey = App::getEnv('_APP_STORAGE_LINODE_ACCESS_KEY', ''); @@ -150,6 +152,7 @@ function getStorageDevice($root): Device $linodeRegion = App::getEnv('_APP_STORAGE_LINODE_REGION', ''); $linodeBucket = App::getEnv('_APP_STORAGE_LINODE_BUCKET', ''); $linodeAcl = 'private'; + return new Linode($root, $linodeAccessKey, $linodeSecretKey, $linodeBucket, $linodeRegion, $linodeAcl); case Storage::DEVICE_WASABI: $wasabiAccessKey = App::getEnv('_APP_STORAGE_WASABI_ACCESS_KEY', ''); @@ -157,12 +160,13 @@ function getStorageDevice($root): Device $wasabiRegion = App::getEnv('_APP_STORAGE_WASABI_REGION', ''); $wasabiBucket = App::getEnv('_APP_STORAGE_WASABI_BUCKET', ''); $wasabiAcl = 'private'; + return new Wasabi($root, $wasabiAccessKey, $wasabiSecretKey, $wasabiBucket, $wasabiRegion, $wasabiAcl); } } App::post('/v1/runtimes') - ->desc("Create a new runtime server") + ->desc('Create a new runtime server') ->param('runtimeId', '', new Text(64), 'Unique runtime ID.') ->param('source', '', new Text(0), 'Path to source files.') ->param('destination', '', new Text(0), 'Destination folder to store build files into.', true) @@ -196,7 +200,7 @@ App::post('/v1/runtimes') $secret = \bin2hex(\random_bytes(16)); - if (!$remove) { + if (! $remove) { $activeRuntimes->set($runtimeId, [ 'id' => $containerId, 'name' => $runtimeId, @@ -208,7 +212,7 @@ App::post('/v1/runtimes') } try { - Console::info('Building container : ' . $runtimeId); + Console::info('Building container : '.$runtimeId); /** * Temporary file paths in the executor @@ -219,19 +223,19 @@ App::post('/v1/runtimes') /** * Copy code files from source to a temporary location on the executor */ - $sourceDevice = getStorageDevice("/"); + $sourceDevice = getStorageDevice('/'); $localDevice = new Local(); $buffer = $sourceDevice->read($source); - if (!$localDevice->write($tmpSource, $buffer)) { + if (! $localDevice->write($tmpSource, $buffer)) { throw new Exception('Failed to copy source code to temporary directory', 500); - }; + } /** * Create the mount folder */ - if (!\file_exists(\dirname($tmpBuild))) { - if (!@\mkdir(\dirname($tmpBuild), 0755, true)) { - throw new Exception("Failed to create temporary directory", 500); + if (! \file_exists(\dirname($tmpBuild))) { + if (! @\mkdir(\dirname($tmpBuild), 0755, true)) { + throw new Exception('Failed to create temporary directory', 500); } } @@ -249,10 +253,10 @@ App::post('/v1/runtimes') ->setSwap((int) App::getEnv('_APP_FUNCTIONS_MEMORY_SWAP', 0)); /** Keep the container alive if we have commands to be executed */ - $entrypoint = !empty($commands) ? [ + $entrypoint = ! empty($commands) ? [ 'tail', '-f', - '/dev/null' + '/dev/null', ] : []; $containerId = $orchestration->run( @@ -269,8 +273,8 @@ App::post('/v1/runtimes') ], workdir: $workdir, volumes: [ - \dirname($tmpSource) . ':/tmp:rw', - \dirname($tmpBuild) . ':/usr/code:rw' + \dirname($tmpSource).':/tmp:rw', + \dirname($tmpBuild).':/usr/code:rw', ] ); @@ -283,7 +287,7 @@ App::post('/v1/runtimes') /** * Execute any commands if they were provided */ - if (!empty($commands)) { + if (! empty($commands)) { $status = $orchestration->execute( name: $runtimeId, command: $commands, @@ -292,27 +296,27 @@ App::post('/v1/runtimes') timeout: App::getEnv('_APP_FUNCTIONS_BUILD_TIMEOUT', 900) ); - if (!$status) { - throw new Exception('Failed to build dependenices ' . $stderr, 500); + if (! $status) { + throw new Exception('Failed to build dependenices '.$stderr, 500); } } /** * Move built code to expected build directory */ - if (!empty($destination)) { + if (! empty($destination)) { // Check if the build was successful by checking if file exists - if (!\file_exists($tmpBuild)) { + if (! \file_exists($tmpBuild)) { throw new Exception('Something went wrong during the build process', 500); } $destinationDevice = getStorageDevice($destination); - $outputPath = $destinationDevice->getPath(\uniqid() . '.' . \pathinfo('code.tar.gz', PATHINFO_EXTENSION)); + $outputPath = $destinationDevice->getPath(\uniqid().'.'.\pathinfo('code.tar.gz', PATHINFO_EXTENSION)); $buffer = $localDevice->read($tmpBuild); - if (!$destinationDevice->write($outputPath, $buffer, $localDevice->getFileMimeType($tmpBuild))) { + if (! $destinationDevice->write($outputPath, $buffer, $localDevice->getFileMimeType($tmpBuild))) { throw new Exception('Failed to move built code to storage', 500); - }; + } $container['outputPath'] = $outputPath; } @@ -334,27 +338,26 @@ App::post('/v1/runtimes') 'duration' => $duration, ]); - - if (!$remove) { + if (! $remove) { $activeRuntimes->set($runtimeId, [ 'id' => $containerId, 'name' => $runtimeId, 'created' => $startTimeUnix, 'updated' => $endTimeUnix, - 'status' => 'Up ' . \round($duration, 2) . 's', + 'status' => 'Up '.\round($duration, 2).'s', 'key' => $secret, ]); } - Console::success('Build Stage completed in ' . ($duration) . ' seconds'); + Console::success('Build Stage completed in '.($duration).' seconds'); } catch (Throwable $th) { - Console::error('Build failed: ' . $th->getMessage() . $stdout); + Console::error('Build failed: '.$th->getMessage().$stdout); - throw new Exception($th->getMessage() . $stdout, 500); + throw new Exception($th->getMessage().$stdout, 500); } finally { // Container cleanup if ($remove) { - if (!empty($containerId)) { + if (! empty($containerId)) { // If container properly created $orchestration->remove($containerId, true); $activeRuntimes->del($runtimeId); @@ -380,9 +383,8 @@ App::post('/v1/runtimes') ->json($container); }); - App::get('/v1/runtimes') - ->desc("List currently active runtimes") + ->desc('List currently active runtimes') ->inject('activeRuntimes') ->inject('response') ->action(function ($activeRuntimes, Response $response) { @@ -398,13 +400,12 @@ App::get('/v1/runtimes') }); App::get('/v1/runtimes/:runtimeId') - ->desc("Get a runtime by its ID") + ->desc('Get a runtime by its ID') ->param('runtimeId', '', new Text(64), 'Runtime unique ID.') ->inject('activeRuntimes') ->inject('response') ->action(function ($runtimeId, $activeRuntimes, Response $response) { - - if (!$activeRuntimes->exists($runtimeId)) { + if (! $activeRuntimes->exists($runtimeId)) { throw new Exception('Runtime not found', 404); } @@ -422,18 +423,17 @@ App::delete('/v1/runtimes/:runtimeId') ->inject('activeRuntimes') ->inject('response') ->action(function (string $runtimeId, $orchestrationPool, $activeRuntimes, Response $response) { - - if (!$activeRuntimes->exists($runtimeId)) { + if (! $activeRuntimes->exists($runtimeId)) { throw new Exception('Runtime not found', 404); } - Console::info('Deleting runtime: ' . $runtimeId); + Console::info('Deleting runtime: '.$runtimeId); try { $orchestration = $orchestrationPool->get(); $orchestration->remove($runtimeId, true); $activeRuntimes->del($runtimeId); - Console::success('Removed runtime container: ' . $runtimeId); + Console::success('Removed runtime container: '.$runtimeId); } finally { $orchestrationPool->put($orchestration); } @@ -454,7 +454,6 @@ App::delete('/v1/runtimes/:runtimeId') ->send(); }); - App::post('/v1/execution') ->desc('Create an execution') ->param('runtimeId', '', new Text(64), 'The runtimeID to execute.') @@ -465,7 +464,7 @@ App::post('/v1/execution') ->inject('response') ->action( function (string $runtimeId, array $vars, string $data, $timeout, $activeRuntimes, Response $response) { - if (!$activeRuntimes->exists($runtimeId)) { + if (! $activeRuntimes->exists($runtimeId)) { throw new Exception('Runtime not found. Please create the runtime.', 404); } @@ -488,7 +487,7 @@ App::post('/v1/execution') throw new Exception('Runtime secret not found. Please re-create the runtime.', 500); } - Console::info('Executing Runtime: ' . $runtimeId); + Console::info('Executing Runtime: '.$runtimeId); $execution = []; $executionStart = \microtime(true); @@ -505,9 +504,9 @@ App::post('/v1/execution') $body = \json_encode([ 'variables' => $vars, 'payload' => $data, - 'timeout' => $timeout + 'timeout' => $timeout, ]); - \curl_setopt($ch, CURLOPT_URL, "http://" . $runtimeId . ":3000/"); + \curl_setopt($ch, CURLOPT_URL, 'http://'.$runtimeId.':3000/'); \curl_setopt($ch, CURLOPT_POST, true); \curl_setopt($ch, CURLOPT_POSTFIELDS, $body); \curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); @@ -516,9 +515,9 @@ App::post('/v1/execution') \curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', - 'Content-Length: ' . \strlen($body), - 'x-internal-challenge: ' . $secret, - 'host: null' + 'Content-Length: '.\strlen($body), + 'x-internal-challenge: '.$secret, + 'host: null', ]); $executorResponse = \curl_exec($ch); @@ -538,10 +537,10 @@ App::post('/v1/execution') break; /** Runtime not ready for requests yet. 111 is the swoole error code for Connection Refused - see https://openswoole.com/docs/swoole-error-code */ case $errNo === 111: - throw new Exception('An internal curl error has occurred within the executor! Error Msg: ' . $error, 406); + throw new Exception('An internal curl error has occurred within the executor! Error Msg: '.$error, 406); /** Any other CURL error */ default: - throw new Exception('An internal curl error has occurred within the executor! Error Msg: ' . $error, 500); + throw new Exception('An internal curl error has occurred within the executor! Error Msg: '.$error, 500); } switch (true) { @@ -570,7 +569,7 @@ App::post('/v1/execution') $executionTime = ($executionEnd - $executionStart); $functionStatus = ($statusCode >= 500) ? 'failed' : 'completed'; - Console::success('Function executed in ' . $executionTime . ' seconds, status: ' . $functionStatus); + Console::success('Function executed in '.$executionTime.' seconds, status: '.$functionStatus); $execution = [ 'status' => $functionStatus, @@ -593,11 +592,11 @@ App::post('/v1/execution') App::setMode(App::MODE_TYPE_PRODUCTION); // Define Mode -$http = new Server("0.0.0.0", 80); +$http = new Server('0.0.0.0', 80); /** Set Resources */ -App::setResource('orchestrationPool', fn() => $orchestrationPool); -App::setResource('activeRuntimes', fn() => $activeRuntimes); +App::setResource('orchestrationPool', fn () => $orchestrationPool); +App::setResource('activeRuntimes', fn () => $activeRuntimes); /** Set callbacks */ App::error() @@ -607,7 +606,7 @@ App::error() ->inject('response') ->action(function (App $utopia, throwable $error, Request $request, Response $response) { $route = $utopia->match($request); - logError($error, "httpError", $route); + logError($error, 'httpError', $route); switch ($error->getCode()) { case 400: // Error allowed publicly @@ -634,7 +633,7 @@ App::error() 'file' => $error->getFile(), 'line' => $error->getLine(), 'trace' => $error->getTrace(), - 'version' => App::getEnv('_APP_VERSION', 'UNKNOWN') + 'version' => App::getEnv('_APP_VERSION', 'UNKNOWN'), ]; $response @@ -659,7 +658,6 @@ App::init() } }); - $http->on('start', function ($http) { global $orchestrationPool; global $activeRuntimes; @@ -674,7 +672,7 @@ $http->on('start', function ($http) { go(function () use ($runtime, $orchestrationPool) { try { $orchestration = $orchestrationPool->get(); - Console::info('Warming up ' . $runtime['name'] . ' ' . $runtime['version'] . ' environment...'); + Console::info('Warming up '.$runtime['name'].' '.$runtime['version'].' environment...'); $response = $orchestration->pull($runtime['image']); if ($response) { Console::success("Successfully Warmed up {$runtime['name']} {$runtime['version']}!"); @@ -706,7 +704,7 @@ $http->on('start', function ($http) { $orchestration->remove($runtime->getName(), true); Console::success("Successfully removed {$runtime->getName()}"); } catch (\Throwable $th) { - Console::error('Orphan runtime deletion failed: ' . $th->getMessage()); + Console::error('Orphan runtime deletion failed: '.$th->getMessage()); } finally { $orchestrationPool->put($orchestration); } @@ -736,7 +734,7 @@ $http->on('start', function ($http) { * Run a maintenance worker every MAINTENANCE_INTERVAL seconds to remove inactive runtimes */ Timer::tick(MAINTENANCE_INTERVAL * 1000, function () use ($orchestrationPool, $activeRuntimes) { - Console::warning("Running maintenance task ..."); + Console::warning('Running maintenance task ...'); foreach ($activeRuntimes as $runtime) { $inactiveThreshold = \time() - App::getEnv('_APP_FUNCTIONS_INACTIVE_THRESHOLD', 60); if ($runtime['updated'] < $inactiveThreshold) { @@ -747,7 +745,7 @@ $http->on('start', function ($http) { $activeRuntimes->del($runtime['name']); Console::success("Successfully removed {$runtime['name']}"); } catch (\Throwable $th) { - Console::error('Inactive Runtime deletion failed: ' . $th->getMessage()); + Console::error('Inactive Runtime deletion failed: '.$th->getMessage()); } finally { $orchestrationPool->put($orchestration); } @@ -757,7 +755,6 @@ $http->on('start', function ($http) { }); }); - $http->on('beforeShutdown', function () { global $orchestrationPool; Console::info('Cleaning up containers before shutdown...'); @@ -771,9 +768,9 @@ $http->on('beforeShutdown', function () { try { $orchestration = $orchestrationPool->get(); $orchestration->remove($container->getId(), true); - Console::info('Removed container ' . $container->getName()); + Console::info('Removed container '.$container->getName()); } catch (\Throwable $th) { - Console::error('Failed to remove container: ' . $container->getName()); + Console::error('Failed to remove container: '.$container->getName()); } finally { $orchestrationPool->put($orchestration); } @@ -781,7 +778,6 @@ $http->on('beforeShutdown', function () { } }); - $http->on('request', function (SwooleRequest $swooleRequest, SwooleResponse $swooleResponse) { $request = new Request($swooleRequest); $response = new Response($swooleResponse); @@ -790,14 +786,14 @@ $http->on('request', function (SwooleRequest $swooleRequest, SwooleResponse $swo try { $app->run($request, $response); } catch (\Throwable $th) { - logError($th, "serverError"); + logError($th, 'serverError'); $swooleResponse->setStatusCode(500); $output = [ - 'message' => 'Error: ' . $th->getMessage(), + 'message' => 'Error: '.$th->getMessage(), 'code' => 500, 'file' => $th->getFile(), 'line' => $th->getLine(), - 'trace' => $th->getTrace() + 'trace' => $th->getTrace(), ]; $swooleResponse->end(\json_encode($output)); } diff --git a/app/http.php b/app/http.php index b9b4d19333..0bc84605d2 100644 --- a/app/http.php +++ b/app/http.php @@ -1,29 +1,29 @@ on('WorkerStart', function ($server, $workerId) { - Console::success('Worker ' . ++$workerId . ' started successfully'); + Console::success('Worker '.++$workerId.' started successfully'); }); $http->on('BeforeReload', function ($server, $workerId) { @@ -52,9 +52,9 @@ $http->on('AfterReload', function ($server, $workerId) { Console::success('Reload completed...'); }); -Files::load(__DIR__ . '/../console'); +Files::load(__DIR__.'/../console'); -include __DIR__ . '/controllers/general.php'; +include __DIR__.'/controllers/general.php'; $http->on('start', function (Server $http) use ($payloadSize, $register) { $app = new App('UTC'); @@ -74,7 +74,7 @@ $http->on('start', function (Server $http) use ($payloadSize, $register) { } catch (\Exception $e) { Console::warning("Database not ready. Retrying connection ({$attempts})..."); if ($attempts >= $max) { - throw new \Exception('Failed to connect to database: ' . $e->getMessage()); + throw new \Exception('Failed to connect to database: '.$e->getMessage()); } sleep($sleep); } @@ -105,7 +105,7 @@ $http->on('start', function (Server $http) use ($payloadSize, $register) { } if ($dbForConsole->getCollection(TimeLimit::COLLECTION)->isEmpty()) { - $adapter = new TimeLimit("", 0, 1, $dbForConsole); + $adapter = new TimeLimit('', 0, 1, $dbForConsole); $adapter->setup(); } @@ -113,7 +113,7 @@ $http->on('start', function (Server $http) use ($payloadSize, $register) { if (($collection['$collection'] ?? '') !== Database::METADATA) { continue; } - if (!$dbForConsole->getCollection($key)->isEmpty()) { + if (! $dbForConsole->getCollection($key)->isEmpty()) { continue; } /** @@ -123,7 +123,7 @@ $http->on('start', function (Server $http) use ($payloadSize, $register) { continue; } - Console::success('[Setup] - Creating collection: ' . $collection['$id'] . '...'); + Console::success('[Setup] - Creating collection: '.$collection['$id'].'...'); $attributes = []; $indexes = []; @@ -138,7 +138,7 @@ $http->on('start', function (Server $http) use ($payloadSize, $register) { 'array' => $attribute['array'], 'filters' => $attribute['filters'], 'default' => $attribute['default'] ?? null, - 'format' => $attribute['format'] ?? '' + 'format' => $attribute['format'] ?? '', ]); } @@ -155,7 +155,7 @@ $http->on('start', function (Server $http) use ($payloadSize, $register) { $dbForConsole->createCollection($key, $attributes, $indexes); } - if ($dbForConsole->getDocument('buckets', 'default')->isEmpty() && !$dbForConsole->exists(App::getEnv('_APP_DB_SCHEMA', 'appwrite'), 'bucket_1')) { + if ($dbForConsole->getDocument('buckets', 'default')->isEmpty() && ! $dbForConsole->exists(App::getEnv('_APP_DB_SCHEMA', 'appwrite'), 'bucket_1')) { Console::success('[Setup] - Creating default bucket...'); $dbForConsole->createDocument('buckets', new Document([ '$id' => ID::custom('default'), @@ -198,7 +198,7 @@ $http->on('start', function (Server $http) use ($payloadSize, $register) { 'array' => $attribute['array'], 'filters' => $attribute['filters'], 'default' => $attribute['default'] ?? null, - 'format' => $attribute['format'] ?? '' + 'format' => $attribute['format'] ?? '', ]); } @@ -212,13 +212,13 @@ $http->on('start', function (Server $http) use ($payloadSize, $register) { ]); } - $dbForConsole->createCollection('bucket_' . $bucket->getInternalId(), $attributes, $indexes); + $dbForConsole->createCollection('bucket_'.$bucket->getInternalId(), $attributes, $indexes); } Console::success('[Setup] - Server database init completed...'); }); - Console::success('Server started successfully (max payload is ' . number_format($payloadSize) . ' bytes)'); + Console::success('Server started successfully (max payload is '.number_format($payloadSize).' bytes)'); Console::info("Master pid {$http->master_pid}, manager pid {$http->manager_pid}"); // listen ctrl + c @@ -237,8 +237,8 @@ $http->on('request', function (SwooleRequest $swooleRequest, SwooleResponse $swo $response ->setContentType(Files::getFileMimeType($request->getURI())) - ->addHeader('Cache-Control', 'public, max-age=' . $time) - ->addHeader('Expires', \date('D, d M Y H:i:s', \time() + $time) . ' GMT') // 45 days cache + ->addHeader('Cache-Control', 'public, max-age='.$time) + ->addHeader('Expires', \date('D, d M Y H:i:s', \time() + $time).' GMT') // 45 days cache ->send(Files::getFileContents($request->getURI())); return; @@ -260,7 +260,7 @@ $http->on('request', function (SwooleRequest $swooleRequest, SwooleResponse $swo } catch (\Throwable $th) { $version = App::getEnv('_APP_VERSION', 'UNKNOWN'); - $logger = $app->getResource("logger"); + $logger = $app->getResource('logger'); if ($logger) { try { /** @var Utopia\Database\Document $user */ @@ -269,16 +269,16 @@ $http->on('request', function (SwooleRequest $swooleRequest, SwooleResponse $swo // All good, user is optional information for logger } - $loggerBreadcrumbs = $app->getResource("loggerBreadcrumbs"); + $loggerBreadcrumbs = $app->getResource('loggerBreadcrumbs'); $route = $app->match($request); $log = new Utopia\Logger\Log(); - if (isset($user) && !$user->isEmpty()) { + if (isset($user) && ! $user->isEmpty()) { $log->setUser(new User($user->getId())); } - $log->setNamespace("http"); + $log->setNamespace('http'); $log->setServer(\gethostname()); $log->setVersion($version); $log->setType(Log::TYPE_ERROR); @@ -290,7 +290,7 @@ $http->on('request', function (SwooleRequest $swooleRequest, SwooleResponse $swo $log->addTag('code', $th->getCode()); // $log->addTag('projectId', $project->getId()); // TODO: Figure out how to get ProjectID, if it becomes relevant $log->addTag('hostname', $request->getHostname()); - $log->addTag('locale', (string)$request->getParam('locale', $request->getHeader('x-appwrite-locale', ''))); + $log->addTag('locale', (string) $request->getParam('locale', $request->getHeader('x-appwrite-locale', ''))); $log->addExtra('file', $th->getFile()); $log->addExtra('line', $th->getLine()); @@ -298,7 +298,7 @@ $http->on('request', function (SwooleRequest $swooleRequest, SwooleResponse $swo $log->addExtra('detailedTrace', $th->getTrace()); $log->addExtra('roles', Authorization::$roles); - $action = $route->getLabel("sdk.namespace", "UNKNOWN_NAMESPACE") . '.' . $route->getLabel("sdk.method", "UNKNOWN_METHOD"); + $action = $route->getLabel('sdk.namespace', 'UNKNOWN_NAMESPACE').'.'.$route->getLabel('sdk.method', 'UNKNOWN_METHOD'); $log->setAction($action); $isProduction = App::getEnv('_APP_ENV', 'development') === 'production'; @@ -309,18 +309,18 @@ $http->on('request', function (SwooleRequest $swooleRequest, SwooleResponse $swo } $responseCode = $logger->addLog($log); - Console::info('Log pushed with status code: ' . $responseCode); + Console::info('Log pushed with status code: '.$responseCode); } - Console::error('[Error] Type: ' . get_class($th)); - Console::error('[Error] Message: ' . $th->getMessage()); - Console::error('[Error] File: ' . $th->getFile()); - Console::error('[Error] Line: ' . $th->getLine()); + Console::error('[Error] Type: '.get_class($th)); + Console::error('[Error] Message: '.$th->getMessage()); + Console::error('[Error] File: '.$th->getFile()); + Console::error('[Error] Line: '.$th->getLine()); $swooleResponse->setStatusCode(500); $output = ((App::isDevelopment())) ? [ - 'message' => 'Error: ' . $th->getMessage(), + 'message' => 'Error: '.$th->getMessage(), 'code' => 500, 'file' => $th->getFile(), 'line' => $th->getLine(), diff --git a/app/init.php b/app/init.php index 86f2a2d901..32b0cba153 100644 --- a/app/init.php +++ b/app/init.php @@ -5,11 +5,9 @@ * * Initializes both Appwrite API entry point, queue workers, and CLI tasks. * Set configuration, framework resources & app constants - * */ - -if (\file_exists(__DIR__ . '/../vendor/autoload.php')) { - require_once __DIR__ . '/../vendor/autoload.php'; +if (\file_exists(__DIR__.'/../vendor/autoload.php')) { + require_once __DIR__.'/../vendor/autoload.php'; } ini_set('memory_limit', '512M'); @@ -43,14 +41,13 @@ use Swoole\Database\PDOPool; use Swoole\Database\RedisConfig; use Swoole\Database\RedisPool; use Utopia\App; -use Utopia\Database\Helpers\ID; -use Utopia\Logger\Logger; use Utopia\Cache\Adapter\Redis as RedisCache; use Utopia\Cache\Cache; use Utopia\Config\Config; use Utopia\Database\Adapter\MariaDB; use Utopia\Database\Database; use Utopia\Database\Document; +use Utopia\Database\Helpers\ID; use Utopia\Database\Query; use Utopia\Database\Validator\Authorization; use Utopia\Database\Validator\DatetimeValidator; @@ -58,6 +55,7 @@ use Utopia\Database\Validator\Structure; use Utopia\Domains\Registrar; use Utopia\Domains\Registrar\OpenSRS; use Utopia\Locale\Locale; +use Utopia\Logger\Logger; use Utopia\Messaging\Adapters\SMS\Mock; use Utopia\Messaging\Adapters\SMS\Msg91; use Utopia\Messaging\Adapters\SMS\Telesign; @@ -73,8 +71,8 @@ use Utopia\Storage\Device\Local; use Utopia\Storage\Device\S3; use Utopia\Storage\Device\Wasabi; use Utopia\Storage\Storage; -use Utopia\Validator\Range; use Utopia\Validator\IP; +use Utopia\Validator\Range; use Utopia\Validator\URL; use Utopia\Validator\WhiteList; @@ -82,7 +80,7 @@ const APP_NAME = 'Appwrite'; const APP_DOMAIN = 'appwrite.io'; const APP_EMAIL_TEAM = 'team@localhost.test'; // Default email address const APP_EMAIL_SECURITY = ''; // Default security email address -const APP_USERAGENT = APP_NAME . '-Server v%s. Please report abuse at %s'; +const APP_USERAGENT = APP_NAME.'-Server v%s. Please report abuse at %s'; const APP_MODE_DEFAULT = 'default'; const APP_MODE_ADMIN = 'admin'; const APP_PAGING_LIMIT = 12; @@ -158,7 +156,7 @@ const DELETE_TYPE_REALTIME = 'realtime'; const DELETE_TYPE_BUCKETS = 'buckets'; const DELETE_TYPE_SESSIONS = 'sessions'; const DELETE_TYPE_CACHE_BY_TIMESTAMP = 'cacheByTimeStamp'; -const DELETE_TYPE_CACHE_BY_RESOURCE = 'cacheByResource'; +const DELETE_TYPE_CACHE_BY_RESOURCE = 'cacheByResource'; // Compression type const COMPRESSION_TYPE_NONE = 'none'; const COMPRESSION_TYPE_GZIP = 'gzip'; @@ -184,39 +182,39 @@ App::setMode(App::getEnv('_APP_ENV', App::MODE_TYPE_PRODUCTION)); /* * ENV vars */ -Config::load('events', __DIR__ . '/config/events.php'); -Config::load('auth', __DIR__ . '/config/auth.php'); -Config::load('errors', __DIR__ . '/config/errors.php'); -Config::load('providers', __DIR__ . '/config/providers.php'); -Config::load('platforms', __DIR__ . '/config/platforms.php'); -Config::load('collections', __DIR__ . '/config/collections.php'); -Config::load('runtimes', __DIR__ . '/config/runtimes.php'); -Config::load('roles', __DIR__ . '/config/roles.php'); // User roles and scopes -Config::load('scopes', __DIR__ . '/config/scopes.php'); // User roles and scopes -Config::load('services', __DIR__ . '/config/services.php'); // List of services -Config::load('variables', __DIR__ . '/config/variables.php'); // List of env variables -Config::load('regions', __DIR__ . '/config/regions.php'); // List of available regions -Config::load('avatar-browsers', __DIR__ . '/config/avatars/browsers.php'); -Config::load('avatar-credit-cards', __DIR__ . '/config/avatars/credit-cards.php'); -Config::load('avatar-flags', __DIR__ . '/config/avatars/flags.php'); -Config::load('locale-codes', __DIR__ . '/config/locale/codes.php'); -Config::load('locale-currencies', __DIR__ . '/config/locale/currencies.php'); -Config::load('locale-eu', __DIR__ . '/config/locale/eu.php'); -Config::load('locale-languages', __DIR__ . '/config/locale/languages.php'); -Config::load('locale-phones', __DIR__ . '/config/locale/phones.php'); -Config::load('locale-countries', __DIR__ . '/config/locale/countries.php'); -Config::load('locale-continents', __DIR__ . '/config/locale/continents.php'); -Config::load('storage-logos', __DIR__ . '/config/storage/logos.php'); -Config::load('storage-mimes', __DIR__ . '/config/storage/mimes.php'); -Config::load('storage-inputs', __DIR__ . '/config/storage/inputs.php'); -Config::load('storage-outputs', __DIR__ . '/config/storage/outputs.php'); +Config::load('events', __DIR__.'/config/events.php'); +Config::load('auth', __DIR__.'/config/auth.php'); +Config::load('errors', __DIR__.'/config/errors.php'); +Config::load('providers', __DIR__.'/config/providers.php'); +Config::load('platforms', __DIR__.'/config/platforms.php'); +Config::load('collections', __DIR__.'/config/collections.php'); +Config::load('runtimes', __DIR__.'/config/runtimes.php'); +Config::load('roles', __DIR__.'/config/roles.php'); // User roles and scopes +Config::load('scopes', __DIR__.'/config/scopes.php'); // User roles and scopes +Config::load('services', __DIR__.'/config/services.php'); // List of services +Config::load('variables', __DIR__.'/config/variables.php'); // List of env variables +Config::load('regions', __DIR__.'/config/regions.php'); // List of available regions +Config::load('avatar-browsers', __DIR__.'/config/avatars/browsers.php'); +Config::load('avatar-credit-cards', __DIR__.'/config/avatars/credit-cards.php'); +Config::load('avatar-flags', __DIR__.'/config/avatars/flags.php'); +Config::load('locale-codes', __DIR__.'/config/locale/codes.php'); +Config::load('locale-currencies', __DIR__.'/config/locale/currencies.php'); +Config::load('locale-eu', __DIR__.'/config/locale/eu.php'); +Config::load('locale-languages', __DIR__.'/config/locale/languages.php'); +Config::load('locale-phones', __DIR__.'/config/locale/phones.php'); +Config::load('locale-countries', __DIR__.'/config/locale/countries.php'); +Config::load('locale-continents', __DIR__.'/config/locale/continents.php'); +Config::load('storage-logos', __DIR__.'/config/storage/logos.php'); +Config::load('storage-mimes', __DIR__.'/config/storage/mimes.php'); +Config::load('storage-inputs', __DIR__.'/config/storage/inputs.php'); +Config::load('storage-outputs', __DIR__.'/config/storage/outputs.php'); $user = App::getEnv('_APP_REDIS_USER', ''); $pass = App::getEnv('_APP_REDIS_PASS', ''); -if (!empty($user) || !empty($pass)) { - Resque::setBackend('redis://' . $user . ':' . $pass . '@' . App::getEnv('_APP_REDIS_HOST', '') . ':' . App::getEnv('_APP_REDIS_PORT', '')); +if (! empty($user) || ! empty($pass)) { + Resque::setBackend('redis://'.$user.':'.$pass.'@'.App::getEnv('_APP_REDIS_HOST', '').':'.App::getEnv('_APP_REDIS_PORT', '')); } else { - Resque::setBackend(App::getEnv('_APP_REDIS_HOST', '') . ':' . App::getEnv('_APP_REDIS_PORT', '')); + Resque::setBackend(App::getEnv('_APP_REDIS_HOST', '').':'.App::getEnv('_APP_REDIS_PORT', '')); } /** @@ -272,8 +270,7 @@ Database::addFilter( if (isset($formatOptions['min']) || isset($formatOptions['max'])) { $attribute ->setAttribute('min', $formatOptions['min']) - ->setAttribute('max', $formatOptions['max']) - ; + ->setAttribute('max', $formatOptions['max']); } return $value; @@ -385,7 +382,7 @@ Database::addFilter( return null; }, function (mixed $value, Document $document, Database $database) { - return Authorization::skip(fn() => $database + return Authorization::skip(fn () => $database ->find('tokens', [ Query::equal('userInternalId', [$document->getInternalId()]), Query::limit(APP_LIMIT_SUBQUERY), @@ -399,7 +396,7 @@ Database::addFilter( return null; }, function (mixed $value, Document $document, Database $database) { - return Authorization::skip(fn() => $database + return Authorization::skip(fn () => $database ->find('memberships', [ Query::equal('userInternalId', [$document->getInternalId()]), Query::limit(APP_LIMIT_SUBQUERY), @@ -441,7 +438,7 @@ Database::addFilter( return null; } $value = json_decode($value, true); - $key = App::getEnv('_APP_OPENSSL_KEY_V' . $value['version']); + $key = App::getEnv('_APP_OPENSSL_KEY_V'.$value['version']); return OpenSSL::decrypt($value['data'], $value['method'], $key, 0, hex2bin($value['iv']), hex2bin($value['tag'])); } @@ -460,6 +457,7 @@ Structure::addFormat(APP_DATABASE_ATTRIBUTE_DATETIME, function () { Structure::addFormat(APP_DATABASE_ATTRIBUTE_ENUM, function ($attribute) { $elements = $attribute['formatOptions']['elements']; + return new WhiteList($elements, true); }, Database::VAR_STRING); @@ -474,12 +472,14 @@ Structure::addFormat(APP_DATABASE_ATTRIBUTE_URL, function () { Structure::addFormat(APP_DATABASE_ATTRIBUTE_INT_RANGE, function ($attribute) { $min = $attribute['formatOptions']['min'] ?? -INF; $max = $attribute['formatOptions']['max'] ?? INF; + return new Range($min, $max, Range::TYPE_INTEGER); }, Database::VAR_INTEGER); Structure::addFormat(APP_DATABASE_ATTRIBUTE_FLOAT_RANGE, function ($attribute) { $min = $attribute['formatOptions']['min'] ?? -INF; $max = $attribute['formatOptions']['max'] ?? INF; + return new Range($min, $max, Range::TYPE_FLOAT); }, Database::VAR_FLOAT); @@ -495,16 +495,17 @@ $register->set('logger', function () { return null; } - if (!Logger::hasProvider($providerName)) { - throw new Exception(Exception::GENERAL_SERVER_ERROR, "Logging provider not supported. Logging is disabled"); + if (! Logger::hasProvider($providerName)) { + throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Logging provider not supported. Logging is disabled'); } - $classname = '\\Utopia\\Logger\\Adapter\\' . \ucfirst($providerName); + $classname = '\\Utopia\\Logger\\Adapter\\'.\ucfirst($providerName); $adapter = new $classname($providerConfig); + return new Logger($adapter); }); $register->set('dbPool', function () { - // Register DB connection + // Register DB connection $dbHost = App::getEnv('_APP_DB_HOST', ''); $dbPort = App::getEnv('_APP_DB_PORT', ''); $dbUser = App::getEnv('_APP_DB_USER', ''); @@ -540,7 +541,7 @@ $register->set('redisPool', function () { $redisAuth = ''; if ($redisUser && $redisPass) { - $redisAuth = $redisUser . ':' . $redisPass; + $redisAuth = $redisUser.':'.$redisPass; } $pool = new RedisPool( @@ -555,7 +556,7 @@ $register->set('redisPool', function () { return $pool; }); $register->set('influxdb', function () { - // Register DB connection + // Register DB connection $host = App::getEnv('_APP_INFLUXDB_HOST', ''); $port = App::getEnv('_APP_INFLUXDB_PORT', ''); @@ -569,7 +570,7 @@ $register->set('influxdb', function () { return $client; }); $register->set('statsd', function () { - // Register DB connection + // Register DB connection $host = App::getEnv('_APP_STATSD_HOST', 'telegraf'); $port = App::getEnv('_APP_STATSD_PORT', 8125); @@ -589,14 +590,14 @@ $register->set('smtp', function () { $mail->XMailer = 'Appwrite Mailer'; $mail->Host = App::getEnv('_APP_SMTP_HOST', 'smtp'); $mail->Port = App::getEnv('_APP_SMTP_PORT', 25); - $mail->SMTPAuth = (!empty($username) && !empty($password)); + $mail->SMTPAuth = (! empty($username) && ! empty($password)); $mail->Username = $username; $mail->Password = $password; $mail->SMTPSecure = App::getEnv('_APP_SMTP_SECURE', false); $mail->SMTPAutoTLS = false; $mail->CharSet = 'UTF-8'; - $from = \urldecode(App::getEnv('_APP_SYSTEM_EMAIL_NAME', APP_NAME . ' Server')); + $from = \urldecode(App::getEnv('_APP_SYSTEM_EMAIL_NAME', APP_NAME.' Server')); $email = App::getEnv('_APP_SYSTEM_EMAIL_ADDRESS', APP_EMAIL_TEAM); $mail->setFrom($email, $from); @@ -607,29 +608,29 @@ $register->set('smtp', function () { return $mail; }); $register->set('geodb', function () { - return new Reader(__DIR__ . '/assets/dbip/dbip-country-lite-2023-01.mmdb'); + return new Reader(__DIR__.'/assets/dbip/dbip-country-lite-2023-01.mmdb'); }); $register->set('db', function () { - // This is usually for our workers or CLI commands scope + // This is usually for our workers or CLI commands scope $dbHost = App::getEnv('_APP_DB_HOST', ''); $dbPort = App::getEnv('_APP_DB_PORT', ''); $dbUser = App::getEnv('_APP_DB_USER', ''); $dbPass = App::getEnv('_APP_DB_PASS', ''); $dbScheme = App::getEnv('_APP_DB_SCHEMA', ''); - $pdo = new PDO("mysql:host={$dbHost};port={$dbPort};dbname={$dbScheme};charset=utf8mb4", $dbUser, $dbPass, array( + $pdo = new PDO("mysql:host={$dbHost};port={$dbPort};dbname={$dbScheme};charset=utf8mb4", $dbUser, $dbPass, [ PDO::ATTR_TIMEOUT => 3, // Seconds PDO::ATTR_PERSISTENT => true, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_EMULATE_PREPARES => true, PDO::ATTR_STRINGIFY_FETCHES => true, - )); + ]); return $pdo; }); $register->set('cache', function () { - // This is usually for our workers or CLI commands scope + // This is usually for our workers or CLI commands scope $redis = new Redis(); $redis->pconnect(App::getEnv('_APP_REDIS_HOST', ''), App::getEnv('_APP_REDIS_PORT', '')); $redis->setOption(Redis::OPT_READ_TIMEOUT, -1); @@ -644,78 +645,78 @@ $register->set('promiseAdapter', function () { * Localization */ Locale::$exceptions = false; -Locale::setLanguageFromJSON('af', __DIR__ . '/config/locale/translations/af.json'); -Locale::setLanguageFromJSON('ar', __DIR__ . '/config/locale/translations/ar.json'); -Locale::setLanguageFromJSON('as', __DIR__ . '/config/locale/translations/as.json'); -Locale::setLanguageFromJSON('az', __DIR__ . '/config/locale/translations/az.json'); -Locale::setLanguageFromJSON('be', __DIR__ . '/config/locale/translations/be.json'); -Locale::setLanguageFromJSON('bg', __DIR__ . '/config/locale/translations/bg.json'); -Locale::setLanguageFromJSON('bh', __DIR__ . '/config/locale/translations/bh.json'); -Locale::setLanguageFromJSON('bn', __DIR__ . '/config/locale/translations/bn.json'); -Locale::setLanguageFromJSON('bs', __DIR__ . '/config/locale/translations/bs.json'); -Locale::setLanguageFromJSON('ca', __DIR__ . '/config/locale/translations/ca.json'); -Locale::setLanguageFromJSON('cs', __DIR__ . '/config/locale/translations/cs.json'); -Locale::setLanguageFromJSON('da', __DIR__ . '/config/locale/translations/da.json'); -Locale::setLanguageFromJSON('de', __DIR__ . '/config/locale/translations/de.json'); -Locale::setLanguageFromJSON('el', __DIR__ . '/config/locale/translations/el.json'); -Locale::setLanguageFromJSON('en', __DIR__ . '/config/locale/translations/en.json'); -Locale::setLanguageFromJSON('eo', __DIR__ . '/config/locale/translations/eo.json'); -Locale::setLanguageFromJSON('es', __DIR__ . '/config/locale/translations/es.json'); -Locale::setLanguageFromJSON('fa', __DIR__ . '/config/locale/translations/fa.json'); -Locale::setLanguageFromJSON('fi', __DIR__ . '/config/locale/translations/fi.json'); -Locale::setLanguageFromJSON('fo', __DIR__ . '/config/locale/translations/fo.json'); -Locale::setLanguageFromJSON('fr', __DIR__ . '/config/locale/translations/fr.json'); -Locale::setLanguageFromJSON('ga', __DIR__ . '/config/locale/translations/ga.json'); -Locale::setLanguageFromJSON('gu', __DIR__ . '/config/locale/translations/gu.json'); -Locale::setLanguageFromJSON('he', __DIR__ . '/config/locale/translations/he.json'); -Locale::setLanguageFromJSON('hi', __DIR__ . '/config/locale/translations/hi.json'); -Locale::setLanguageFromJSON('hr', __DIR__ . '/config/locale/translations/hr.json'); -Locale::setLanguageFromJSON('hu', __DIR__ . '/config/locale/translations/hu.json'); -Locale::setLanguageFromJSON('hy', __DIR__ . '/config/locale/translations/hy.json'); -Locale::setLanguageFromJSON('id', __DIR__ . '/config/locale/translations/id.json'); -Locale::setLanguageFromJSON('is', __DIR__ . '/config/locale/translations/is.json'); -Locale::setLanguageFromJSON('it', __DIR__ . '/config/locale/translations/it.json'); -Locale::setLanguageFromJSON('ja', __DIR__ . '/config/locale/translations/ja.json'); -Locale::setLanguageFromJSON('jv', __DIR__ . '/config/locale/translations/jv.json'); -Locale::setLanguageFromJSON('kn', __DIR__ . '/config/locale/translations/kn.json'); -Locale::setLanguageFromJSON('km', __DIR__ . '/config/locale/translations/km.json'); -Locale::setLanguageFromJSON('ko', __DIR__ . '/config/locale/translations/ko.json'); -Locale::setLanguageFromJSON('la', __DIR__ . '/config/locale/translations/la.json'); -Locale::setLanguageFromJSON('lb', __DIR__ . '/config/locale/translations/lb.json'); -Locale::setLanguageFromJSON('lt', __DIR__ . '/config/locale/translations/lt.json'); -Locale::setLanguageFromJSON('lv', __DIR__ . '/config/locale/translations/lv.json'); -Locale::setLanguageFromJSON('ml', __DIR__ . '/config/locale/translations/ml.json'); -Locale::setLanguageFromJSON('mr', __DIR__ . '/config/locale/translations/mr.json'); -Locale::setLanguageFromJSON('ms', __DIR__ . '/config/locale/translations/ms.json'); -Locale::setLanguageFromJSON('nb', __DIR__ . '/config/locale/translations/nb.json'); -Locale::setLanguageFromJSON('ne', __DIR__ . '/config/locale/translations/ne.json'); -Locale::setLanguageFromJSON('nl', __DIR__ . '/config/locale/translations/nl.json'); -Locale::setLanguageFromJSON('nn', __DIR__ . '/config/locale/translations/nn.json'); -Locale::setLanguageFromJSON('or', __DIR__ . '/config/locale/translations/or.json'); -Locale::setLanguageFromJSON('pa', __DIR__ . '/config/locale/translations/pa.json'); -Locale::setLanguageFromJSON('pl', __DIR__ . '/config/locale/translations/pl.json'); -Locale::setLanguageFromJSON('pt-br', __DIR__ . '/config/locale/translations/pt-br.json'); -Locale::setLanguageFromJSON('pt-pt', __DIR__ . '/config/locale/translations/pt-pt.json'); -Locale::setLanguageFromJSON('ro', __DIR__ . '/config/locale/translations/ro.json'); -Locale::setLanguageFromJSON('ru', __DIR__ . '/config/locale/translations/ru.json'); -Locale::setLanguageFromJSON('sa', __DIR__ . '/config/locale/translations/sa.json'); -Locale::setLanguageFromJSON('sd', __DIR__ . '/config/locale/translations/sd.json'); -Locale::setLanguageFromJSON('si', __DIR__ . '/config/locale/translations/si.json'); -Locale::setLanguageFromJSON('sk', __DIR__ . '/config/locale/translations/sk.json'); -Locale::setLanguageFromJSON('sl', __DIR__ . '/config/locale/translations/sl.json'); -Locale::setLanguageFromJSON('sn', __DIR__ . '/config/locale/translations/sn.json'); -Locale::setLanguageFromJSON('sq', __DIR__ . '/config/locale/translations/sq.json'); -Locale::setLanguageFromJSON('sv', __DIR__ . '/config/locale/translations/sv.json'); -Locale::setLanguageFromJSON('ta', __DIR__ . '/config/locale/translations/ta.json'); -Locale::setLanguageFromJSON('te', __DIR__ . '/config/locale/translations/te.json'); -Locale::setLanguageFromJSON('th', __DIR__ . '/config/locale/translations/th.json'); -Locale::setLanguageFromJSON('tl', __DIR__ . '/config/locale/translations/tl.json'); -Locale::setLanguageFromJSON('tr', __DIR__ . '/config/locale/translations/tr.json'); -Locale::setLanguageFromJSON('uk', __DIR__ . '/config/locale/translations/uk.json'); -Locale::setLanguageFromJSON('ur', __DIR__ . '/config/locale/translations/ur.json'); -Locale::setLanguageFromJSON('vi', __DIR__ . '/config/locale/translations/vi.json'); -Locale::setLanguageFromJSON('zh-cn', __DIR__ . '/config/locale/translations/zh-cn.json'); -Locale::setLanguageFromJSON('zh-tw', __DIR__ . '/config/locale/translations/zh-tw.json'); +Locale::setLanguageFromJSON('af', __DIR__.'/config/locale/translations/af.json'); +Locale::setLanguageFromJSON('ar', __DIR__.'/config/locale/translations/ar.json'); +Locale::setLanguageFromJSON('as', __DIR__.'/config/locale/translations/as.json'); +Locale::setLanguageFromJSON('az', __DIR__.'/config/locale/translations/az.json'); +Locale::setLanguageFromJSON('be', __DIR__.'/config/locale/translations/be.json'); +Locale::setLanguageFromJSON('bg', __DIR__.'/config/locale/translations/bg.json'); +Locale::setLanguageFromJSON('bh', __DIR__.'/config/locale/translations/bh.json'); +Locale::setLanguageFromJSON('bn', __DIR__.'/config/locale/translations/bn.json'); +Locale::setLanguageFromJSON('bs', __DIR__.'/config/locale/translations/bs.json'); +Locale::setLanguageFromJSON('ca', __DIR__.'/config/locale/translations/ca.json'); +Locale::setLanguageFromJSON('cs', __DIR__.'/config/locale/translations/cs.json'); +Locale::setLanguageFromJSON('da', __DIR__.'/config/locale/translations/da.json'); +Locale::setLanguageFromJSON('de', __DIR__.'/config/locale/translations/de.json'); +Locale::setLanguageFromJSON('el', __DIR__.'/config/locale/translations/el.json'); +Locale::setLanguageFromJSON('en', __DIR__.'/config/locale/translations/en.json'); +Locale::setLanguageFromJSON('eo', __DIR__.'/config/locale/translations/eo.json'); +Locale::setLanguageFromJSON('es', __DIR__.'/config/locale/translations/es.json'); +Locale::setLanguageFromJSON('fa', __DIR__.'/config/locale/translations/fa.json'); +Locale::setLanguageFromJSON('fi', __DIR__.'/config/locale/translations/fi.json'); +Locale::setLanguageFromJSON('fo', __DIR__.'/config/locale/translations/fo.json'); +Locale::setLanguageFromJSON('fr', __DIR__.'/config/locale/translations/fr.json'); +Locale::setLanguageFromJSON('ga', __DIR__.'/config/locale/translations/ga.json'); +Locale::setLanguageFromJSON('gu', __DIR__.'/config/locale/translations/gu.json'); +Locale::setLanguageFromJSON('he', __DIR__.'/config/locale/translations/he.json'); +Locale::setLanguageFromJSON('hi', __DIR__.'/config/locale/translations/hi.json'); +Locale::setLanguageFromJSON('hr', __DIR__.'/config/locale/translations/hr.json'); +Locale::setLanguageFromJSON('hu', __DIR__.'/config/locale/translations/hu.json'); +Locale::setLanguageFromJSON('hy', __DIR__.'/config/locale/translations/hy.json'); +Locale::setLanguageFromJSON('id', __DIR__.'/config/locale/translations/id.json'); +Locale::setLanguageFromJSON('is', __DIR__.'/config/locale/translations/is.json'); +Locale::setLanguageFromJSON('it', __DIR__.'/config/locale/translations/it.json'); +Locale::setLanguageFromJSON('ja', __DIR__.'/config/locale/translations/ja.json'); +Locale::setLanguageFromJSON('jv', __DIR__.'/config/locale/translations/jv.json'); +Locale::setLanguageFromJSON('kn', __DIR__.'/config/locale/translations/kn.json'); +Locale::setLanguageFromJSON('km', __DIR__.'/config/locale/translations/km.json'); +Locale::setLanguageFromJSON('ko', __DIR__.'/config/locale/translations/ko.json'); +Locale::setLanguageFromJSON('la', __DIR__.'/config/locale/translations/la.json'); +Locale::setLanguageFromJSON('lb', __DIR__.'/config/locale/translations/lb.json'); +Locale::setLanguageFromJSON('lt', __DIR__.'/config/locale/translations/lt.json'); +Locale::setLanguageFromJSON('lv', __DIR__.'/config/locale/translations/lv.json'); +Locale::setLanguageFromJSON('ml', __DIR__.'/config/locale/translations/ml.json'); +Locale::setLanguageFromJSON('mr', __DIR__.'/config/locale/translations/mr.json'); +Locale::setLanguageFromJSON('ms', __DIR__.'/config/locale/translations/ms.json'); +Locale::setLanguageFromJSON('nb', __DIR__.'/config/locale/translations/nb.json'); +Locale::setLanguageFromJSON('ne', __DIR__.'/config/locale/translations/ne.json'); +Locale::setLanguageFromJSON('nl', __DIR__.'/config/locale/translations/nl.json'); +Locale::setLanguageFromJSON('nn', __DIR__.'/config/locale/translations/nn.json'); +Locale::setLanguageFromJSON('or', __DIR__.'/config/locale/translations/or.json'); +Locale::setLanguageFromJSON('pa', __DIR__.'/config/locale/translations/pa.json'); +Locale::setLanguageFromJSON('pl', __DIR__.'/config/locale/translations/pl.json'); +Locale::setLanguageFromJSON('pt-br', __DIR__.'/config/locale/translations/pt-br.json'); +Locale::setLanguageFromJSON('pt-pt', __DIR__.'/config/locale/translations/pt-pt.json'); +Locale::setLanguageFromJSON('ro', __DIR__.'/config/locale/translations/ro.json'); +Locale::setLanguageFromJSON('ru', __DIR__.'/config/locale/translations/ru.json'); +Locale::setLanguageFromJSON('sa', __DIR__.'/config/locale/translations/sa.json'); +Locale::setLanguageFromJSON('sd', __DIR__.'/config/locale/translations/sd.json'); +Locale::setLanguageFromJSON('si', __DIR__.'/config/locale/translations/si.json'); +Locale::setLanguageFromJSON('sk', __DIR__.'/config/locale/translations/sk.json'); +Locale::setLanguageFromJSON('sl', __DIR__.'/config/locale/translations/sl.json'); +Locale::setLanguageFromJSON('sn', __DIR__.'/config/locale/translations/sn.json'); +Locale::setLanguageFromJSON('sq', __DIR__.'/config/locale/translations/sq.json'); +Locale::setLanguageFromJSON('sv', __DIR__.'/config/locale/translations/sv.json'); +Locale::setLanguageFromJSON('ta', __DIR__.'/config/locale/translations/ta.json'); +Locale::setLanguageFromJSON('te', __DIR__.'/config/locale/translations/te.json'); +Locale::setLanguageFromJSON('th', __DIR__.'/config/locale/translations/th.json'); +Locale::setLanguageFromJSON('tl', __DIR__.'/config/locale/translations/tl.json'); +Locale::setLanguageFromJSON('tr', __DIR__.'/config/locale/translations/tr.json'); +Locale::setLanguageFromJSON('uk', __DIR__.'/config/locale/translations/uk.json'); +Locale::setLanguageFromJSON('ur', __DIR__.'/config/locale/translations/ur.json'); +Locale::setLanguageFromJSON('vi', __DIR__.'/config/locale/translations/vi.json'); +Locale::setLanguageFromJSON('zh-cn', __DIR__.'/config/locale/translations/zh-cn.json'); +Locale::setLanguageFromJSON('zh-tw', __DIR__.'/config/locale/translations/zh-tw.json'); \stream_context_set_default([ // Set global user agent and http settings 'http' => [ @@ -738,32 +739,32 @@ App::setResource('loggerBreadcrumbs', function () { return []; }); -App::setResource('register', fn() => $register); +App::setResource('register', fn () => $register); -App::setResource('locale', fn() => new Locale(App::getEnv('_APP_LOCALE', 'en'))); +App::setResource('locale', fn () => new Locale(App::getEnv('_APP_LOCALE', 'en'))); -App::setResource('registrar', function(){ - $opensrs = new OpenSRS( - App::getEnv('OPENSRS_KEY'), - App::getEnv('OPENSRS_USERNAME'), - 'appwrite', - '0p3n5R5@Appwrite', - [ - 'ns1.appwrite.io', - 'ns2.appwrite.io', - ] - ); - - return new Registrar($opensrs); +App::setResource('registrar', function () { + $opensrs = new OpenSRS( + App::getEnv('OPENSRS_KEY'), + App::getEnv('OPENSRS_USERNAME'), + 'appwrite', + '0p3n5R5@Appwrite', + [ + 'ns1.appwrite.io', + 'ns2.appwrite.io', + ] + ); + + return new Registrar($opensrs); }); // Queues -App::setResource('events', fn() => new Event('', '')); -App::setResource('audits', fn() => new Audit()); -App::setResource('mails', fn() => new Mail()); -App::setResource('deletes', fn() => new Delete()); -App::setResource('database', fn() => new EventDatabase()); -App::setResource('messaging', fn() => new Phone()); +App::setResource('events', fn () => new Event('', '')); +App::setResource('audits', fn () => new Audit()); +App::setResource('mails', fn () => new Mail()); +App::setResource('deletes', fn () => new Delete()); +App::setResource('database', fn () => new EventDatabase()); +App::setResource('messaging', fn () => new Phone()); App::setResource('usage', function ($register) { return new Stats($register->get('statsd')); }, ['register']); @@ -784,7 +785,7 @@ App::setResource('clients', function ($request, $console, $project) { fn ($node) => $node['hostname'], \array_filter( $console->getAttribute('platforms', []), - fn ($node) => (isset($node['type']) && ($node['type'] === Origin::CLIENT_TYPE_WEB) && isset($node['hostname']) && !empty($node['hostname'])) + fn ($node) => (isset($node['type']) && ($node['type'] === Origin::CLIENT_TYPE_WEB) && isset($node['hostname']) && ! empty($node['hostname'])) ) ); @@ -795,7 +796,7 @@ App::setResource('clients', function ($request, $console, $project) { fn ($node) => $node['hostname'], \array_filter( $project->getAttribute('platforms', []), - fn ($node) => (isset($node['type']) && ($node['type'] === Origin::CLIENT_TYPE_WEB || $node['type'] === Origin::CLIENT_TYPE_FLUTTER_WEB) && isset($node['hostname']) && !empty($node['hostname'])) + fn ($node) => (isset($node['type']) && ($node['type'] === Origin::CLIENT_TYPE_WEB || $node['type'] === Origin::CLIENT_TYPE_FLUTTER_WEB) && isset($node['hostname']) && ! empty($node['hostname'])) ) ) ) @@ -811,23 +812,22 @@ App::setResource('user', function ($mode, $project, $console, $request, $respons /** @var Utopia\Database\Database $dbForProject */ /** @var Utopia\Database\Database $dbForConsole */ /** @var string $mode */ - Authorization::setDefaultStatus(true); - Auth::setCookieName('a_session_' . $project->getId()); + Auth::setCookieName('a_session_'.$project->getId()); $authDuration = $project->getAttribute('auths', [])['duration'] ?? Auth::TOKEN_EXPIRATION_LOGIN_LONG; if (APP_MODE_ADMIN === $mode) { - Auth::setCookieName('a_session_' . $console->getId()); + Auth::setCookieName('a_session_'.$console->getId()); $authDuration = Auth::TOKEN_EXPIRATION_LOGIN_LONG; } $session = Auth::decodeSession( $request->getCookie( Auth::$cookieName, // Get sessions - $request->getCookie(Auth::$cookieName . '_legacy', '') + $request->getCookie(Auth::$cookieName.'_legacy', '') ) - );// Get fallback session from old clients (no SameSite support) + ); // Get fallback session from old clients (no SameSite support) // Get fallback session from clients who block 3rd-party cookies if ($response) { @@ -858,7 +858,7 @@ App::setResource('user', function ($mode, $project, $console, $request, $respons if ( $user->isEmpty() // Check a document has been found in the DB - || !Auth::sessionVerify($user->getAttribute('sessions', []), Auth::$secret, $authDuration) + || ! Auth::sessionVerify($user->getAttribute('sessions', []), Auth::$secret, $authDuration) ) { // Validate user has valid login token $user = new Document(['$id' => ID::custom(''), '$collection' => 'users']); } @@ -873,13 +873,13 @@ App::setResource('user', function ($mode, $project, $console, $request, $respons $authJWT = $request->getHeader('x-appwrite-jwt', ''); - if (!empty($authJWT) && !$project->isEmpty()) { // JWT authentication + if (! empty($authJWT) && ! $project->isEmpty()) { // JWT authentication $jwt = new JWT(App::getEnv('_APP_OPENSSL_KEY_V1'), 'HS256', 900, 10); // Instantiate with key, algo, maxAge and leeway. try { $payload = $jwt->decode($authJWT); } catch (JWTException $error) { - throw new Exception(Exception::USER_JWT_INVALID, 'Failed to verify JWT. ' . $error->getMessage()); + throw new Exception(Exception::USER_JWT_INVALID, 'Failed to verify JWT. '.$error->getMessage()); } $jwtUserId = $payload['userId'] ?? ''; @@ -901,14 +901,13 @@ App::setResource('project', function ($dbForConsole, $request, $console) { /** @var Appwrite\Utopia\Request $request */ /** @var Utopia\Database\Database $dbForConsole */ /** @var Utopia\Database\Document $console */ - $projectId = $request->getParam('project', $request->getHeader('x-appwrite-project', 'console')); if ($projectId === 'console') { return $console; } - $project = Authorization::skip(fn() => $dbForConsole->getDocument('projects', $projectId)); + $project = Authorization::skip(fn () => $dbForConsole->getDocument('projects', $projectId)); return $project; }, ['dbForConsole', 'request', 'console']); @@ -942,8 +941,8 @@ App::setResource('console', function () { 'limit' => (App::getEnv('_APP_CONSOLE_WHITELIST_ROOT', 'enabled') === 'enabled') ? 1 : 0, // limit signup to 1 user 'duration' => Auth::TOKEN_EXPIRATION_LOGIN_LONG, // 1 Year in seconds ], - 'authWhitelistEmails' => (!empty(App::getEnv('_APP_CONSOLE_WHITELIST_EMAILS', null))) ? \explode(',', App::getEnv('_APP_CONSOLE_WHITELIST_EMAILS', null)) : [], - 'authWhitelistIPs' => (!empty(App::getEnv('_APP_CONSOLE_WHITELIST_IPS', null))) ? \explode(',', App::getEnv('_APP_CONSOLE_WHITELIST_IPS', null)) : [], + 'authWhitelistEmails' => (! empty(App::getEnv('_APP_CONSOLE_WHITELIST_EMAILS', null))) ? \explode(',', App::getEnv('_APP_CONSOLE_WHITELIST_EMAILS', null)) : [], + 'authWhitelistIPs' => (! empty(App::getEnv('_APP_CONSOLE_WHITELIST_IPS', null))) ? \explode(',', App::getEnv('_APP_CONSOLE_WHITELIST_IPS', null)) : [], ]); }, []); @@ -967,21 +966,20 @@ App::setResource('dbForConsole', function ($db, $cache) { return $database; }, ['db', 'cache']); - App::setResource('deviceLocal', function () { return new Local(); }); App::setResource('deviceFiles', function ($project) { - return getDevice(APP_STORAGE_UPLOADS . '/app-' . $project->getId()); + return getDevice(APP_STORAGE_UPLOADS.'/app-'.$project->getId()); }, ['project']); App::setResource('deviceFunctions', function ($project) { - return getDevice(APP_STORAGE_FUNCTIONS . '/app-' . $project->getId()); + return getDevice(APP_STORAGE_FUNCTIONS.'/app-'.$project->getId()); }, ['project']); App::setResource('deviceBuilds', function ($project) { - return getDevice(APP_STORAGE_BUILDS . '/app-' . $project->getId()); + return getDevice(APP_STORAGE_BUILDS.'/app-'.$project->getId()); }, ['project']); function getDevice($root): Device @@ -996,6 +994,7 @@ function getDevice($root): Device $s3Region = App::getEnv('_APP_STORAGE_S3_REGION', ''); $s3Bucket = App::getEnv('_APP_STORAGE_S3_BUCKET', ''); $s3Acl = 'private'; + return new S3($root, $s3AccessKey, $s3SecretKey, $s3Bucket, $s3Region, $s3Acl); case Storage::DEVICE_DO_SPACES: $doSpacesAccessKey = App::getEnv('_APP_STORAGE_DO_SPACES_ACCESS_KEY', ''); @@ -1003,6 +1002,7 @@ function getDevice($root): Device $doSpacesRegion = App::getEnv('_APP_STORAGE_DO_SPACES_REGION', ''); $doSpacesBucket = App::getEnv('_APP_STORAGE_DO_SPACES_BUCKET', ''); $doSpacesAcl = 'private'; + return new DOSpaces($root, $doSpacesAccessKey, $doSpacesSecretKey, $doSpacesBucket, $doSpacesRegion, $doSpacesAcl); case Storage::DEVICE_BACKBLAZE: $backblazeAccessKey = App::getEnv('_APP_STORAGE_BACKBLAZE_ACCESS_KEY', ''); @@ -1010,6 +1010,7 @@ function getDevice($root): Device $backblazeRegion = App::getEnv('_APP_STORAGE_BACKBLAZE_REGION', ''); $backblazeBucket = App::getEnv('_APP_STORAGE_BACKBLAZE_BUCKET', ''); $backblazeAcl = 'private'; + return new Backblaze($root, $backblazeAccessKey, $backblazeSecretKey, $backblazeBucket, $backblazeRegion, $backblazeAcl); case Storage::DEVICE_LINODE: $linodeAccessKey = App::getEnv('_APP_STORAGE_LINODE_ACCESS_KEY', ''); @@ -1017,6 +1018,7 @@ function getDevice($root): Device $linodeRegion = App::getEnv('_APP_STORAGE_LINODE_REGION', ''); $linodeBucket = App::getEnv('_APP_STORAGE_LINODE_BUCKET', ''); $linodeAcl = 'private'; + return new Linode($root, $linodeAccessKey, $linodeSecretKey, $linodeBucket, $linodeRegion, $linodeAcl); case Storage::DEVICE_WASABI: $wasabiAccessKey = App::getEnv('_APP_STORAGE_WASABI_ACCESS_KEY', ''); @@ -1024,6 +1026,7 @@ function getDevice($root): Device $wasabiRegion = App::getEnv('_APP_STORAGE_WASABI_REGION', ''); $wasabiBucket = App::getEnv('_APP_STORAGE_WASABI_BUCKET', ''); $wasabiAcl = 'private'; + return new Wasabi($root, $wasabiAccessKey, $wasabiSecretKey, $wasabiBucket, $wasabiRegion, $wasabiAcl); } } @@ -1076,7 +1079,6 @@ App::setResource('promiseAdapter', function ($register) { }, ['register']); App::setResource('schema', function ($utopia, $dbForProject) { - $complexity = function (int $complexity, array $args) { $queries = Query::parseQueries($args['queries'] ?? []); $query = Query::getByType($queries, Query::TYPE_LIMIT)[0] ?? null; @@ -1086,7 +1088,7 @@ App::setResource('schema', function ($utopia, $dbForProject) { }; $attributes = function (int $limit, int $offset) use ($dbForProject) { - $attrs = Authorization::skip(fn() => $dbForProject->find('attributes', [ + $attrs = Authorization::skip(fn () => $dbForProject->find('attributes', [ Query::limit($limit), Query::offset($offset), ])); @@ -1116,7 +1118,7 @@ App::setResource('schema', function ($utopia, $dbForProject) { $params = [ 'list' => function (string $databaseId, string $collectionId, array $args) { - return [ 'queries' => $args['queries']]; + return ['queries' => $args['queries']]; }, 'create' => function (string $databaseId, string $collectionId, array $args) { $id = $args['id'] ?? 'unique()'; diff --git a/app/preload.php b/app/preload.php index 8789936417..126312af85 100644 --- a/app/preload.php +++ b/app/preload.php @@ -5,37 +5,35 @@ * * Inializes both Appwrite API entry point, queue workers, and CLI tasks. * Set configuration, framework resources, app constants - * */ - ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); -if (file_exists(__DIR__ . '/../vendor/autoload.php')) { - require __DIR__ . '/../vendor/autoload.php'; +if (file_exists(__DIR__.'/../vendor/autoload.php')) { + require __DIR__.'/../vendor/autoload.php'; } use Utopia\Preloader\Preloader; -include __DIR__ . '/controllers/general.php'; +include __DIR__.'/controllers/general.php'; $preloader = new Preloader(); foreach ( [ - realpath(__DIR__ . '/../vendor/composer'), - realpath(__DIR__ . '/../vendor/amphp'), - realpath(__DIR__ . '/../vendor/felixfbecker'), - realpath(__DIR__ . '/../vendor/twig/twig'), - realpath(__DIR__ . '/../vendor/guzzlehttp/guzzle'), - realpath(__DIR__ . '/../vendor/slickdeals'), - realpath(__DIR__ . '/../vendor/psr/log'), - realpath(__DIR__ . '/../vendor/matomo'), - realpath(__DIR__ . '/../vendor/symfony'), - realpath(__DIR__ . '/../vendor/mongodb'), - realpath(__DIR__ . '/../vendor/utopia-php/websocket'), // TODO: remove workerman autoload - realpath(__DIR__ . '/../vendor/utopia-php/cache'), // TODO: remove memcache autoload + realpath(__DIR__.'/../vendor/composer'), + realpath(__DIR__.'/../vendor/amphp'), + realpath(__DIR__.'/../vendor/felixfbecker'), + realpath(__DIR__.'/../vendor/twig/twig'), + realpath(__DIR__.'/../vendor/guzzlehttp/guzzle'), + realpath(__DIR__.'/../vendor/slickdeals'), + realpath(__DIR__.'/../vendor/psr/log'), + realpath(__DIR__.'/../vendor/matomo'), + realpath(__DIR__.'/../vendor/symfony'), + realpath(__DIR__.'/../vendor/mongodb'), + realpath(__DIR__.'/../vendor/utopia-php/websocket'), // TODO: remove workerman autoload + realpath(__DIR__.'/../vendor/utopia-php/cache'), // TODO: remove memcache autoload ] as $key => $value ) { if ($value !== false) { @@ -44,7 +42,7 @@ foreach ( } $preloader - ->paths(realpath(__DIR__ . '/../app/config')) - ->paths(realpath(__DIR__ . '/../app/controllers')) - ->paths(realpath(__DIR__ . '/../src')) + ->paths(realpath(__DIR__.'/../app/config')) + ->paths(realpath(__DIR__.'/../app/controllers')) + ->paths(realpath(__DIR__.'/../src')) ->load(); diff --git a/app/realtime.php b/app/realtime.php index 5ff642aea4..14e7498b50 100644 --- a/app/realtime.php +++ b/app/realtime.php @@ -3,6 +3,7 @@ use Appwrite\Auth\Auth; use Appwrite\Messaging\Adapter\Realtime; use Appwrite\Network\Validator\Origin; +use Appwrite\Utopia\Request; use Appwrite\Utopia\Response; use Swoole\Http\Request as SwooleRequest; use Swoole\Http\Response as SwooleResponse; @@ -12,24 +13,23 @@ use Swoole\Timer; use Utopia\Abuse\Abuse; use Utopia\Abuse\Adapters\TimeLimit; use Utopia\App; -use Utopia\CLI\Console; -use Utopia\Database\Helpers\ID; -use Utopia\Database\Helpers\Role; -use Utopia\Logger\Log; -use Utopia\Database\Database; -use Utopia\Database\DateTime; use Utopia\Cache\Adapter\Redis as RedisCache; use Utopia\Cache\Cache; +use Utopia\CLI\Console; use Utopia\Database\Adapter\MariaDB; +use Utopia\Database\Database; +use Utopia\Database\DateTime; use Utopia\Database\Document; +use Utopia\Database\Helpers\ID; +use Utopia\Database\Helpers\Role; use Utopia\Database\Query; use Utopia\Database\Validator\Authorization; +use Utopia\Logger\Log; use Utopia\Registry\Registry; -use Appwrite\Utopia\Request; -use Utopia\WebSocket\Server; use Utopia\WebSocket\Adapter; +use Utopia\WebSocket\Server; -require_once __DIR__ . '/init.php'; +require_once __DIR__.'/init.php'; Runtime::enableCoroutine(SWOOLE_HOOK_ALL); @@ -64,7 +64,7 @@ $logError = function (Throwable $error, string $action) use ($register) { $version = App::getEnv('_APP_VERSION', 'UNKNOWN'); $log = new Log(); - $log->setNamespace("realtime"); + $log->setNamespace('realtime'); $log->setServer(\gethostname()); $log->setVersion($version); $log->setType(Log::TYPE_ERROR); @@ -84,13 +84,13 @@ $logError = function (Throwable $error, string $action) use ($register) { $log->setEnvironment($isProduction ? Log::ENVIRONMENT_PRODUCTION : Log::ENVIRONMENT_STAGING); $responseCode = $logger->addLog($log); - Console::info('Realtime log pushed with status code: ' . $responseCode); + Console::info('Realtime log pushed with status code: '.$responseCode); } - Console::error('[Error] Type: ' . get_class($error)); - Console::error('[Error] Message: ' . $error->getMessage()); - Console::error('[Error] File: ' . $error->getFile()); - Console::error('[Error] Line: ' . $error->getLine()); + Console::error('[Error] Type: '.get_class($error)); + Console::error('[Error] Message: '.$error->getMessage()); + Console::error('[Error] File: '.$error->getFile()); + Console::error('[Error] Line: '.$error->getLine()); }; $server->error($logError); @@ -111,7 +111,7 @@ function getDatabase(Registry &$register, string $namespace) $database->setDefaultDatabase(App::getEnv('_APP_DB_SCHEMA', 'appwrite')); $database->setNamespace($namespace); - if (!$database->exists($database->getDefaultDatabase(), 'realtime')) { + if (! $database->exists($database->getDefaultDatabase(), 'realtime')) { throw new Exception('Collection not ready'); } @@ -119,7 +119,7 @@ function getDatabase(Registry &$register, string $namespace) } catch (\Throwable $e) { Console::warning("Database not ready. Retrying connection ({$attempts})..."); if ($attempts >= DATABASE_RECONNECT_MAX_ATTEMPTS) { - throw new \Exception('Failed to connect to database: ' . $e->getMessage()); + throw new \Exception('Failed to connect to database: '.$e->getMessage()); } sleep(DATABASE_RECONNECT_SLEEP); } @@ -130,7 +130,7 @@ function getDatabase(Registry &$register, string $namespace) function () use ($register, $db, $redis) { $register->get('dbPool')->put($db); $register->get('redisPool')->put($redis); - } + }, ]; } @@ -153,7 +153,7 @@ $server->onStart(function () use ($stats, $register, $containerId, &$statsDocume '$permissions' => [], 'container' => $containerId, 'timestamp' => DateTime::now(), - 'value' => '{}' + 'value' => '{}', ]); $statsDocument = Authorization::skip(fn () => $database->createDocument('realtime', $document)); @@ -187,7 +187,7 @@ $server->onStart(function () use ($stats, $register, $containerId, &$statsDocume Authorization::skip(fn () => $database->updateDocument('realtime', $statsDocument->getId(), $statsDocument)); } catch (\Throwable $th) { - call_user_func($logError, $th, "updateWorkerDocument"); + call_user_func($logError, $th, 'updateWorkerDocument'); } finally { call_user_func($returnDatabase); } @@ -195,12 +195,12 @@ $server->onStart(function () use ($stats, $register, $containerId, &$statsDocume }); $server->onWorkerStart(function (int $workerId) use ($server, $register, $stats, $realtime, $logError) { - Console::success('Worker ' . $workerId . ' started successfully'); + Console::success('Worker '.$workerId.' started successfully'); $attempts = 0; $start = time(); - Timer::tick(5000, function () use ($server, $register, $realtime, $stats, $logError) { + Timer::tick(5000, function () use ($server, $register, $realtime, $stats) { /** * Sending current connections to project channels on the console project every 5 seconds. */ @@ -219,34 +219,34 @@ $server->onWorkerStart(function (int $workerId) use ($server, $register, $stats, foreach ($list as $document) { foreach (json_decode($document->getAttribute('value')) as $projectId => $value) { if (array_key_exists($projectId, $payload)) { - $payload[$projectId] += $value; + $payload[$projectId] += $value; } else { - $payload[$projectId] = $value; + $payload[$projectId] = $value; } } } foreach ($stats as $projectId => $value) { - if (!array_key_exists($projectId, $payload)) { + if (! array_key_exists($projectId, $payload)) { continue; } $event = [ 'project' => 'console', - 'roles' => ['team:' . $stats->get($projectId, 'teamId')], + 'roles' => ['team:'.$stats->get($projectId, 'teamId')], 'data' => [ 'events' => ['stats.connections'], 'channels' => ['project'], 'timestamp' => DateTime::formatTz(DateTime::now()), 'payload' => [ - $projectId => $payload[$projectId] - ] - ] + $projectId => $payload[$projectId], + ], + ], ]; $server->send($realtime->getSubscribers($event), json_encode([ 'type' => 'event', - 'data' => $event['data'] + 'data' => $event['data'], ])); } @@ -265,13 +265,13 @@ $server->onWorkerStart(function (int $workerId) use ($server, $register, $stats, 'events' => ['test.event'], 'channels' => ['tests'], 'timestamp' => DateTime::formatTz(DateTime::now()), - 'payload' => $payload - ] + 'payload' => $payload, + ], ]; $server->send($realtime->getSubscribers($event), json_encode([ 'type' => 'event', - 'data' => $event['data'] + 'data' => $event['data'], ])); } }); @@ -279,8 +279,8 @@ $server->onWorkerStart(function (int $workerId) use ($server, $register, $stats, while ($attempts < 300) { try { if ($attempts > 0) { - Console::error('Pub/sub connection lost (lasted ' . (time() - $start) . ' seconds, worker: ' . $workerId . '). - Attempting restart in 5 seconds (attempt #' . $attempts . ')'); + Console::error('Pub/sub connection lost (lasted '.(time() - $start).' seconds, worker: '.$workerId.'). + Attempting restart in 5 seconds (attempt #'.$attempts.')'); sleep(5); // 5 sec delay between connection attempts } $start = time(); @@ -291,9 +291,9 @@ $server->onWorkerStart(function (int $workerId) use ($server, $register, $stats, if ($redis->ping(true)) { $attempts = 0; - Console::success('Pub/sub connection established (worker: ' . $workerId . ')'); + Console::success('Pub/sub connection established (worker: '.$workerId.')'); } else { - Console::error('Pub/sub failed (worker: ' . $workerId . ')'); + Console::error('Pub/sub failed (worker: '.$workerId.')'); } $redis->subscribe(['realtime'], function (Redis $redis, string $channel, string $payload) use ($server, $workerId, $stats, $register, $realtime) { @@ -303,8 +303,8 @@ $server->onWorkerStart(function (int $workerId) use ($server, $register, $stats, $projectId = $event['project']; $userId = $event['userId']; - if ($realtime->hasSubscriber($projectId, 'user:' . $userId)) { - $connection = array_key_first(reset($realtime->subscriptions[$projectId]['user:' . $userId])); + if ($realtime->hasSubscriber($projectId, 'user:'.$userId)) { + $connection = array_key_first(reset($realtime->subscriptions[$projectId]['user:'.$userId])); [$consoleDatabase, $returnConsoleDatabase] = getDatabase($register, '_console'); $project = Authorization::skip(fn () => $consoleDatabase->getDocument('projects', $projectId)); [$database, $returnDatabase] = getDatabase($register, "_{$project->getInternalId()}"); @@ -322,17 +322,17 @@ $server->onWorkerStart(function (int $workerId) use ($server, $register, $stats, $receivers = $realtime->getSubscribers($event); - if (App::isDevelopment() && !empty($receivers)) { - Console::log("[Debug][Worker {$workerId}] Receivers: " . count($receivers)); - Console::log("[Debug][Worker {$workerId}] Receivers Connection IDs: " . json_encode($receivers)); - Console::log("[Debug][Worker {$workerId}] Event: " . $payload); + if (App::isDevelopment() && ! empty($receivers)) { + Console::log("[Debug][Worker {$workerId}] Receivers: ".count($receivers)); + Console::log("[Debug][Worker {$workerId}] Receivers Connection IDs: ".json_encode($receivers)); + Console::log("[Debug][Worker {$workerId}] Event: ".$payload); } $server->send( $receivers, json_encode([ 'type' => 'event', - 'data' => $event['data'] + 'data' => $event['data'], ]) ); @@ -341,12 +341,13 @@ $server->onWorkerStart(function (int $workerId) use ($server, $register, $stats, } }); } catch (\Throwable $th) { - call_user_func($logError, $th, "pubSubConnection"); + call_user_func($logError, $th, 'pubSubConnection'); - Console::error('Pub/sub error: ' . $th->getMessage()); + Console::error('Pub/sub error: '.$th->getMessage()); $register->get('redisPool')->put($redis); $attempts++; sleep(DATABASE_RECONNECT_SLEEP); + continue; } } @@ -417,7 +418,7 @@ $server->onOpen(function (int $connection, SwooleRequest $request) use ($server, $origin = $request->getOrigin(); $originValidator = new Origin(\array_merge($project->getAttribute('platforms', []), $console->getAttribute('platforms', []))); - if (!$originValidator->isValid($origin) && $project->getId() !== 'console') { + if (! $originValidator->isValid($origin) && $project->getId() !== 'console') { throw new Exception($originValidator->getDescription(), 1008); } @@ -440,25 +441,25 @@ $server->onOpen(function (int $connection, SwooleRequest $request) use ($server, 'type' => 'connected', 'data' => [ 'channels' => array_keys($channels), - 'user' => $user - ] + 'user' => $user, + ], ])); $stats->set($project->getId(), [ 'projectId' => $project->getId(), - 'teamId' => $project->getAttribute('teamId') + 'teamId' => $project->getAttribute('teamId'), ]); $stats->incr($project->getId(), 'connections'); $stats->incr($project->getId(), 'connectionsTotal'); } catch (\Throwable $th) { - call_user_func($logError, $th, "initServer"); + call_user_func($logError, $th, 'initServer'); $response = [ 'type' => 'error', 'data' => [ 'code' => $th->getCode(), - 'message' => $th->getMessage() - ] + 'message' => $th->getMessage(), + ], ]; $server->send([$connection], json_encode($response)); @@ -466,8 +467,8 @@ $server->onOpen(function (int $connection, SwooleRequest $request) use ($server, if (App::isDevelopment()) { Console::error('[Error] Connection Error'); - Console::error('[Error] Code: ' . $response['data']['code']); - Console::error('[Error] Message: ' . $response['data']['message']); + Console::error('[Error] Code: '.$response['data']['code']); + Console::error('[Error] Message: '.$response['data']['message']); } if ($th instanceof PDOException) { @@ -492,7 +493,7 @@ $server->onMessage(function (int $connection, string $message) use ($server, $re $cache = new Cache(new RedisCache($redis)); $database = new Database(new MariaDB($db), $cache); $database->setDefaultDatabase(App::getEnv('_APP_DB_SCHEMA', 'appwrite')); - $database->setNamespace("_console"); + $database->setNamespace('_console'); $projectId = $realtime->connections[$connection]['projectId']; $project = $projectId === 'console' ? $app->getResource('console') : Authorization::skip(fn () => $database->getDocument('projects', $projectId)); $database->setNamespace("_{$project->getInternalId()}"); @@ -515,16 +516,16 @@ $server->onMessage(function (int $connection, string $message) use ($server, $re $message = json_decode($message, true); - if (is_null($message) || (!array_key_exists('type', $message) && !array_key_exists('data', $message))) { + if (is_null($message) || (! array_key_exists('type', $message) && ! array_key_exists('data', $message))) { throw new Exception('Message format is not valid.', 1003); } switch ($message['type']) { - /** + /** * This type is used to authenticate. */ case 'authentication': - if (!array_key_exists('session', $message['data'])) { + if (! array_key_exists('session', $message['data'])) { throw new Exception('Payload is not valid.', 1003); } @@ -537,7 +538,7 @@ $server->onMessage(function (int $connection, string $message) use ($server, $re if ( empty($user->getId()) // Check a document has been found in the DB - || !Auth::sessionVerify($user->getAttribute('sessions', []), Auth::$secret, $authDuration) // Validate user has valid login token + || ! Auth::sessionVerify($user->getAttribute('sessions', []), Auth::$secret, $authDuration) // Validate user has valid login token ) { // cookie not valid throw new Exception('Session is not valid.', 1003); @@ -553,8 +554,8 @@ $server->onMessage(function (int $connection, string $message) use ($server, $re 'data' => [ 'to' => 'authentication', 'success' => true, - 'user' => $user - ] + 'user' => $user, + ], ])); break; @@ -568,8 +569,8 @@ $server->onMessage(function (int $connection, string $message) use ($server, $re 'type' => 'error', 'data' => [ 'code' => $th->getCode(), - 'message' => $th->getMessage() - ] + 'message' => $th->getMessage(), + ], ]; $server->send([$connection], json_encode($response)); @@ -589,7 +590,7 @@ $server->onClose(function (int $connection) use ($realtime, $stats) { } $realtime->unsubscribe($connection); - Console::info('Connection close: ' . $connection); + Console::info('Connection close: '.$connection); }); $server->start(); diff --git a/app/tasks/doctor.php b/app/tasks/doctor.php index d79e8d530f..4f4bbceff1 100644 --- a/app/tasks/doctor.php +++ b/app/tasks/doctor.php @@ -3,12 +3,12 @@ global $cli; use Appwrite\ClamAV\Network; -use Utopia\Logger\Logger; -use Utopia\Storage\Device\Local; -use Utopia\Storage\Storage; use Utopia\App; use Utopia\CLI\Console; use Utopia\Domains\Domain; +use Utopia\Logger\Logger; +use Utopia\Storage\Device\Local; +use Utopia\Storage\Storage; $cli ->task('doctor') @@ -19,24 +19,24 @@ $cli / \ ) __/ ) __/\ /\ / ) / )( )( ) _) _ )(( O ) \_/\_/(__) (__) (_/\_)(__\_)(__) (__) (____)(_)(__)\__/ "); - Console::log("\n" . '👩‍⚕️ Running ' . APP_NAME . ' Doctor for version ' . App::getEnv('_APP_VERSION', 'UNKNOWN') . ' ...' . "\n"); + Console::log("\n".'👩‍⚕️ Running '.APP_NAME.' Doctor for version '.App::getEnv('_APP_VERSION', 'UNKNOWN').' ...'."\n"); Console::log('Checking for production best practices...'); $domain = new Domain(App::getEnv('_APP_DOMAIN')); - if (!$domain->isKnown() || $domain->isTest()) { - Console::log('🔴 Hostname has no public suffix (' . $domain->get() . ')'); + if (! $domain->isKnown() || $domain->isTest()) { + Console::log('🔴 Hostname has no public suffix ('.$domain->get().')'); } else { - Console::log('🟢 Hostname has a public suffix (' . $domain->get() . ')'); + Console::log('🟢 Hostname has a public suffix ('.$domain->get().')'); } $domain = new Domain(App::getEnv('_APP_DOMAIN_TARGET')); - if (!$domain->isKnown() || $domain->isTest()) { - Console::log('🔴 CNAME target has no public suffix (' . $domain->get() . ')'); + if (! $domain->isKnown() || $domain->isTest()) { + Console::log('🔴 CNAME target has no public suffix ('.$domain->get().')'); } else { - Console::log('🟢 CNAME target has a public suffix (' . $domain->get() . ')'); + Console::log('🟢 CNAME target has a public suffix ('.$domain->get().')'); } if (App::getEnv('_APP_OPENSSL_KEY_V1') === 'your-secret-key' || empty(App::getEnv('_APP_OPENSSL_KEY_V1'))) { @@ -77,20 +77,19 @@ $cli Console::log('🟢 HTTPS force option is enabled'); } - $providerName = App::getEnv('_APP_LOGGING_PROVIDER', ''); $providerConfig = App::getEnv('_APP_LOGGING_CONFIG', ''); - if (empty($providerName) || empty($providerConfig) || !Logger::hasProvider($providerName)) { + if (empty($providerName) || empty($providerConfig) || ! Logger::hasProvider($providerName)) { Console::log('🔴 Logging adapter is disabled'); } else { - Console::log('🟢 Logging adapter is enabled (' . $providerName . ')'); + Console::log('🟢 Logging adapter is enabled ('.$providerName.')'); } \sleep(0.2); try { - Console::log("\n" . 'Checking connectivity...'); + Console::log("\n".'Checking connectivity...'); } catch (\Throwable $th) { //throw $th; } @@ -150,7 +149,7 @@ $cli $host = App::getEnv('_APP_STATSD_HOST', 'telegraf'); $port = App::getEnv('_APP_STATSD_PORT', 8125); - if ($fp = @\fsockopen('udp://' . $host, $port, $errCode, $errStr, 2)) { + if ($fp = @\fsockopen('udp://'.$host, $port, $errCode, $errStr, 2)) { Console::success('StatsD..............connected 👍'); \fclose($fp); } else { @@ -174,24 +173,24 @@ $cli foreach ( [ - 'Uploads' => APP_STORAGE_UPLOADS, - 'Cache' => APP_STORAGE_CACHE, - 'Config' => APP_STORAGE_CONFIG, - 'Certs' => APP_STORAGE_CERTIFICATES + 'Uploads' => APP_STORAGE_UPLOADS, + 'Cache' => APP_STORAGE_CACHE, + 'Config' => APP_STORAGE_CONFIG, + 'Certs' => APP_STORAGE_CERTIFICATES, ] as $key => $volume ) { $device = new Local($volume); if (\is_readable($device->getRoot())) { - Console::success('🟢 ' . $key . ' Volume is readable'); + Console::success('🟢 '.$key.' Volume is readable'); } else { - Console::error('🔴 ' . $key . ' Volume is unreadable'); + Console::error('🔴 '.$key.' Volume is unreadable'); } if (\is_writable($device->getRoot())) { - Console::success('🟢 ' . $key . ' Volume is writeable'); + Console::success('🟢 '.$key.' Volume is writeable'); } else { - Console::error('🔴 ' . $key . ' Volume is unwriteable'); + Console::error('🔴 '.$key.' Volume is unwriteable'); } } @@ -202,10 +201,10 @@ $cli foreach ( [ - 'Uploads' => APP_STORAGE_UPLOADS, - 'Cache' => APP_STORAGE_CACHE, - 'Config' => APP_STORAGE_CONFIG, - 'Certs' => APP_STORAGE_CERTIFICATES + 'Uploads' => APP_STORAGE_UPLOADS, + 'Cache' => APP_STORAGE_CACHE, + 'Config' => APP_STORAGE_CONFIG, + 'Certs' => APP_STORAGE_CERTIFICATES, ] as $key => $volume ) { $device = new Local($volume); @@ -213,31 +212,31 @@ $cli $percentage = (($device->getPartitionTotalSpace() - $device->getPartitionFreeSpace()) / $device->getPartitionTotalSpace()) * 100; - $message = $key . ' Volume has ' . Storage::human($device->getPartitionFreeSpace()) . ' free space (' . \round($percentage, 2) . '% used)'; + $message = $key.' Volume has '.Storage::human($device->getPartitionFreeSpace()).' free space ('.\round($percentage, 2).'% used)'; if ($percentage < 80) { - Console::success('🟢 ' . $message); + Console::success('🟢 '.$message); } else { - Console::error('🔴 ' . $message); + Console::error('🔴 '.$message); } } try { if (App::isProduction()) { Console::log(''); - $version = \json_decode(@\file_get_contents(App::getEnv('_APP_HOME', 'http://localhost') . '/v1/health/version'), true); + $version = \json_decode(@\file_get_contents(App::getEnv('_APP_HOME', 'http://localhost').'/v1/health/version'), true); if ($version && isset($version['version'])) { if (\version_compare($version['version'], App::getEnv('_APP_VERSION', 'UNKNOWN')) === 0) { - Console::info('You are running the latest version of ' . APP_NAME . '! 🥳'); + Console::info('You are running the latest version of '.APP_NAME.'! 🥳'); } else { - Console::info('A new version (' . $version['version'] . ') is available! 🥳' . "\n"); + Console::info('A new version ('.$version['version'].') is available! 🥳'."\n"); } } else { - Console::error('Failed to check for a newer version' . "\n"); + Console::error('Failed to check for a newer version'."\n"); } } } catch (\Throwable $th) { - Console::error('Failed to check for a newer version' . "\n"); + Console::error('Failed to check for a newer version'."\n"); } }); diff --git a/app/tasks/install.php b/app/tasks/install.php index 3519b58d0b..e2a68b7029 100644 --- a/app/tasks/install.php +++ b/app/tasks/install.php @@ -57,19 +57,19 @@ $cli Console::success('Starting Appwrite installation...'); // Create directory with write permissions - if (null !== $path && !\file_exists(\dirname($path))) { - if (!@\mkdir(\dirname($path), 0755, true)) { - Console::error('Can\'t create directory ' . \dirname($path)); + if (null !== $path && ! \file_exists(\dirname($path))) { + if (! @\mkdir(\dirname($path), 0755, true)) { + Console::error('Can\'t create directory '.\dirname($path)); Console::exit(1); } } - $data = @file_get_contents($path . '/docker-compose.yml'); + $data = @file_get_contents($path.'/docker-compose.yml'); if ($data !== false) { $time = \time(); - Console::info('Compose file found, creating backup: docker-compose.yml.' . $time . '.backup'); - file_put_contents($path . '/docker-compose.yml.' . $time . '.backup', $data); + Console::info('Compose file found, creating backup: docker-compose.yml.'.$time.'.backup'); + file_put_contents($path.'/docker-compose.yml.'.$time.'.backup', $data); $compose = new Compose($data); $appwrite = $compose->getService('appwrite'); $oldVersion = ($appwrite) ? $appwrite->getImageVersion() : null; @@ -78,14 +78,14 @@ $cli } catch (\Throwable $th) { $ports = [ $defaultHTTPPort => $defaultHTTPPort, - $defaultHTTPSPort => $defaultHTTPSPort + $defaultHTTPSPort => $defaultHTTPSPort, ]; Console::warning('Traefik not found. Falling back to default ports.'); } if ($oldVersion) { foreach ($compose->getServices() as $service) { // Fetch all env vars from previous compose file - if (!$service) { + if (! $service) { continue; } @@ -103,11 +103,11 @@ $cli } } - $data = @file_get_contents($path . '/.env'); + $data = @file_get_contents($path.'/.env'); if ($data !== false) { // Fetch all env vars from previous .env file - Console::info('Env file found, creating backup: .env.' . $time . '.backup'); - file_put_contents($path . '/.env.' . $time . '.backup', $data); + Console::info('Env file found, creating backup: .env.'.$time.'.backup'); + file_put_contents($path.'/.env.'.$time.'.backup', $data); $env = new Env($data); foreach ($env->list() as $key => $value) { @@ -135,40 +135,44 @@ $cli } if (empty($httpPort)) { - $httpPort = Console::confirm('Choose your server HTTP port: (default: ' . $defaultHTTPPort . ')'); + $httpPort = Console::confirm('Choose your server HTTP port: (default: '.$defaultHTTPPort.')'); $httpPort = ($httpPort) ? $httpPort : $defaultHTTPPort; } if (empty($httpsPort)) { - $httpsPort = Console::confirm('Choose your server HTTPS port: (default: ' . $defaultHTTPSPort . ')'); + $httpsPort = Console::confirm('Choose your server HTTPS port: (default: '.$defaultHTTPSPort.')'); $httpsPort = ($httpsPort) ? $httpsPort : $defaultHTTPSPort; } $input = []; foreach ($vars as $key => $var) { - if (!empty($var['filter']) && ($interactive !== 'Y' || !Console::isInteractive())) { + if (! empty($var['filter']) && ($interactive !== 'Y' || ! Console::isInteractive())) { if ($data && $var['default'] !== null) { $input[$var['name']] = $var['default']; + continue; } if ($var['filter'] === 'token') { $input[$var['name']] = Auth::tokenGenerator(); + continue; } if ($var['filter'] === 'password') { $input[$var['name']] = Auth::passwordGenerator(); + continue; } } - if (!$var['required'] || !Console::isInteractive() || $interactive !== 'Y') { + if (! $var['required'] || ! Console::isInteractive() || $interactive !== 'Y') { $input[$var['name']] = $var['default']; + continue; } - $input[$var['name']] = Console::confirm($var['question'] . ' (default: \'' . $var['default'] . '\')'); + $input[$var['name']] = Console::confirm($var['question'].' (default: \''.$var['default'].'\')'); if (empty($input[$var['name']])) { $input[$var['name']] = $var['default']; @@ -178,38 +182,36 @@ $cli if ($input[$var['name']] !== 'localhost') { Console::warning("\nIf you haven't already done so, set the following record for {$input[$var['name']]} on your DNS provider:\n"); $mask = "%-15.15s %-10.10s %-30.30s\n"; - printf($mask, "Type", "Name", "Value"); - printf($mask, "A or AAAA", "@", ""); + printf($mask, 'Type', 'Name', 'Value'); + printf($mask, 'A or AAAA', '@', ''); Console::warning("\nUse 'AAAA' if you're using an IPv6 address and 'A' if you're using an IPv4 address.\n"); } } } - $templateForCompose = new View(__DIR__ . '/../views/install/compose.phtml'); - $templateForEnv = new View(__DIR__ . '/../views/install/env.phtml'); + $templateForCompose = new View(__DIR__.'/../views/install/compose.phtml'); + $templateForEnv = new View(__DIR__.'/../views/install/env.phtml'); $templateForCompose ->setParam('httpPort', $httpPort) ->setParam('httpsPort', $httpsPort) ->setParam('version', APP_VERSION_STABLE) ->setParam('organization', $organization) - ->setParam('image', $image) - ; + ->setParam('image', $image); $templateForEnv - ->setParam('vars', $input) - ; + ->setParam('vars', $input); - if (!file_put_contents($path . '/docker-compose.yml', $templateForCompose->render(false))) { + if (! file_put_contents($path.'/docker-compose.yml', $templateForCompose->render(false))) { $message = 'Failed to save Docker Compose file'; - $analytics->createEvent('install/server', 'install', APP_VERSION_STABLE . ' - ' . $message); + $analytics->createEvent('install/server', 'install', APP_VERSION_STABLE.' - '.$message); Console::error($message); Console::exit(1); } - if (!file_put_contents($path . '/.env', $templateForEnv->render(false))) { + if (! file_put_contents($path.'/.env', $templateForEnv->render(false))) { $message = 'Failed to save environment variables file'; - $analytics->createEvent('install/server', 'install', APP_VERSION_STABLE . ' - ' . $message); + $analytics->createEvent('install/server', 'install', APP_VERSION_STABLE.' - '.$message); Console::error($message); Console::exit(1); } @@ -220,7 +222,7 @@ $cli foreach ($input as $key => $value) { if ($value) { - $env .= $key . '=' . \escapeshellarg($value) . ' '; + $env .= $key.'='.\escapeshellarg($value).' '; } } @@ -230,13 +232,13 @@ $cli if ($exit !== 0) { $message = 'Failed to install Appwrite dockers'; - $analytics->createEvent('install/server', 'install', APP_VERSION_STABLE . ' - ' . $message); + $analytics->createEvent('install/server', 'install', APP_VERSION_STABLE.' - '.$message); Console::error($message); Console::error($stderr); Console::exit($exit); } else { $message = 'Appwrite installed successfully'; - $analytics->createEvent('install/server', 'install', APP_VERSION_STABLE . ' - ' . $message); + $analytics->createEvent('install/server', 'install', APP_VERSION_STABLE.' - '.$message); Console::success($message); } }); diff --git a/app/tasks/maintenance.php b/app/tasks/maintenance.php index 7199a338e3..f1551fc164 100644 --- a/app/tasks/maintenance.php +++ b/app/tasks/maintenance.php @@ -3,16 +3,15 @@ global $cli; global $register; -use Appwrite\Auth\Auth; use Appwrite\Event\Certificate; use Appwrite\Event\Delete; use Utopia\App; +use Utopia\Cache\Adapter\Redis as RedisCache; use Utopia\Cache\Cache; use Utopia\CLI\Console; use Utopia\Database\Adapter\MariaDB; use Utopia\Database\Database; use Utopia\Database\DateTime; -use Utopia\Cache\Adapter\Redis as RedisCache; use Utopia\Database\Document; use Utopia\Database\Query; @@ -30,7 +29,7 @@ function getConsoleDB(): Database $database->setDefaultDatabase(App::getEnv('_APP_DB_SCHEMA', 'appwrite')); $database->setNamespace('_console'); // Main DB - if (!$database->exists($database->getDefaultDatabase(), 'certificates')) { + if (! $database->exists($database->getDefaultDatabase(), 'certificates')) { throw new \Exception('Console project not ready'); } @@ -38,7 +37,7 @@ function getConsoleDB(): Database } catch (\Exception $e) { Console::warning("Database not ready. Retrying connection ({$attempts})..."); if ($attempts >= DATABASE_RECONNECT_MAX_ATTEMPTS) { - throw new \Exception('Failed to connect to database: ' . $e->getMessage()); + throw new \Exception('Failed to connect to database: '.$e->getMessage()); } sleep(DATABASE_RECONNECT_SLEEP); } @@ -52,7 +51,7 @@ $cli ->desc('Schedules maintenance tasks and publishes them to resque') ->action(function () { Console::title('Maintenance V1'); - Console::success(APP_NAME . ' maintenance process v1 has started'); + Console::success(APP_NAME.' maintenance process v1 has started'); function notifyDeleteExecutionLogs(int $interval) { @@ -106,20 +105,19 @@ $cli $time = DateTime::now(); $certificates = $dbForConsole->find('certificates', [ - Query::lessThan('attempts', 5), // Maximum 5 attempts - Query::lessThanEqual('renewDate', $time), // includes 60 days cooldown (we have 30 days to renew) - Query::limit(200), // Limit 200 comes from LetsEncrypt (300 orders per 3 hours, keeping some for new domains) + Query::lessThan('attempts', 5), // Maximum 5 attempts + Query::lessThanEqual('renewDate', $time), // includes 60 days cooldown (we have 30 days to renew) + Query::limit(200), // Limit 200 comes from LetsEncrypt (300 orders per 3 hours, keeping some for new domains) ]); - if (\count($certificates) > 0) { - Console::info("[{$time}] Found " . \count($certificates) . " certificates for renewal, scheduling jobs."); + Console::info("[{$time}] Found ".\count($certificates).' certificates for renewal, scheduling jobs.'); $event = new Certificate(); foreach ($certificates as $certificate) { $event ->setDomain(new Document([ - 'domain' => $certificate->getAttribute('domain') + 'domain' => $certificate->getAttribute('domain'), ])) ->trigger(); } @@ -130,7 +128,6 @@ $cli function notifyDeleteCache($interval) { - (new Delete()) ->setType(DELETE_TYPE_CACHE_BY_TIMESTAMP) ->setDatetime(DateTime::addSeconds(new \DateTime(), -1 * $interval)) diff --git a/app/tasks/migrate.php b/app/tasks/migrate.php index 1d155c210d..0e96c85823 100644 --- a/app/tasks/migrate.php +++ b/app/tasks/migrate.php @@ -2,11 +2,11 @@ global $cli, $register; -use Utopia\CLI\Console; use Appwrite\Migration\Migration; use Utopia\App; -use Utopia\Cache\Cache; use Utopia\Cache\Adapter\Redis as RedisCache; +use Utopia\Cache\Cache; +use Utopia\CLI\Console; use Utopia\Database\Adapter\MariaDB; use Utopia\Database\Database; use Utopia\Database\Document; @@ -19,7 +19,7 @@ function clearProjectsCache(Redis $redis, Document $project) try { $redis->del($redis->keys("cache-_{$project->getInternalId()}:*")); } catch (\Throwable $th) { - Console::error('Failed to clear project ("' . $project->getId() . '") cache with error: ' . $th->getMessage()); + Console::error('Failed to clear project ("'.$project->getId().'") cache with error: '.$th->getMessage()); } } @@ -28,15 +28,16 @@ $cli ->param('version', APP_VERSION_STABLE, new Text(32), 'Version to migrate to.', true) ->action(function ($version) use ($register) { Authorization::disable(); - if (!array_key_exists($version, Migration::$versions)) { + if (! array_key_exists($version, Migration::$versions)) { Console::error("Version {$version} not found."); Console::exit(1); + return; } $app = new App('UTC'); - Console::success('Starting Data Migration to version ' . $version); + Console::success('Starting Data Migration to version '.$version); $db = $register->get('db', true); $redis = $register->get('cache', true); @@ -68,10 +69,10 @@ $cli $totalProjects = $consoleDB->count('projects') + 1; } - $class = 'Appwrite\\Migration\\Version\\' . Migration::$versions[$version]; + $class = 'Appwrite\\Migration\\Version\\'.Migration::$versions[$version]; $migration = new $class(); - while (!empty($projects)) { + while (! empty($projects)) { foreach ($projects as $project) { /** * Skip user projects with id 'console' @@ -88,7 +89,7 @@ $cli ->execute(); } catch (\Throwable $th) { throw $th; - Console::error('Failed to update project ("' . $project->getId() . '") version with error: ' . $th->getMessage()); + Console::error('Failed to update project ("'.$project->getId().'") version with error: '.$th->getMessage()); } clearProjectsCache($redis, $project); @@ -100,7 +101,7 @@ $cli $offset = $offset + $limit; $count = $count + $sum; - Console::log('Migrated ' . $count . '/' . $totalProjects . ' projects...'); + Console::log('Migrated '.$count.'/'.$totalProjects.' projects...'); } Swoole\Event::wait(); // Wait for Coroutines to finish diff --git a/app/tasks/sdks.php b/app/tasks/sdks.php index bc9aab7a41..8ba1cfe0d4 100644 --- a/app/tasks/sdks.php +++ b/app/tasks/sdks.php @@ -1,6 +1,7 @@ task('sdks') ->action(function () { $platforms = Config::getParam('platforms'); - $selectedPlatform = Console::confirm('Choose Platform ("' . APP_PLATFORM_CLIENT . '", "' . APP_PLATFORM_SERVER . '", "' . APP_PLATFORM_CONSOLE . '" or "*" for all):'); + $selectedPlatform = Console::confirm('Choose Platform ("'.APP_PLATFORM_CLIENT.'", "'.APP_PLATFORM_SERVER.'", "'.APP_PLATFORM_CONSOLE.'" or "*" for all):'); $selectedSDK = \strtolower(Console::confirm('Choose SDK ("*" for all):')); $version = Console::confirm('Choose an Appwrite version'); $git = (Console::confirm('Should we use git push? (yes/no)') == 'yes'); $production = ($git) ? (Console::confirm('Type "Appwrite" to push code to production git repos') == 'Appwrite') : false; $message = ($git) ? Console::confirm('Please enter your commit message:') : ''; - if (!in_array($version, ['0.6.x', '0.7.x', '0.8.x', '0.9.x', '0.10.x', '0.11.x', '0.12.x', '0.13.x', '0.14.x', '0.15.x', '1.0.x', '1.1.x', '1.2.x', 'latest'])) { + if (! in_array($version, ['0.6.x', '0.7.x', '0.8.x', '0.9.x', '0.10.x', '0.11.x', '0.12.x', '0.13.x', '0.14.x', '0.15.x', '1.0.x', '1.1.x', '1.2.x', 'latest'])) { throw new Exception('Unknown version given'); } @@ -47,30 +47,31 @@ $cli continue; } - if (!$language['enabled']) { - Console::warning($language['name'] . ' for ' . $platform['name'] . ' is disabled'); + if (! $language['enabled']) { + Console::warning($language['name'].' for '.$platform['name'].' is disabled'); + continue; } - Console::info('Fetching API Spec for ' . $language['name'] . ' for ' . $platform['name'] . ' (version: ' . $version . ')'); + Console::info('Fetching API Spec for '.$language['name'].' for '.$platform['name'].' (version: '.$version.')'); - $spec = file_get_contents(__DIR__ . '/../config/specs/swagger2-' . $version . '-' . $language['family'] . '.json'); + $spec = file_get_contents(__DIR__.'/../config/specs/swagger2-'.$version.'-'.$language['family'].'.json'); $cover = 'https://appwrite.io/images/github.png'; - $result = \realpath(__DIR__ . '/..') . '/sdks/' . $key . '-' . $language['key']; - $resultExamples = \realpath(__DIR__ . '/../..') . '/docs/examples/' . $version . '/' . $key . '-' . $language['key']; - $target = \realpath(__DIR__ . '/..') . '/sdks/git/' . $language['key'] . '/'; - $readme = \realpath(__DIR__ . '/../../docs/sdks/' . $language['key'] . '/README.md'); + $result = \realpath(__DIR__.'/..').'/sdks/'.$key.'-'.$language['key']; + $resultExamples = \realpath(__DIR__.'/../..').'/docs/examples/'.$version.'/'.$key.'-'.$language['key']; + $target = \realpath(__DIR__.'/..').'/sdks/git/'.$language['key'].'/'; + $readme = \realpath(__DIR__.'/../../docs/sdks/'.$language['key'].'/README.md'); $readme = ($readme) ? \file_get_contents($readme) : ''; - $gettingStarted = \realpath(__DIR__ . '/../../docs/sdks/' . $language['key'] . '/GETTING_STARTED.md'); + $gettingStarted = \realpath(__DIR__.'/../../docs/sdks/'.$language['key'].'/GETTING_STARTED.md'); $gettingStarted = ($gettingStarted) ? \file_get_contents($gettingStarted) : ''; - $examples = \realpath(__DIR__ . '/../../docs/sdks/' . $language['key'] . '/EXAMPLES.md'); + $examples = \realpath(__DIR__.'/../../docs/sdks/'.$language['key'].'/EXAMPLES.md'); $examples = ($examples) ? \file_get_contents($examples) : ''; - $changelog = \realpath(__DIR__ . '/../../docs/sdks/' . $language['key'] . '/CHANGELOG.md'); + $changelog = \realpath(__DIR__.'/../../docs/sdks/'.$language['key'].'/CHANGELOG.md'); $changelog = ($changelog) ? \file_get_contents($changelog) : '# Change Log'; - $warning = '**This SDK is compatible with Appwrite server version ' . $version . '. For older versions, please check [previous releases](' . $language['url'] . '/releases).**'; + $warning = '**This SDK is compatible with Appwrite server version '.$version.'. For older versions, please check [previous releases]('.$language['url'].'/releases).**'; $license = 'BSD-3-Clause'; - $licenseContent = 'Copyright (c) ' . date('Y') . ' Appwrite (https://appwrite.io) and individual contributors. + $licenseContent = 'Copyright (c) '.date('Y').' Appwrite (https://appwrite.io) and individual contributors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -124,7 +125,7 @@ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND $config = new Node(); $config->setNPMPackage('node-appwrite'); $config->setBowerPackage('appwrite'); - $warning = $warning . "\n\n > This is the Node.js SDK for integrating with Appwrite from your Node.js server-side code. + $warning = $warning."\n\n > This is the Node.js SDK for integrating with Appwrite from your Node.js server-side code. If you're looking to integrate from the browser, you should check [appwrite/sdk-for-web](https://github.com/appwrite/sdk-for-web)"; break; case 'deno': @@ -150,14 +151,14 @@ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND case 'dart': $config = new Dart(); $config->setPackageName('dart_appwrite'); - $warning = $warning . "\n\n > This is the Dart SDK for integrating with Appwrite from your Dart server-side code. If you're looking for the Flutter SDK you should check [appwrite/sdk-for-flutter](https://github.com/appwrite/sdk-for-flutter)"; + $warning = $warning."\n\n > This is the Dart SDK for integrating with Appwrite from your Dart server-side code. If you're looking for the Flutter SDK you should check [appwrite/sdk-for-flutter](https://github.com/appwrite/sdk-for-flutter)"; break; case 'go': $config = new Go(); break; case 'swift': $config = new Swift(); - $warning = $warning . "\n\n > This is the Swift SDK for integrating with Appwrite from your Swift server-side code. If you're looking for the Apple SDK you should check [appwrite/sdk-for-apple](https://github.com/appwrite/sdk-for-apple)"; + $warning = $warning."\n\n > This is the Swift SDK for integrating with Appwrite from your Swift server-side code. If you're looking for the Apple SDK you should check [appwrite/sdk-for-apple](https://github.com/appwrite/sdk-for-apple)"; break; case 'apple': $config = new Apple(); @@ -171,7 +172,7 @@ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND break; case 'kotlin': $config = new Kotlin(); - $warning = $warning . "\n\n > This is the Kotlin SDK for integrating with Appwrite from your Kotlin server-side code. If you're looking for the Android SDK you should check [appwrite/sdk-for-android](https://github.com/appwrite/sdk-for-android)"; + $warning = $warning."\n\n > This is the Kotlin SDK for integrating with Appwrite from your Kotlin server-side code. If you're looking for the Android SDK you should check [appwrite/sdk-for-android](https://github.com/appwrite/sdk-for-android)"; break; case 'graphql': $config = new GraphQL(); @@ -180,7 +181,7 @@ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND $config = new REST(); break; default: - throw new Exception('Language "' . $language['key'] . '" not supported'); + throw new Exception('Language "'.$language['key'].'" not supported'); } Console::info("Generating {$language['name']} SDK..."); @@ -228,29 +229,28 @@ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND $gitUrl = $language['gitUrl']; $gitBranch = $language['gitBranch']; - - if (!$production) { - $gitUrl = 'git@github.com:aw-tests/' . $language['gitRepoName'] . '.git'; + if (! $production) { + $gitUrl = 'git@github.com:aw-tests/'.$language['gitRepoName'].'.git'; } - if ($git && !empty($gitUrl)) { - \exec('rm -rf ' . $target . ' && \ - mkdir -p ' . $target . ' && \ - cd ' . $target . ' && \ - git init --initial-branch=' . $gitBranch . ' && \ - git remote add origin ' . $gitUrl . ' && \ + if ($git && ! empty($gitUrl)) { + \exec('rm -rf '.$target.' && \ + mkdir -p '.$target.' && \ + cd '.$target.' && \ + git init --initial-branch='.$gitBranch.' && \ + git remote add origin '.$gitUrl.' && \ git fetch && \ - git pull ' . $gitUrl . ' && \ - rm -rf ' . $target . '/* && \ - cp -r ' . $result . '/* ' . $target . '/ && \ + git pull '.$gitUrl.' && \ + rm -rf '.$target.'/* && \ + cp -r '.$result.'/* '.$target.'/ && \ git add . && \ - git commit -m "' . $message . '" && \ - git push -u origin ' . $gitBranch . ' + git commit -m "'.$message.'" && \ + git push -u origin '.$gitBranch.' '); Console::success("Pushed {$language['name']} SDK to {$gitUrl}"); - \exec('rm -rf ' . $target); + \exec('rm -rf '.$target); Console::success("Remove temp directory '{$target}' for {$language['name']} SDK"); } @@ -261,10 +261,10 @@ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND } foreach ($docDirectories as $languageTitle => $path) { - $languagePath = strtolower($languageTitle !== 0 ? '/' . $languageTitle : ''); + $languagePath = strtolower($languageTitle !== 0 ? '/'.$languageTitle : ''); \exec( - 'mkdir -p ' . $resultExamples . $languagePath . ' && \ - cp -r ' . $result . '/docs/examples' . $languagePath . ' ' . $resultExamples + 'mkdir -p '.$resultExamples.$languagePath.' && \ + cp -r '.$result.'/docs/examples'.$languagePath.' '.$resultExamples ); Console::success("Copied code examples for {$language['name']} SDK to: {$resultExamples}"); } diff --git a/app/tasks/specs.php b/app/tasks/specs.php index 57c6bf29e1..7d7a6e111b 100644 --- a/app/tasks/specs.php +++ b/app/tasks/specs.php @@ -2,7 +2,6 @@ global $cli; -use Utopia\Validator\Text; use Appwrite\Specification\Format\OpenAPI3; use Appwrite\Specification\Format\Swagger2; use Appwrite\Specification\Specification; @@ -12,6 +11,7 @@ use Utopia\App; use Utopia\CLI\Console; use Utopia\Config\Config; use Utopia\Request; +use Utopia\Validator\Text; use Utopia\Validator\WhiteList; $cli @@ -155,15 +155,15 @@ $cli $sdkPlaforms[] = APP_PLATFORM_CLIENT; } - if (!$route->getLabel('docs', true)) { + if (! $route->getLabel('docs', true)) { continue; } - if ($route->getLabel('sdk.mock', false) && !$mocks) { + if ($route->getLabel('sdk.mock', false) && ! $mocks) { continue; } - if (!$route->getLabel('sdk.mock', false) && $mocks) { + if (! $route->getLabel('sdk.mock', false) && $mocks) { continue; } @@ -171,7 +171,7 @@ $cli continue; } - if ($platform !== APP_PLATFORM_CONSOLE && !\in_array($platforms[$platform], $sdkPlaforms)) { + if ($platform !== APP_PLATFORM_CONSOLE && ! \in_array($platforms[$platform], $sdkPlaforms)) { continue; } @@ -181,10 +181,10 @@ $cli foreach (Config::getParam('services', []) as $service) { if ( - !isset($service['docs']) // Skip service if not part of the public API - || !isset($service['sdk']) - || !$service['docs'] - || !$service['sdk'] + ! isset($service['docs']) // Skip service if not part of the public API + || ! isset($service['sdk']) + || ! $service['docs'] + || ! $service['sdk'] ) { continue; } @@ -199,7 +199,7 @@ $cli $models = $response->getModels(); foreach ($models as $key => $value) { - if ($platform !== APP_PLATFORM_CONSOLE && !$value->isPublic()) { + if ($platform !== APP_PLATFORM_CONSOLE && ! $value->isPublic()) { unset($models[$key]); } } @@ -209,7 +209,7 @@ $cli $formatInstance = match ($format) { 'swagger2' => new Swagger2(...$arguments), 'open-api3' => new OpenAPI3(...$arguments), - default => throw new Exception('Format not found: ' . $format) + default => throw new Exception('Format not found: '.$format) }; $specs = new Specification($formatInstance); @@ -221,36 +221,36 @@ $cli ->setParam('description', 'Appwrite backend as a service cuts up to 70% of the time and costs required for building a modern application. We abstract and simplify common development tasks behind a REST APIs, to help you develop your app in a fast and secure way. For full API documentation and tutorials go to [https://appwrite.io/docs](https://appwrite.io/docs)') ->setParam('endpoint', 'https://HOSTNAME/v1') ->setParam('version', APP_VERSION_STABLE) - ->setParam('terms', $endpoint . '/policy/terms') + ->setParam('terms', $endpoint.'/policy/terms') ->setParam('support.email', $email) - ->setParam('support.url', $endpoint . '/support') - ->setParam('contact.name', APP_NAME . ' Team') + ->setParam('support.url', $endpoint.'/support') + ->setParam('contact.name', APP_NAME.' Team') ->setParam('contact.email', $email) - ->setParam('contact.url', $endpoint . '/support') + ->setParam('contact.url', $endpoint.'/support') ->setParam('license.name', 'BSD-3-Clause') ->setParam('license.url', 'https://raw.githubusercontent.com/appwrite/appwrite/master/LICENSE') ->setParam('docs.description', 'Full API docs, specs and tutorials') - ->setParam('docs.url', $endpoint . '/docs'); + ->setParam('docs.url', $endpoint.'/docs'); if ($mocks) { - $path = __DIR__ . '/../config/specs/' . $format . '-mocks-' . $platform . '.json'; + $path = __DIR__.'/../config/specs/'.$format.'-mocks-'.$platform.'.json'; - if (!file_put_contents($path, json_encode($specs->parse()))) { - throw new Exception('Failed to save mocks spec file: ' . $path); + if (! file_put_contents($path, json_encode($specs->parse()))) { + throw new Exception('Failed to save mocks spec file: '.$path); } - Console::success('Saved mocks spec file: ' . realpath($path)); + Console::success('Saved mocks spec file: '.realpath($path)); continue; } - $path = __DIR__ . '/../config/specs/' . $format . '-' . $version . '-' . $platform . '.json'; + $path = __DIR__.'/../config/specs/'.$format.'-'.$version.'-'.$platform.'.json'; - if (!file_put_contents($path, json_encode($specs->parse()))) { - throw new Exception('Failed to save spec file: ' . $path); + if (! file_put_contents($path, json_encode($specs->parse()))) { + throw new Exception('Failed to save spec file: '.$path); } - Console::success('Saved spec file: ' . realpath($path)); + Console::success('Saved spec file: '.realpath($path)); } } }); diff --git a/app/tasks/ssl.php b/app/tasks/ssl.php index 345da1f22e..770129a94d 100644 --- a/app/tasks/ssl.php +++ b/app/tasks/ssl.php @@ -13,11 +13,11 @@ $cli ->desc('Validate server certificates') ->param('domain', App::getEnv('_APP_DOMAIN', ''), new Hostname(), 'Domain to generate certificate for. If empty, main domain will be used.', true) ->action(function ($domain) { - Console::success('Scheduling a job to issue a TLS certificate for domain: ' . $domain); + Console::success('Scheduling a job to issue a TLS certificate for domain: '.$domain); (new Certificate()) ->setDomain(new Document([ - 'domain' => $domain + 'domain' => $domain, ])) ->setSkipRenewCheck(true) ->trigger(); diff --git a/app/tasks/usage.php b/app/tasks/usage.php index d940dd5e49..554845ee85 100644 --- a/app/tasks/usage.php +++ b/app/tasks/usage.php @@ -11,9 +11,8 @@ use Utopia\CLI\Console; use Utopia\Database\Adapter\MariaDB; use Utopia\Database\Database as UtopiaDatabase; use Utopia\Database\Validator\Authorization; -use Utopia\Registry\Registry; use Utopia\Logger\Log; -use Utopia\Validator\WhiteList; +use Utopia\Registry\Registry; Authorization::disable(); Authorization::setDefaultStatus(false); @@ -34,14 +33,14 @@ function getDatabase(Registry &$register, string $namespace): UtopiaDatabase $database->setDefaultDatabase(App::getEnv('_APP_DB_SCHEMA', 'appwrite')); $database->setNamespace($namespace); - if (!$database->exists($database->getDefaultDatabase(), 'projects')) { + if (! $database->exists($database->getDefaultDatabase(), 'projects')) { throw new Exception('Projects collection not ready'); } break; // leave loop if successful } catch (\Exception $e) { Console::warning("Database not ready. Retrying connection ({$attempts})..."); if ($attempts >= DATABASE_RECONNECT_MAX_ATTEMPTS) { - throw new \Exception('Failed to connect to database: ' . $e->getMessage()); + throw new \Exception('Failed to connect to database: '.$e->getMessage()); } sleep(DATABASE_RECONNECT_SLEEP); } @@ -73,6 +72,7 @@ function getInfluxDB(Registry &$register): InfluxDatabase sleep($sleep); } } while ($attempts < $max); + return $database; } @@ -83,7 +83,7 @@ $logError = function (Throwable $error, string $action = 'syncUsageStats') use ( $version = App::getEnv('_APP_VERSION', 'UNKNOWN'); $log = new Log(); - $log->setNamespace("usage"); + $log->setNamespace('usage'); $log->setServer(\gethostname()); $log->setVersion($version); $log->setType(Log::TYPE_ERROR); @@ -103,7 +103,7 @@ $logError = function (Throwable $error, string $action = 'syncUsageStats') use ( $log->setEnvironment($isProduction ? Log::ENVIRONMENT_PRODUCTION : Log::ENVIRONMENT_STAGING); $responseCode = $logger->addLog($log); - Console::info('Usage stats log pushed with status code: ' . $responseCode); + Console::info('Usage stats log pushed with status code: '.$responseCode); } Console::warning("Failed: {$error->getMessage()}"); @@ -115,7 +115,7 @@ $cli ->desc('Schedules syncing data from influxdb to Appwrite console db') ->action(function () use ($register, $logError) { Console::title('Usage Aggregation V1'); - Console::success(APP_NAME . ' usage aggregation process v1 has started'); + Console::success(APP_NAME.' usage aggregation process v1 has started'); $database = getDatabase($register, '_console'); $influxDB = getInfluxDB($register); diff --git a/app/tasks/vars.php b/app/tasks/vars.php index af972e218d..41422018cd 100644 --- a/app/tasks/vars.php +++ b/app/tasks/vars.php @@ -20,6 +20,6 @@ $cli } foreach ($vars as $key => $value) { - Console::log('- ' . $value['name'] . '=' . App::getEnv($value['name'], '')); + Console::log('- '.$value['name'].'='.App::getEnv($value['name'], '')); } }); diff --git a/app/workers/audits.php b/app/workers/audits.php index b25430ec41..bfcddc8d92 100644 --- a/app/workers/audits.php +++ b/app/workers/audits.php @@ -6,16 +6,16 @@ use Utopia\Audit\Audit; use Utopia\CLI\Console; use Utopia\Database\Document; -require_once __DIR__ . '/../init.php'; +require_once __DIR__.'/../init.php'; Console::title('Audits V1 Worker'); -Console::success(APP_NAME . ' audits worker v1 has started'); +Console::success(APP_NAME.' audits worker v1 has started'); class AuditsV1 extends Worker { public function getName(): string { - return "audits"; + return 'audits'; } public function init(): void diff --git a/app/workers/builds.php b/app/workers/builds.php index 93a77d5347..828305a30e 100644 --- a/app/workers/builds.php +++ b/app/workers/builds.php @@ -3,24 +3,22 @@ use Appwrite\Event\Event; use Appwrite\Messaging\Adapter\Realtime; use Appwrite\Resque\Worker; +use Appwrite\Usage\Stats; use Appwrite\Utopia\Response\Model\Deployment; use Cron\CronExpression; use Executor\Executor; -use Appwrite\Usage\Stats; -use Utopia\Database\Database; -use Utopia\Database\DateTime; use Utopia\App; use Utopia\CLI\Console; +use Utopia\Config\Config; +use Utopia\Database\DateTime; +use Utopia\Database\Document; use Utopia\Database\Helpers\ID; use Utopia\Storage\Storage; -use Utopia\Database\Document; -use Utopia\Config\Config; -use Utopia\Database\Query; -require_once __DIR__ . '/../init.php'; +require_once __DIR__.'/../init.php'; Console::title('Builds V1 Worker'); -Console::success(APP_NAME . ' build worker v1 has started'); +Console::success(APP_NAME.' build worker v1 has started'); // TODO: Executor should return appropriate response codes. class BuildsV1 extends Worker @@ -29,7 +27,7 @@ class BuildsV1 extends Worker public function getName(): string { - return "builds"; + return 'builds'; } public function init(): void @@ -47,7 +45,7 @@ class BuildsV1 extends Worker switch ($type) { case BUILD_TYPE_DEPLOYMENT: case BUILD_TYPE_RETRY: - Console::info('Creating build for deployment: ' . $deployment->getId()); + Console::info('Creating build for deployment: '.$deployment->getId()); $this->buildDeployment($project, $resource, $deployment); break; @@ -75,7 +73,7 @@ class BuildsV1 extends Worker $key = $function->getAttribute('runtime'); $runtime = isset($runtimes[$key]) ? $runtimes[$key] : null; if (\is_null($runtime)) { - throw new Exception('Runtime "' . $function->getAttribute('runtime', '') . '" is not supported'); + throw new Exception('Runtime "'.$function->getAttribute('runtime', '').'" is not supported'); } $buildId = $deployment->getAttribute('buildId', ''); @@ -95,7 +93,7 @@ class BuildsV1 extends Worker 'stdout' => '', 'stderr' => '', 'endTime' => null, - 'duration' => 0 + 'duration' => 0, ])); $deployment->setAttribute('buildId', $buildId); $deployment = $dbForProject->updateDocument('deployments', $deployment->getId(), $deployment); @@ -128,7 +126,7 @@ class BuildsV1 extends Worker /** Trigger Realtime */ $allEvents = Event::generateEvents('functions.[functionId].deployments.[deploymentId].update', [ 'functionId' => $function->getId(), - 'deploymentId' => $deployment->getId() + 'deploymentId' => $deployment->getId(), ]); $target = Realtime::fromPayload( // Pass first, most verbose event pattern @@ -149,6 +147,7 @@ class BuildsV1 extends Worker $vars = array_reduce($function['vars'] ?? [], function (array $carry, Document $var) { $carry[$var->getAttribute('key')] = $var->getAttribute('value'); + return $carry; }, []); @@ -160,7 +159,7 @@ class BuildsV1 extends Worker deploymentId: $deployment->getId(), entrypoint: $deployment->getAttribute('entrypoint'), source: $source, - destination: APP_STORAGE_BUILDS . "/app-{$project->getId()}", + destination: APP_STORAGE_BUILDS."/app-{$project->getId()}", vars: $vars, runtime: $key, baseImage: $baseImage, @@ -169,7 +168,7 @@ class BuildsV1 extends Worker commands: [ 'sh', '-c', 'tar -zxf /tmp/code.tar.gz -C /usr/code && \ - cd /usr/local/src/ && ./build.sh' + cd /usr/local/src/ && ./build.sh', ] ); @@ -194,8 +193,8 @@ class BuildsV1 extends Worker /** Update function schedule */ $schedule = $function->getAttribute('schedule', ''); - $cron = (empty($function->getAttribute('deployment')) && !empty($schedule)) ? new CronExpression($schedule) : null; - $next = (empty($function->getAttribute('deployment')) && !empty($schedule)) ? DateTime::format($cron->getNextRunDate()) : null; + $cron = (empty($function->getAttribute('deployment')) && ! empty($schedule)) ? new CronExpression($schedule) : null; + $next = (empty($function->getAttribute('deployment')) && ! empty($schedule)) ? DateTime::format($cron->getNextRunDate()) : null; $function->setAttribute('scheduleNext', $next); $function = $dbForProject->updateDocument('functions', $function->getId(), $function); } catch (\Throwable $th) { diff --git a/app/workers/certificates.php b/app/workers/certificates.php index 33752215b8..2cb488760d 100644 --- a/app/workers/certificates.php +++ b/app/workers/certificates.php @@ -1,6 +1,5 @@ dbForConsole = $this->getConsoleDB(); $skipCheck = $this->args['skipRenewCheck'] ?? false; // If true, we won't double-check expiry from cert file @@ -80,7 +78,7 @@ class CertificatesV1 extends Worker $certificate = $this->dbForConsole->findOne('certificates', [Query::equal('domain', [$domain->get()])]); // If we don't have certificate for domain yet, let's create new document. At the end we save it - if (!$certificate) { + if (! $certificate) { $certificate = new Document(); $certificate->setAttribute('domain', $domain->get()); } @@ -93,14 +91,14 @@ class CertificatesV1 extends Worker } // Validate domain and DNS records. Skip if job is forced - if (!$skipCheck) { + if (! $skipCheck) { $mainDomain = $this->getMainDomain(); - $isMainDomain = !isset($mainDomain) || $domain->get() === $mainDomain; + $isMainDomain = ! isset($mainDomain) || $domain->get() === $mainDomain; $this->validateDomain($domain, $isMainDomain); } // If certificate exists already, double-check expiry date. Skip if job is forced - if (!$skipCheck && !$this->isRenewRequired($domain->get())) { + if (! $skipCheck && ! $this->isRenewRequired($domain->get())) { throw new Exception('Renew isn\'t required.'); } @@ -153,16 +151,15 @@ class CertificatesV1 extends Worker /** * Save certificate data into database. * - * @param string $domain Domain name that certificate is for - * @param Document $certificate Certificate document that we need to save - * + * @param string $domain Domain name that certificate is for + * @param Document $certificate Certificate document that we need to save * @return void */ private function saveCertificateDocument(string $domain, Document $certificate): void { // Check if update or insert required $certificateDocument = $this->dbForConsole->findOne('certificates', [Query::equal('domain', [$domain])]); - if (!empty($certificateDocument) && !$certificateDocument->isEmpty()) { + if (! empty($certificateDocument) && ! $certificateDocument->isEmpty()) { // Merge new data with current data $certificate = new Document(\array_merge($certificateDocument->getArrayCopy(), $certificate->getArrayCopy())); @@ -183,7 +180,7 @@ class CertificatesV1 extends Worker private function getMainDomain(): ?string { $envDomain = App::getEnv('_APP_DOMAIN', ''); - if (!empty($envDomain) && $envDomain !== 'localhost') { + if (! empty($envDomain) && $envDomain !== 'localhost') { return $envDomain; } else { $domainDocument = $this->dbForConsole->findOne('domains', [Query::orderAsc('_id')]); @@ -200,9 +197,8 @@ class CertificatesV1 extends Worker * - Domain needs to be public and valid (prevents NFT domains that are not supported by Let's Encrypt) * - Domain must have proper DNS record * - * @param Domain $domain Domain which we validate - * @param bool $isMainDomain In case of master domain, we look for different DNS configurations - * + * @param Domain $domain Domain which we validate + * @param bool $isMainDomain In case of master domain, we look for different DNS configurations * @return void */ private function validateDomain(Domain $domain, bool $isMainDomain): void @@ -211,23 +207,23 @@ class CertificatesV1 extends Worker throw new Exception('Missing certificate domain.'); } - if (!$domain->isKnown() || $domain->isTest()) { + if (! $domain->isKnown() || $domain->isTest()) { throw new Exception('Unknown public suffix for domain.'); } - if (!$isMainDomain) { + if (! $isMainDomain) { // TODO: Would be awesome to also support A/AAAA records here. Maybe dry run? // Validate if domain target is properly configured $target = new Domain(App::getEnv('_APP_DOMAIN_TARGET', '')); - if (!$target->isKnown() || $target->isTest()) { - throw new Exception('Unreachable CNAME target (' . $target->get() . '), please use a domain with a public suffix.'); + if (! $target->isKnown() || $target->isTest()) { + throw new Exception('Unreachable CNAME target ('.$target->get().'), please use a domain with a public suffix.'); } // Verify domain with DNS records $validator = new CNAME($target->get()); - if (!$validator->isValid($domain->get())) { + if (! $validator->isValid($domain->get())) { throw new Exception('Failed to verify domain DNS records.'); } } else { @@ -239,13 +235,12 @@ class CertificatesV1 extends Worker /** * Reads expiry date of certificate from file and decides if renewal is required or not. * - * @param string $domain Domain for which we check certificate file - * + * @param string $domain Domain for which we check certificate file * @return bool True, if certificate needs to be renewed */ private function isRenewRequired(string $domain): bool { - $certPath = APP_STORAGE_CERTIFICATES . '/' . $domain . '/cert.pem'; + $certPath = APP_STORAGE_CERTIFICATES.'/'.$domain.'/cert.pem'; if (\file_exists($certPath)) { $validTo = null; @@ -269,9 +264,8 @@ class CertificatesV1 extends Worker /** * LetsEncrypt communication to issue certificate (using certbot CLI) * - * @param string $folder Folder into which certificates should be generated - * @param string $domain Domain to generate certificate for - * + * @param string $folder Folder into which certificates should be generated + * @param string $domain Domain to generate certificate for * @return array Named array with keys 'stdout' and 'stderr', both string */ private function issueCertificate(string $folder, string $domain, string $email): array @@ -281,83 +275,82 @@ class CertificatesV1 extends Worker $staging = (App::isProduction()) ? '' : ' --dry-run'; $exit = Console::execute("certbot certonly --webroot --noninteractive --agree-tos{$staging}" - . " --email " . $email - . " --cert-name " . $folder - . " -w " . APP_STORAGE_CERTIFICATES - . " -d {$domain}", '', $stdout, $stderr); + .' --email '.$email + .' --cert-name '.$folder + .' -w '.APP_STORAGE_CERTIFICATES + ." -d {$domain}", '', $stdout, $stderr); // Unexpected error, usually 5XX, API limits, ... if ($exit !== 0) { - throw new Exception('Failed to issue a certificate with message: ' . $stderr); + throw new Exception('Failed to issue a certificate with message: '.$stderr); } return [ 'stdout' => $stdout, - 'stderr' => $stderr + 'stderr' => $stderr, ]; } /** * Read new renew date from certificate file generated by Let's Encrypt * - * @param string $domain Domain which certificate was generated for - * + * @param string $domain Domain which certificate was generated for * @return string */ private function getRenewDate(string $domain): string { - $certPath = APP_STORAGE_CERTIFICATES . '/' . $domain . '/cert.pem'; + $certPath = APP_STORAGE_CERTIFICATES.'/'.$domain.'/cert.pem'; $certData = openssl_x509_parse(file_get_contents($certPath)); $validTo = $certData['validTo_time_t'] ?? null; $dt = (new \DateTime())->setTimestamp($validTo); + return DateTime::addSeconds($dt, -60 * 60 * 24 * 30); // -30 days } /** * Method to take files from Let's Encrypt, and put it into Traefik. * - * @param string $domain Domain which certificate was generated for - * @param string $folder Folder in which certificates were generated - * @param array $letsEncryptData Let's Encrypt logs to use for additional info when throwing error - * + * @param string $domain Domain which certificate was generated for + * @param string $folder Folder in which certificates were generated + * @param array $letsEncryptData Let's Encrypt logs to use for additional info when throwing error * @return void */ private function applyCertificateFiles(string $folder, string $domain, array $letsEncryptData): void { // Prepare folder in storage for domain - $path = APP_STORAGE_CERTIFICATES . '/' . $domain; - if (!\is_readable($path)) { - if (!\mkdir($path, 0755, true)) { + $path = APP_STORAGE_CERTIFICATES.'/'.$domain; + if (! \is_readable($path)) { + if (! \mkdir($path, 0755, true)) { throw new Exception('Failed to create path for certificate.'); } } // Move generated files - if (!@\rename('/etc/letsencrypt/live/' . $folder . '/cert.pem', APP_STORAGE_CERTIFICATES . '/' . $domain . '/cert.pem')) { - throw new Exception('Failed to rename certificate cert.pem. Let\'s Encrypt log: ' . $letsEncryptData['stderr'] . ' ; ' . $letsEncryptData['stdout']); + if (! @\rename('/etc/letsencrypt/live/'.$folder.'/cert.pem', APP_STORAGE_CERTIFICATES.'/'.$domain.'/cert.pem')) { + throw new Exception('Failed to rename certificate cert.pem. Let\'s Encrypt log: '.$letsEncryptData['stderr'].' ; '.$letsEncryptData['stdout']); } - if (!@\rename('/etc/letsencrypt/live/' . $folder . '/chain.pem', APP_STORAGE_CERTIFICATES . '/' . $domain . '/chain.pem')) { - throw new Exception('Failed to rename certificate chain.pem. Let\'s Encrypt log: ' . $letsEncryptData['stderr'] . ' ; ' . $letsEncryptData['stdout']); + if (! @\rename('/etc/letsencrypt/live/'.$folder.'/chain.pem', APP_STORAGE_CERTIFICATES.'/'.$domain.'/chain.pem')) { + throw new Exception('Failed to rename certificate chain.pem. Let\'s Encrypt log: '.$letsEncryptData['stderr'].' ; '.$letsEncryptData['stdout']); } - if (!@\rename('/etc/letsencrypt/live/' . $folder . '/fullchain.pem', APP_STORAGE_CERTIFICATES . '/' . $domain . '/fullchain.pem')) { - throw new Exception('Failed to rename certificate fullchain.pem. Let\'s Encrypt log: ' . $letsEncryptData['stderr'] . ' ; ' . $letsEncryptData['stdout']); + if (! @\rename('/etc/letsencrypt/live/'.$folder.'/fullchain.pem', APP_STORAGE_CERTIFICATES.'/'.$domain.'/fullchain.pem')) { + throw new Exception('Failed to rename certificate fullchain.pem. Let\'s Encrypt log: '.$letsEncryptData['stderr'].' ; '.$letsEncryptData['stdout']); } - if (!@\rename('/etc/letsencrypt/live/' . $folder . '/privkey.pem', APP_STORAGE_CERTIFICATES . '/' . $domain . '/privkey.pem')) { - throw new Exception('Failed to rename certificate privkey.pem. Let\'s Encrypt log: ' . $letsEncryptData['stderr'] . ' ; ' . $letsEncryptData['stdout']); + if (! @\rename('/etc/letsencrypt/live/'.$folder.'/privkey.pem', APP_STORAGE_CERTIFICATES.'/'.$domain.'/privkey.pem')) { + throw new Exception('Failed to rename certificate privkey.pem. Let\'s Encrypt log: '.$letsEncryptData['stderr'].' ; '.$letsEncryptData['stdout']); } $config = \implode(PHP_EOL, [ - "tls:", - " certificates:", + 'tls:', + ' certificates:', " - certFile: /storage/certificates/{$domain}/fullchain.pem", - " keyFile: /storage/certificates/{$domain}/privkey.pem" + " keyFile: /storage/certificates/{$domain}/privkey.pem", ]); // Save configuration into Traefik using our new cert files - if (!\file_put_contents(APP_STORAGE_CONFIG . '/' . $domain . '.yml', $config)) { + if (! \file_put_contents(APP_STORAGE_CONFIG.'/'.$domain.'.yml', $config)) { throw new Exception('Failed to save Traefik configuration.'); } } @@ -365,39 +358,38 @@ class CertificatesV1 extends Worker /** * Method to make sure information about error is delivered to admnistrator. * - * @param string $domain Domain that caused the error - * @param string $errorMessage Verbose error message - * @param int $attempt How many times it failed already - * + * @param string $domain Domain that caused the error + * @param string $errorMessage Verbose error message + * @param int $attempt How many times it failed already * @return void */ private function notifyError(string $domain, string $errorMessage, int $attempt): void { // Log error into console - Console::warning('Cannot renew domain (' . $domain . ') on attempt no. ' . $attempt . ' certificate: ' . $errorMessage); + Console::warning('Cannot renew domain ('.$domain.') on attempt no. '.$attempt.' certificate: '.$errorMessage); // Send mail to administratore mail $locale = new Locale(App::getEnv('_APP_LOCALE', 'en')); - if (!$locale->getText('emails.sender') || !$locale->getText("emails.certificate.hello") || !$locale->getText("emails.certificate.subject") || !$locale->getText("emails.certificate.body") || !$locale->getText("emails.certificate.footer") || !$locale->getText("emails.certificate.thanks") || !$locale->getText("emails.certificate.signature")) { + if (! $locale->getText('emails.sender') || ! $locale->getText('emails.certificate.hello') || ! $locale->getText('emails.certificate.subject') || ! $locale->getText('emails.certificate.body') || ! $locale->getText('emails.certificate.footer') || ! $locale->getText('emails.certificate.thanks') || ! $locale->getText('emails.certificate.signature')) { $locale->setDefault('en'); } - $body = Template::fromFile(__DIR__ . '/../../config/locale/templates/email-base.tpl'); + $body = Template::fromFile(__DIR__.'/../../config/locale/templates/email-base.tpl'); - $subject = \sprintf($locale->getText("emails.certificate.subject"), $domain); - $body->setParam('{{domain}}', $domain); - $body->setParam('{{error}}', $errorMessage); - $body->setParam('{{attempt}}', $attempt); + $subject = \sprintf($locale->getText('emails.certificate.subject'), $domain); + $body->setParam('{{domain}}', $domain); + $body->setParam('{{error}}', $errorMessage); + $body->setParam('{{attempt}}', $attempt); $body ->setParam('{{subject}}', $subject) - ->setParam('{{hello}}', $locale->getText("emails.certificate.hello")) - ->setParam('{{body}}', $locale->getText("emails.certificate.body")) - ->setParam('{{redirect}}', 'https://' . $domain) - ->setParam('{{footer}}', $locale->getText("emails.certificate.footer")) - ->setParam('{{thanks}}', $locale->getText("emails.certificate.thanks")) - ->setParam('{{signature}}', $locale->getText("emails.certificate.signature")) + ->setParam('{{hello}}', $locale->getText('emails.certificate.hello')) + ->setParam('{{body}}', $locale->getText('emails.certificate.body')) + ->setParam('{{redirect}}', 'https://'.$domain) + ->setParam('{{footer}}', $locale->getText('emails.certificate.footer')) + ->setParam('{{thanks}}', $locale->getText('emails.certificate.thanks')) + ->setParam('{{signature}}', $locale->getText('emails.certificate.signature')) ->setParam('{{project}}', 'Console') ->setParam('{{direction}}', $locale->getText('settings.direction')) ->setParam('{{bg-body}}', '#f7f7f7') @@ -419,9 +411,8 @@ class CertificatesV1 extends Worker * - when renew creates new document? It might? * - overall makes it more reliable * - * @param string $certificateId ID of a new or updated certificate document - * @param string $domain Domain that is affected by new certificate - * + * @param string $certificateId ID of a new or updated certificate document + * @param string $domain Domain that is affected by new certificate * @return void */ private function updateDomainDocuments(string $certificateId, string $domain): void diff --git a/app/workers/databases.php b/app/workers/databases.php index 71e78b3777..6347d2227e 100644 --- a/app/workers/databases.php +++ b/app/workers/databases.php @@ -6,10 +6,10 @@ use Appwrite\Resque\Worker; use Utopia\CLI\Console; use Utopia\Database\Document; -require_once __DIR__ . '/../init.php'; +require_once __DIR__.'/../init.php'; Console::title('Database V1 Worker'); -Console::success(APP_NAME . ' database worker v1 has started' . "\n"); +Console::success(APP_NAME.' database worker v1 has started'."\n"); class DatabaseV1 extends Worker { @@ -48,7 +48,7 @@ class DatabaseV1 extends Worker break; default: - Console::error('No database operation for type: ' . $type); + Console::error('No database operation for type: '.$type); break; } } @@ -58,10 +58,10 @@ class DatabaseV1 extends Worker } /** - * @param Document $database - * @param Document $collection - * @param Document $attribute - * @param string $projectId + * @param Document $database + * @param Document $collection + * @param Document $attribute + * @param string $projectId */ protected function createAttribute(Document $database, Document $collection, Document $attribute, string $projectId): void { @@ -71,7 +71,7 @@ class DatabaseV1 extends Worker $events = Event::generateEvents('databases.[databaseId].collections.[collectionId].attributes.[attributeId].update', [ 'databaseId' => $database->getId(), 'collectionId' => $collection->getId(), - 'attributeId' => $attribute->getId() + 'attributeId' => $attribute->getId(), ]); /** * Fetch attribute from the database, since with Resque float values are loosing informations. @@ -92,7 +92,7 @@ class DatabaseV1 extends Worker $project = $dbForConsole->getDocument('projects', $projectId); try { - if (!$dbForProject->createAttribute('database_' . $database->getInternalId() . '_collection_' . $collection->getInternalId(), $key, $type, $size, $required, $default, $signed, $array, $format, $formatOptions, $filters)) { + if (! $dbForProject->createAttribute('database_'.$database->getInternalId().'_collection_'.$collection->getInternalId(), $key, $type, $size, $required, $default, $signed, $array, $format, $formatOptions, $filters)) { throw new Exception('Failed to create Attribute'); } $dbForProject->updateDocument('attributes', $attribute->getId(), $attribute->setAttribute('status', 'available')); @@ -116,19 +116,19 @@ class DatabaseV1 extends Worker options: [ 'projectId' => $projectId, 'databaseId' => $database->getId(), - 'collectionId' => $collection->getId() + 'collectionId' => $collection->getId(), ] ); } - $dbForProject->deleteCachedDocument('database_' . $database->getInternalId(), $collectionId); + $dbForProject->deleteCachedDocument('database_'.$database->getInternalId(), $collectionId); } /** - * @param Document $database - * @param Document $collection - * @param Document $attribute - * @param string $projectId + * @param Document $database + * @param Document $collection + * @param Document $attribute + * @param string $projectId */ protected function deleteAttribute(Document $database, Document $collection, Document $attribute, string $projectId): void { @@ -138,7 +138,7 @@ class DatabaseV1 extends Worker $events = Event::generateEvents('databases.[databaseId].collections.[collectionId].attributes.[attributeId].delete', [ 'databaseId' => $database->getId(), 'collectionId' => $collection->getId(), - 'attributeId' => $attribute->getId() + 'attributeId' => $attribute->getId(), ]); $collectionId = $collection->getId(); $key = $attribute->getAttribute('key', ''); @@ -152,7 +152,7 @@ class DatabaseV1 extends Worker // - failed: attribute was never created // - stuck: attribute was available but cannot be removed try { - if ($status !== 'failed' && !$dbForProject->deleteAttribute('database_' . $database->getInternalId() . '_collection_' . $collection->getInternalId(), $key)) { + if ($status !== 'failed' && ! $dbForProject->deleteAttribute('database_'.$database->getInternalId().'_collection_'.$collection->getInternalId(), $key)) { throw new Exception('Failed to delete Attribute'); } $dbForProject->deleteDocument('attributes', $attribute->getId()); @@ -176,7 +176,7 @@ class DatabaseV1 extends Worker options: [ 'projectId' => $projectId, 'databaseId' => $database->getId(), - 'collectionId' => $collection->getId() + 'collectionId' => $collection->getId(), ] ); } @@ -208,8 +208,7 @@ class DatabaseV1 extends Worker $index ->setAttribute('attributes', $attributes, Document::SET_TYPE_ASSIGN) ->setAttribute('lengths', $lengths, Document::SET_TYPE_ASSIGN) - ->setAttribute('orders', $orders, Document::SET_TYPE_ASSIGN) - ; + ->setAttribute('orders', $orders, Document::SET_TYPE_ASSIGN); // Check if an index exists with the same attributes and orders $exists = false; @@ -233,15 +232,15 @@ class DatabaseV1 extends Worker } } - $dbForProject->deleteCachedDocument('database_' . $database->getInternalId(), $collectionId); - $dbForProject->deleteCachedCollection('database_' . $database->getInternalId() . '_collection_' . $collection->getInternalId()); + $dbForProject->deleteCachedDocument('database_'.$database->getInternalId(), $collectionId); + $dbForProject->deleteCachedCollection('database_'.$database->getInternalId().'_collection_'.$collection->getInternalId()); } /** - * @param Document $database - * @param Document $collection - * @param Document $index - * @param string $projectId + * @param Document $database + * @param Document $collection + * @param Document $index + * @param string $projectId */ protected function createIndex(Document $database, Document $collection, Document $index, string $projectId): void { @@ -251,7 +250,7 @@ class DatabaseV1 extends Worker $events = Event::generateEvents('databases.[databaseId].collections.[collectionId].indexes.[indexId].update', [ 'databaseId' => $database->getId(), 'collectionId' => $collection->getId(), - 'indexId' => $index->getId() + 'indexId' => $index->getId(), ]); $collectionId = $collection->getId(); $key = $index->getAttribute('key', ''); @@ -262,7 +261,7 @@ class DatabaseV1 extends Worker $project = $dbForConsole->getDocument('projects', $projectId); try { - if (!$dbForProject->createIndex('database_' . $database->getInternalId() . '_collection_' . $collection->getInternalId(), $key, $type, $attributes, $lengths, $orders)) { + if (! $dbForProject->createIndex('database_'.$database->getInternalId().'_collection_'.$collection->getInternalId(), $key, $type, $attributes, $lengths, $orders)) { throw new Exception('Failed to create Index'); } $dbForProject->updateDocument('indexes', $index->getId(), $index->setAttribute('status', 'available')); @@ -286,19 +285,19 @@ class DatabaseV1 extends Worker options: [ 'projectId' => $projectId, 'databaseId' => $database->getId(), - 'collectionId' => $collection->getId() + 'collectionId' => $collection->getId(), ] ); } - $dbForProject->deleteCachedDocument('database_' . $database->getInternalId(), $collectionId); + $dbForProject->deleteCachedDocument('database_'.$database->getInternalId(), $collectionId); } /** - * @param Document $database - * @param Document $collection - * @param Document $index - * @param string $projectId + * @param Document $database + * @param Document $collection + * @param Document $index + * @param string $projectId */ protected function deleteIndex(Document $database, Document $collection, Document $index, string $projectId): void { @@ -308,14 +307,14 @@ class DatabaseV1 extends Worker $events = Event::generateEvents('databases.[databaseId].collections.[collectionId].indexes.[indexId].delete', [ 'databaseId' => $database->getId(), 'collectionId' => $collection->getId(), - 'indexId' => $index->getId() + 'indexId' => $index->getId(), ]); $key = $index->getAttribute('key'); $status = $index->getAttribute('status', ''); $project = $dbForConsole->getDocument('projects', $projectId); try { - if ($status !== 'failed' && !$dbForProject->deleteIndex('database_' . $database->getInternalId() . '_collection_' . $collection->getInternalId(), $key)) { + if ($status !== 'failed' && ! $dbForProject->deleteIndex('database_'.$database->getInternalId().'_collection_'.$collection->getInternalId(), $key)) { throw new Exception('Failed to delete index'); } $dbForProject->deleteDocument('indexes', $index->getId()); @@ -339,11 +338,11 @@ class DatabaseV1 extends Worker options: [ 'projectId' => $projectId, 'databaseId' => $database->getId(), - 'collectionId' => $collection->getId() + 'collectionId' => $collection->getId(), ] ); } - $dbForProject->deleteCachedDocument('database_' . $database->getInternalId(), $collection->getId()); + $dbForProject->deleteCachedDocument('database_'.$database->getInternalId(), $collection->getId()); } } diff --git a/app/workers/deletes.php b/app/workers/deletes.php index 111889318a..c570dd908a 100644 --- a/app/workers/deletes.php +++ b/app/workers/deletes.php @@ -1,31 +1,30 @@ deleteCollection($document, $project->getId()); break; } - Console::error('No lazy delete operation available for document of type: ' . $document->getCollection()); + Console::error('No lazy delete operation available for document of type: '.$document->getCollection()); break; } break; @@ -78,14 +77,14 @@ class DeletesV1 extends Worker case DELETE_TYPE_AUDIT: $datetime = $this->args['datetime'] ?? null; - if (!empty($datetime)) { + if (! empty($datetime)) { $this->deleteAuditLogs($datetime); } $document = new Document($this->args['document'] ?? []); - if (!$document->isEmpty()) { - $this->deleteAuditLogsByResource('document/' . $document->getId(), $project->getId()); + if (! $document->isEmpty()) { + $this->deleteAuditLogsByResource('document/'.$document->getId(), $project->getId()); } break; @@ -118,7 +117,7 @@ class DeletesV1 extends Worker $this->deleteCacheByDate(); break; default: - Console::error('No delete operation for type: ' . $type); + Console::error('No delete operation for type: '.$type); break; } } @@ -128,7 +127,7 @@ class DeletesV1 extends Worker } /** - * @param string $projectId + * @param string $projectId */ protected function deleteCacheByResource(string $projectId): void { @@ -147,10 +146,9 @@ class DeletesV1 extends Worker protected function deleteCacheFiles($query): void { $this->deleteForProjectIds(function (string $projectId) use ($query) { - $dbForProject = $this->getProjectDB($projectId); $cache = new Cache( - new Filesystem(APP_STORAGE_CACHE . DIRECTORY_SEPARATOR . 'app-' . $projectId) + new Filesystem(APP_STORAGE_CACHE.DIRECTORY_SEPARATOR.'app-'.$projectId) ); $this->deleteByGroup( @@ -158,12 +156,12 @@ class DeletesV1 extends Worker $query, $dbForProject, function (Document $document) use ($cache, $projectId) { - $path = APP_STORAGE_CACHE . DIRECTORY_SEPARATOR . 'app-' . $projectId . DIRECTORY_SEPARATOR . $document->getId(); + $path = APP_STORAGE_CACHE.DIRECTORY_SEPARATOR.'app-'.$projectId.DIRECTORY_SEPARATOR.$document->getId(); if ($cache->purge($document->getId())) { - Console::success('Deleting cache file: ' . $path); + Console::success('Deleting cache file: '.$path); } else { - Console::error('Failed to delete cache file: ' . $path); + Console::error('Failed to delete cache file: '.$path); } } ); @@ -171,8 +169,9 @@ class DeletesV1 extends Worker } /** - * @param Document $document database document - * @param string $projectId + * @param Document $document database document + * @param string $projectId + * * @throws Exception */ protected function deleteDatabase(Document $document, string $projectId): void @@ -181,18 +180,19 @@ class DeletesV1 extends Worker $dbForProject = $this->getProjectDB($projectId); - $this->deleteByGroup('database_' . $document->getInternalId(), [], $dbForProject, function ($document) use ($projectId) { + $this->deleteByGroup('database_'.$document->getInternalId(), [], $dbForProject, function ($document) use ($projectId) { $this->deleteCollection($document, $projectId); }); - $dbForProject->deleteCollection('database_' . $document->getInternalId()); + $dbForProject->deleteCollection('database_'.$document->getInternalId()); - $this->deleteAuditLogsByResource('database/' . $databaseId, $projectId); + $this->deleteAuditLogsByResource('database/'.$databaseId, $projectId); } /** - * @param Document $document teams document - * @param string $projectId + * @param Document $document teams document + * @param string $projectId + * * @throws Exception */ protected function deleteCollection(Document $document, string $projectId): void @@ -203,23 +203,24 @@ class DeletesV1 extends Worker $dbForProject = $this->getProjectDB($projectId); - $dbForProject->deleteCollection('database_' . $databaseInternalId . '_collection_' . $document->getInternalId()); + $dbForProject->deleteCollection('database_'.$databaseInternalId.'_collection_'.$document->getInternalId()); $this->deleteByGroup('attributes', [ Query::equal('databaseId', [$databaseId]), - Query::equal('collectionId', [$collectionId]) + Query::equal('collectionId', [$collectionId]), ], $dbForProject); $this->deleteByGroup('indexes', [ Query::equal('databaseId', [$databaseId]), - Query::equal('collectionId', [$collectionId]) + Query::equal('collectionId', [$collectionId]), ], $dbForProject); - $this->deleteAuditLogsByResource('database/' . $databaseId . '/collection/' . $collectionId, $projectId); + $this->deleteAuditLogsByResource('database/'.$databaseId.'/collection/'.$collectionId, $projectId); } /** - * @param string $hourlyUsageRetentionDatetime + * @param string $hourlyUsageRetentionDatetime + * * @throws Exception */ protected function deleteUsageStats(string $hourlyUsageRetentionDatetime) @@ -234,8 +235,9 @@ class DeletesV1 extends Worker } /** - * @param Document $document teams document - * @param string $projectId + * @param Document $document teams document + * @param string $projectId + * * @throws Exception */ protected function deleteMemberships(Document $document, string $projectId): void @@ -244,12 +246,13 @@ class DeletesV1 extends Worker // Delete Memberships $this->deleteByGroup('memberships', [ - Query::equal('teamId', [$teamId]) + Query::equal('teamId', [$teamId]), ], $this->getProjectDB($projectId)); } /** - * @param Document $document project document + * @param Document $document project document + * * @throws Exception */ protected function deleteProject(Document $document): void @@ -260,7 +263,7 @@ class DeletesV1 extends Worker $dbForConsole = $this->getConsoleDB(); $domains = $dbForConsole->find('domains', [ - Query::equal('projectInternalId', [$document->getInternalId()]) + Query::equal('projectInternalId', [$document->getInternalId()]), ]); foreach ($domains as $domain) { @@ -303,8 +306,9 @@ class DeletesV1 extends Worker } /** - * @param Document $document user document - * @param string $projectId + * @param Document $document user document + * @param string $projectId + * * @throws Exception */ protected function deleteUser(Document $document, string $projectId): void @@ -313,20 +317,19 @@ class DeletesV1 extends Worker // Delete all sessions of this user from the sessions table and update the sessions field of the user record $this->deleteByGroup('sessions', [ - Query::equal('userId', [$userId]) + Query::equal('userId', [$userId]), ], $this->getProjectDB($projectId)); $this->getProjectDB($projectId)->deleteCachedDocument('users', $userId); // Delete Memberships and decrement team membership counts $this->deleteByGroup('memberships', [ - Query::equal('userId', [$userId]) + Query::equal('userId', [$userId]), ], $this->getProjectDB($projectId), function (Document $document) use ($projectId) { - if ($document->getAttribute('confirm')) { // Count only confirmed members $teamId = $document->getAttribute('teamId'); $team = $this->getProjectDB($projectId)->getDocument('teams', $teamId); - if (!$team->isEmpty()) { + if (! $team->isEmpty()) { $team = $this ->getProjectDB($projectId) ->updateDocument( @@ -341,12 +344,13 @@ class DeletesV1 extends Worker // Delete tokens $this->deleteByGroup('tokens', [ - Query::equal('userId', [$userId]) + Query::equal('userId', [$userId]), ], $this->getProjectDB($projectId)); } /** - * @param string $datetime + * @param string $datetime + * * @throws Exception */ protected function deleteExecutionLogs(string $datetime): void @@ -355,7 +359,7 @@ class DeletesV1 extends Worker $dbForProject = $this->getProjectDB($projectId); // Delete Executions $this->deleteByGroup('executions', [ - Query::lessThan('$createdAt', $datetime) + Query::lessThan('$createdAt', $datetime), ], $dbForProject); }); } @@ -373,13 +377,14 @@ class DeletesV1 extends Worker // Delete Sessions $this->deleteByGroup('sessions', [ - Query::lessThan('$createdAt', $expired) + Query::lessThan('$createdAt', $expired), ], $dbForProject); }); } /** - * @param string $datetime + * @param string $datetime + * * @throws Exception */ protected function deleteRealtimeUsage(string $datetime): void @@ -388,13 +393,14 @@ class DeletesV1 extends Worker $dbForProject = $this->getProjectDB($projectId); // Delete Dead Realtime Logs $this->deleteByGroup('realtime', [ - Query::lessThan('timestamp', $datetime) + Query::lessThan('timestamp', $datetime), ], $dbForProject); }); } /** - * @param string $datetime + * @param string $datetime + * * @throws Exception */ protected function deleteAbuseLogs(string $datetime): void @@ -405,17 +411,18 @@ class DeletesV1 extends Worker $this->deleteForProjectIds(function (string $projectId) use ($datetime) { $dbForProject = $this->getProjectDB($projectId); - $timeLimit = new TimeLimit("", 0, 1, $dbForProject); + $timeLimit = new TimeLimit('', 0, 1, $dbForProject); $abuse = new Abuse($timeLimit); $status = $abuse->cleanup($datetime); - if (!$status) { - throw new Exception('Failed to delete Abuse logs for project ' . $projectId); + if (! $status) { + throw new Exception('Failed to delete Abuse logs for project '.$projectId); } }); } /** - * @param string $datetime + * @param string $datetime + * * @throws Exception */ protected function deleteAuditLogs(string $datetime): void @@ -428,15 +435,16 @@ class DeletesV1 extends Worker $dbForProject = $this->getProjectDB($projectId); $audit = new Audit($dbForProject); $status = $audit->cleanup($datetime); - if (!$status) { - throw new Exception('Failed to delete Audit logs for project' . $projectId); + if (! $status) { + throw new Exception('Failed to delete Audit logs for project'.$projectId); } }); } /** - * @param string $resource - * @param string $projectId + * @param string $resource + * @param string $projectId + * * @throws Exception */ protected function deleteAuditLogsByResource(string $resource, string $projectId): void @@ -444,13 +452,14 @@ class DeletesV1 extends Worker $dbForProject = $this->getProjectDB($projectId); $this->deleteByGroup(Audit::COLLECTION, [ - Query::equal('resource', [$resource]) + Query::equal('resource', [$resource]), ], $dbForProject); } /** - * @param Document $document function document - * @param string $projectId + * @param Document $document function document + * @param string $projectId + * * @throws Exception */ protected function deleteFunction(Document $document, string $projectId): void @@ -461,41 +470,41 @@ class DeletesV1 extends Worker /** * Delete Variables */ - Console::info("Deleting variables for function " . $functionId); + Console::info('Deleting variables for function '.$functionId); $this->deleteByGroup('variables', [ - Query::equal('functionId', [$functionId]) + Query::equal('functionId', [$functionId]), ], $dbForProject); /** * Delete Deployments */ - Console::info("Deleting deployments for function " . $functionId); + Console::info('Deleting deployments for function '.$functionId); $storageFunctions = $this->getFunctionsDevice($projectId); $deploymentIds = []; $this->deleteByGroup('deployments', [ - Query::equal('resourceId', [$functionId]) + Query::equal('resourceId', [$functionId]), ], $dbForProject, function (Document $document) use ($storageFunctions, &$deploymentIds) { $deploymentIds[] = $document->getId(); if ($storageFunctions->delete($document->getAttribute('path', ''), true)) { - Console::success('Deleted deployment files: ' . $document->getAttribute('path', '')); + Console::success('Deleted deployment files: '.$document->getAttribute('path', '')); } else { - Console::error('Failed to delete deployment files: ' . $document->getAttribute('path', '')); + Console::error('Failed to delete deployment files: '.$document->getAttribute('path', '')); } }); /** * Delete builds */ - Console::info("Deleting builds for function " . $functionId); + Console::info('Deleting builds for function '.$functionId); $storageBuilds = $this->getBuildsDevice($projectId); foreach ($deploymentIds as $deploymentId) { $this->deleteByGroup('builds', [ - Query::equal('deploymentId', [$deploymentId]) - ], $dbForProject, function (Document $document) use ($storageBuilds, $deploymentId) { + Query::equal('deploymentId', [$deploymentId]), + ], $dbForProject, function (Document $document) use ($storageBuilds) { if ($storageBuilds->delete($document->getAttribute('outputPath', ''), true)) { - Console::success('Deleted build files: ' . $document->getAttribute('outputPath', '')); + Console::success('Deleted build files: '.$document->getAttribute('outputPath', '')); } else { - Console::error('Failed to delete build files: ' . $document->getAttribute('outputPath', '')); + Console::error('Failed to delete build files: '.$document->getAttribute('outputPath', '')); } }); } @@ -503,15 +512,15 @@ class DeletesV1 extends Worker /** * Delete Executions */ - Console::info("Deleting executions for function " . $functionId); + Console::info('Deleting executions for function '.$functionId); $this->deleteByGroup('executions', [ - Query::equal('functionId', [$functionId]) + Query::equal('functionId', [$functionId]), ], $dbForProject); /** * Request executor to delete all deployment containers */ - Console::info("Requesting executor to delete all deployment containers for function " . $functionId); + Console::info('Requesting executor to delete all deployment containers for function '.$functionId); $executor = new Executor(App::getEnv('_APP_EXECUTOR_HOST')); foreach ($deploymentIds as $deploymentId) { try { @@ -523,8 +532,9 @@ class DeletesV1 extends Worker } /** - * @param Document $document deployment document - * @param string $projectId + * @param Document $document deployment document + * @param string $projectId + * * @throws Exception */ protected function deleteDeployment(Document $document, string $projectId): void @@ -536,33 +546,33 @@ class DeletesV1 extends Worker /** * Delete deployment files */ - Console::info("Deleting deployment files for deployment " . $deploymentId); + Console::info('Deleting deployment files for deployment '.$deploymentId); $storageFunctions = $this->getFunctionsDevice($projectId); if ($storageFunctions->delete($document->getAttribute('path', ''), true)) { - Console::success('Deleted deployment files: ' . $document->getAttribute('path', '')); + Console::success('Deleted deployment files: '.$document->getAttribute('path', '')); } else { - Console::error('Failed to delete deployment files: ' . $document->getAttribute('path', '')); + Console::error('Failed to delete deployment files: '.$document->getAttribute('path', '')); } /** * Delete builds */ - Console::info("Deleting builds for deployment " . $deploymentId); + Console::info('Deleting builds for deployment '.$deploymentId); $storageBuilds = $this->getBuildsDevice($projectId); $this->deleteByGroup('builds', [ - Query::equal('deploymentId', [$deploymentId]) + Query::equal('deploymentId', [$deploymentId]), ], $dbForProject, function (Document $document) use ($storageBuilds) { if ($storageBuilds->delete($document->getAttribute('outputPath', ''), true)) { - Console::success('Deleted build files: ' . $document->getAttribute('outputPath', '')); + Console::success('Deleted build files: '.$document->getAttribute('outputPath', '')); } else { - Console::error('Failed to delete build files: ' . $document->getAttribute('outputPath', '')); + Console::error('Failed to delete build files: '.$document->getAttribute('outputPath', '')); } }); /** * Request executor to delete the deployment container */ - Console::info("Requesting executor to delete deployment container for deployment " . $deploymentId); + Console::info('Requesting executor to delete deployment container for deployment '.$deploymentId); try { $executor = new Executor(App::getEnv('_APP_EXECUTOR_HOST')); $executor->deleteRuntime($projectId, $deploymentId); @@ -571,19 +581,18 @@ class DeletesV1 extends Worker } } - /** - * @param Document $document to be deleted - * @param Database $database to delete it from - * @param callable|null $callback to perform after document is deleted - * + * @param Document $document to be deleted + * @param Database $database to delete it from + * @param callable|null $callback to perform after document is deleted * @return bool + * * @throws \Utopia\Database\Exception\Authorization */ protected function deleteById(Document $document, Database $database, callable $callback = null): bool { if ($database->deleteDocument($document->getCollection(), $document->getId())) { - Console::success('Deleted document "' . $document->getId() . '" successfully'); + Console::success('Deleted document "'.$document->getId().'" successfully'); if (is_callable($callback)) { $callback($document); @@ -591,13 +600,15 @@ class DeletesV1 extends Worker return true; } else { - Console::error('Failed to delete document: ' . $document->getId()); + Console::error('Failed to delete document: '.$document->getId()); + return false; } } /** - * @param callable $callback + * @param callable $callback + * * @throws Exception */ protected function deleteForProjectIds(callable $callback): void @@ -620,7 +631,7 @@ class DeletesV1 extends Worker $sum = count($projects); - Console::info('Executing delete function for chunk #' . $chunk . '. Found ' . $sum . ' projects'); + Console::info('Executing delete function for chunk #'.$chunk.'. Found '.$sum.' projects'); foreach ($projectIds as $projectId) { $callback($projectId); $count++; @@ -628,14 +639,15 @@ class DeletesV1 extends Worker } $executionEnd = \microtime(true); - Console::info("Found {$count} projects " . ($executionEnd - $executionStart) . " seconds"); + Console::info("Found {$count} projects ".($executionEnd - $executionStart).' seconds'); } /** - * @param string $collection collectionID - * @param array $queries - * @param Database $database - * @param callable|null $callback + * @param string $collection collectionID + * @param array $queries + * @param Database $database + * @param callable|null $callback + * * @throws Exception */ protected function deleteByGroup(string $collection, array $queries, Database $database, callable $callback = null): void @@ -655,7 +667,7 @@ class DeletesV1 extends Worker $sum = count($results); - Console::info('Deleting chunk #' . $chunk . '. Found ' . $sum . ' documents'); + Console::info('Deleting chunk #'.$chunk.'. Found '.$sum.' documents'); foreach ($results as $document) { $this->deleteById($document, $database, $callback); @@ -665,11 +677,12 @@ class DeletesV1 extends Worker $executionEnd = \microtime(true); - Console::info("Deleted {$count} document by group in " . ($executionEnd - $executionStart) . " seconds"); + Console::info("Deleted {$count} document by group in ".($executionEnd - $executionStart).' seconds'); } /** - * @param Document $document certificates document + * @param Document $document certificates document + * * @throws \Utopia\Database\Exception\Authorization */ protected function deleteCertificates(Document $document): void @@ -679,10 +692,10 @@ class DeletesV1 extends Worker // If domain has certificate generated if (isset($document['certificateId'])) { $domainUsingCertificate = $consoleDB->findOne('domains', [ - Query::equal('certificateId', [$document['certificateId']]) + Query::equal('certificateId', [$document['certificateId']]), ]); - if (!$domainUsingCertificate) { + if (! $domainUsingCertificate) { $mainDomain = App::getEnv('_APP_DOMAIN_TARGET', ''); if ($mainDomain === $document->getAttribute('domain')) { $domainUsingCertificate = $mainDomain; @@ -692,13 +705,14 @@ class DeletesV1 extends Worker // If certificate is still used by some domain, mark we can't delete. // Current domain should not be found, because we only have copy. Original domain is already deleted from database. if ($domainUsingCertificate) { - Console::warning("Skipping certificate deletion, because a domain is still using it."); + Console::warning('Skipping certificate deletion, because a domain is still using it.'); + return; } } $domain = $document->getAttribute('domain'); - $directory = APP_STORAGE_CERTIFICATES . '/' . $domain; + $directory = APP_STORAGE_CERTIFICATES.'/'.$domain; $checkTraversal = realpath($directory) === $directory; if ($domain && $checkTraversal && is_dir($directory)) { @@ -708,7 +722,7 @@ class DeletesV1 extends Worker } // Delete files, so Traefik is aware of change - array_map('unlink', glob($directory . '/*.*')); + array_map('unlink', glob($directory.'/*.*')); rmdir($directory); Console::info("Deleted certificate files for {$domain}"); } else { @@ -719,7 +733,7 @@ class DeletesV1 extends Worker protected function deleteBucket(Document $document, string $projectId) { $dbForProject = $this->getProjectDB($projectId); - $dbForProject->deleteCollection('bucket_' . $document->getInternalId()); + $dbForProject->deleteCollection('bucket_'.$document->getInternalId()); $device = $this->getFilesDevice($projectId); diff --git a/app/workers/functions.php b/app/workers/functions.php index d7cb8c7ff3..937fc3eb0d 100644 --- a/app/workers/functions.php +++ b/app/workers/functions.php @@ -16,23 +16,25 @@ use Utopia\Database\DateTime; use Utopia\Database\Document; use Utopia\Database\Helpers\ID; use Utopia\Database\Helpers\Permission; -use Utopia\Database\Query; use Utopia\Database\Helpers\Role; +use Utopia\Database\Query; -require_once __DIR__ . '/../init.php'; +require_once __DIR__.'/../init.php'; Console::title('Functions V1 Worker'); -Console::success(APP_NAME . ' functions worker v1 has started'); +Console::success(APP_NAME.' functions worker v1 has started'); class FunctionsV1 extends Worker { private ?Executor $executor = null; + public array $args = []; + public array $allowed = []; public function getName(): string { - return "functions"; + return 'functions'; } public function init(): void @@ -57,13 +59,12 @@ class FunctionsV1 extends Worker /** * Handle Event execution. */ - if (!empty($events)) { + if (! empty($events)) { $limit = 30; $sum = 30; $offset = 0; $functions = []; /** @var Document[] $functions */ - while ($sum >= $limit) { $functions = $database->find('functions', [ Query::limit($limit), @@ -73,14 +74,14 @@ class FunctionsV1 extends Worker $sum = \count($functions); $offset = $offset + $limit; - Console::log('Fetched ' . $sum . ' functions...'); + Console::log('Fetched '.$sum.' functions...'); foreach ($functions as $function) { - if (!array_intersect($events, $function->getAttribute('events', []))) { + if (! array_intersect($events, $function->getAttribute('events', []))) { continue; } - Console::success('Iterating function: ' . $function->getAttribute('name')); + Console::success('Iterating function: '.$function->getAttribute('name')); $this->execute( project: $project, @@ -93,7 +94,7 @@ class FunctionsV1 extends Worker user: $user ); - Console::success('Triggered function: ' . $events[0]); + Console::success('Triggered function: '.$events[0]); } } @@ -147,7 +148,7 @@ class FunctionsV1 extends Worker $function = $database->getDocument('functions', $function->getId()); if (empty($function->getId())) { - throw new Exception('Function not found (' . $function->getId() . ')'); + throw new Exception('Function not found ('.$function->getId().')'); } if ($functionOriginal->getAttribute('schedule') !== $function->getAttribute('schedule')) { // Schedule has changed from previous run, ignore this run. @@ -178,7 +179,6 @@ class FunctionsV1 extends Worker ->setUser($user) ->setProject($project) ->schedule(new \DateTime($next)); - ; $this->execute( project: $project, @@ -203,7 +203,6 @@ class FunctionsV1 extends Worker ?Document $user = null, string $jwt = null ) { - $user ??= new Document(); $functionId = $function->getId(); $deploymentId = $function->getAttribute('deployment', ''); @@ -232,8 +231,8 @@ class FunctionsV1 extends Worker /** Check if runtime is supported */ $runtimes = Config::getParam('runtimes', []); - if (!\array_key_exists($function->getAttribute('runtime'), $runtimes)) { - throw new Exception('Runtime "' . $function->getAttribute('runtime', '') . '" is not supported', 400); + if (! \array_key_exists($function->getAttribute('runtime'), $runtimes)) { + throw new Exception('Runtime "'.$function->getAttribute('runtime', '').'" is not supported', 400); } $runtime = $runtimes[$function->getAttribute('runtime')]; @@ -265,6 +264,7 @@ class FunctionsV1 extends Worker $vars = array_reduce($function['vars'] ?? [], function (array $carry, Document $var) { $carry[$var->getAttribute('key')] = $var->getAttribute('value'); + return $carry; }, []); @@ -309,7 +309,7 @@ class FunctionsV1 extends Worker } catch (\Throwable $th) { $interval = (new \DateTime())->diff(new \DateTime($execution->getCreatedAt())); $execution - ->setAttribute('duration', (float)$interval->format('%s.%f')) + ->setAttribute('duration', (float) $interval->format('%s.%f')) ->setAttribute('status', 'failed') ->setAttribute('statusCode', $th->getCode()) ->setAttribute('stderr', $th->getMessage()); @@ -339,7 +339,7 @@ class FunctionsV1 extends Worker /** Trigger realtime event */ $allEvents = Event::generateEvents('functions.[functionId].executions.[executionId].update', [ 'functionId' => $function->getId(), - 'executionId' => $execution->getId() + 'executionId' => $execution->getId(), ]); $target = Realtime::fromPayload( // Pass first, most verbose event pattern diff --git a/app/workers/mails.php b/app/workers/mails.php index e850885ddc..15be227a1c 100644 --- a/app/workers/mails.php +++ b/app/workers/mails.php @@ -4,16 +4,16 @@ use Appwrite\Resque\Worker; use Utopia\App; use Utopia\CLI\Console; -require_once __DIR__ . '/../init.php'; +require_once __DIR__.'/../init.php'; Console::title('Mails V1 Worker'); -Console::success(APP_NAME . ' mails worker v1 has started' . "\n"); +Console::success(APP_NAME.' mails worker v1 has started'."\n"); class MailsV1 extends Worker { public function getName(): string { - return "mails"; + return 'mails'; } public function init(): void @@ -26,10 +26,10 @@ class MailsV1 extends Worker if (empty(App::getEnv('_APP_SMTP_HOST'))) { Console::info('Skipped mail processing. No SMTP server hostname has been set.'); + return; } - $recipient = $this->args['recipient']; $subject = $this->args['subject']; $name = $this->args['name']; @@ -56,7 +56,7 @@ class MailsV1 extends Worker $mail->clearBCCs(); $mail->clearCCs(); - $mail->setFrom(App::getEnv('_APP_SYSTEM_EMAIL_ADDRESS', APP_EMAIL_TEAM), (empty($from) ? \urldecode(App::getEnv('_APP_SYSTEM_EMAIL_NAME', APP_NAME . ' Server')) : $from)); + $mail->setFrom(App::getEnv('_APP_SYSTEM_EMAIL_ADDRESS', APP_EMAIL_TEAM), (empty($from) ? \urldecode(App::getEnv('_APP_SYSTEM_EMAIL_NAME', APP_NAME.' Server')) : $from)); $mail->addAddress($recipient, $name); $mail->Subject = $subject; $mail->Body = $body; @@ -65,7 +65,7 @@ class MailsV1 extends Worker try { $mail->send(); } catch (\Exception $error) { - throw new Exception('Error sending mail: ' . $error->getMessage(), 500); + throw new Exception('Error sending mail: '.$error->getMessage(), 500); } } diff --git a/app/workers/messaging.php b/app/workers/messaging.php index 8373d07ba3..a8bd97b510 100644 --- a/app/workers/messaging.php +++ b/app/workers/messaging.php @@ -13,19 +13,20 @@ use Utopia\Messaging\Adapters\SMS\Twilio; use Utopia\Messaging\Adapters\SMS\Vonage; use Utopia\Messaging\Messages\SMS; -require_once __DIR__ . '/../init.php'; +require_once __DIR__.'/../init.php'; Console::title('Messaging V1 Worker'); -Console::success(APP_NAME . ' messaging worker v1 has started' . "\n"); +Console::success(APP_NAME.' messaging worker v1 has started'."\n"); class MessagingV1 extends Worker { protected ?Adapter $sms = null; + protected ?string $from = null; public function getName(): string { - return "mails"; + return 'mails'; } public function init(): void @@ -51,11 +52,13 @@ class MessagingV1 extends Worker { if (empty(App::getEnv('_APP_SMS_PROVIDER'))) { Console::info('Skipped sms processing. No Phone provider has been set.'); + return; } if (empty($this->from)) { Console::info('Skipped sms processing. No phone number has been set.'); + return; } @@ -68,7 +71,7 @@ class MessagingV1 extends Worker try { $this->sms->send($message); } catch (\Exception $error) { - throw new Exception('Error sending message: ' . $error->getMessage(), 500); + throw new Exception('Error sending message: '.$error->getMessage(), 500); } } diff --git a/app/workers/webhooks.php b/app/workers/webhooks.php index 4048581c0c..33fd4e5f6c 100644 --- a/app/workers/webhooks.php +++ b/app/workers/webhooks.php @@ -5,10 +5,10 @@ use Utopia\App; use Utopia\CLI\Console; use Utopia\Database\Document; -require_once __DIR__ . '/../init.php'; +require_once __DIR__.'/../init.php'; Console::title('Webhooks V1 Worker'); -Console::success(APP_NAME . ' webhooks worker v1 has started'); +Console::success(APP_NAME.' webhooks worker v1 has started'); class WebhooksV1 extends Worker { @@ -16,7 +16,7 @@ class WebhooksV1 extends Worker public function getName(): string { - return "webhooks"; + return 'webhooks'; } public function init(): void @@ -36,7 +36,7 @@ class WebhooksV1 extends Worker } } - if (!empty($this->errors)) { + if (! empty($this->errors)) { throw new Exception(\implode(" / \n\n", $this->errors)); } } @@ -45,7 +45,7 @@ class WebhooksV1 extends Worker { $url = \rawurldecode($webhook->getAttribute('url')); $signatureKey = $webhook->getAttribute('signatureKey'); - $signature = base64_encode(hash_hmac('sha1', $url . $payload, $signatureKey, true)); + $signature = base64_encode(hash_hmac('sha1', $url.$payload, $signatureKey, true)); $httpUser = $webhook->getAttribute('httpUser'); $httpPass = $webhook->getAttribute('httpPass'); $ch = \curl_init($webhook->getAttribute('url')); @@ -64,28 +64,28 @@ class WebhooksV1 extends Worker CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', - 'Content-Length: ' . \strlen($payload), - 'X-' . APP_NAME . '-Webhook-Id: ' . $webhook->getId(), - 'X-' . APP_NAME . '-Webhook-Events: ' . implode(',', $events), - 'X-' . APP_NAME . '-Webhook-Name: ' . $webhook->getAttribute('name', ''), - 'X-' . APP_NAME . '-Webhook-User-Id: ' . $user->getId(), - 'X-' . APP_NAME . '-Webhook-Project-Id: ' . $project->getId(), - 'X-' . APP_NAME . '-Webhook-Signature: ' . $signature, + 'Content-Length: '.\strlen($payload), + 'X-'.APP_NAME.'-Webhook-Id: '.$webhook->getId(), + 'X-'.APP_NAME.'-Webhook-Events: '.implode(',', $events), + 'X-'.APP_NAME.'-Webhook-Name: '.$webhook->getAttribute('name', ''), + 'X-'.APP_NAME.'-Webhook-User-Id: '.$user->getId(), + 'X-'.APP_NAME.'-Webhook-Project-Id: '.$project->getId(), + 'X-'.APP_NAME.'-Webhook-Signature: '.$signature, ] ); - if (!$webhook->getAttribute('security', true)) { + if (! $webhook->getAttribute('security', true)) { \curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); \curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); } - if (!empty($httpUser) && !empty($httpPass)) { + if (! empty($httpUser) && ! empty($httpPass)) { \curl_setopt($ch, CURLOPT_USERPWD, "$httpUser:$httpPass"); \curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); } if (false === \curl_exec($ch)) { - $this->errors[] = \curl_error($ch) . ' in events ' . implode(', ', $events) . ' for webhook ' . $webhook->getAttribute('name'); + $this->errors[] = \curl_error($ch).' in events '.implode(', ', $events).' for webhook '.$webhook->getAttribute('name'); } \curl_close($ch); diff --git a/src/Appwrite/Auth/Auth.php b/src/Appwrite/Auth/Auth.php index 7217a87680..fa2f2ef956 100644 --- a/src/Appwrite/Auth/Auth.php +++ b/src/Appwrite/Auth/Auth.php @@ -9,9 +9,8 @@ use Appwrite\Auth\Hash\Phpass; use Appwrite\Auth\Hash\Scrypt; use Appwrite\Auth\Hash\Scryptmodified; use Appwrite\Auth\Hash\Sha; -use Utopia\Database\Database; -use Utopia\Database\Document; use Utopia\Database\DateTime; +use Utopia\Database\Document; use Utopia\Database\Helpers\Role; use Utopia\Database\Validator\Authorization; use Utopia\Database\Validator\Roles; @@ -26,49 +25,69 @@ class Auth 'phpass', 'scrypt', 'scryptMod', - 'plaintext' + 'plaintext', ]; public const DEFAULT_ALGO = 'argon2'; + public const DEFAULT_ALGO_OPTIONS = ['type' => 'argon2', 'memoryCost' => 2048, 'timeCost' => 4, 'threads' => 3]; /** * User Roles. */ public const USER_ROLE_ANY = 'any'; + public const USER_ROLE_GUESTS = 'guests'; + public const USER_ROLE_USERS = 'users'; + public const USER_ROLE_ADMIN = 'admin'; + public const USER_ROLE_DEVELOPER = 'developer'; + public const USER_ROLE_OWNER = 'owner'; + public const USER_ROLE_APPS = 'apps'; + public const USER_ROLE_SYSTEM = 'system'; /** * Token Types. */ public const TOKEN_TYPE_LOGIN = 1; // Deprecated + public const TOKEN_TYPE_VERIFICATION = 2; + public const TOKEN_TYPE_RECOVERY = 3; + public const TOKEN_TYPE_INVITE = 4; + public const TOKEN_TYPE_MAGIC_URL = 5; + public const TOKEN_TYPE_PHONE = 6; /** * Session Providers. */ public const SESSION_PROVIDER_EMAIL = 'email'; + public const SESSION_PROVIDER_ANONYMOUS = 'anonymous'; + public const SESSION_PROVIDER_MAGIC_URL = 'magic-url'; + public const SESSION_PROVIDER_PHONE = 'phone'; /** * Token Expiration times. */ public const TOKEN_EXPIRATION_LOGIN_LONG = 31536000; /* 1 year */ + public const TOKEN_EXPIRATION_LOGIN_SHORT = 3600; /* 1 hour */ + public const TOKEN_EXPIRATION_RECOVERY = 3600; /* 1 hour */ + public const TOKEN_EXPIRATION_CONFIRM = 3600 * 24 * 7; /* 7 days */ + public const TOKEN_EXPIRATION_PHONE = 60 * 15; /* 15 minutes */ /** @@ -94,7 +113,6 @@ class Auth * Set Cookie Name. * * @param $string - * * @return string */ public static function setCookieName($string) @@ -105,9 +123,8 @@ class Auth /** * Encode Session. * - * @param string $id - * @param string $secret - * + * @param string $id + * @param string $secret * @return string */ public static function encodeSession($id, $secret) @@ -121,8 +138,7 @@ class Auth /** * Decode Session. * - * @param string $session - * + * @param string $session * @return array * * @throws \Exception @@ -132,7 +148,7 @@ class Auth $session = \json_decode(\base64_decode($session), true); $default = ['id' => null, 'secret' => '']; - if (!\is_array($session)) { + if (! \is_array($session)) { return $default; } @@ -145,7 +161,6 @@ class Auth * One-way encryption * * @param $string - * * @return string */ public static function hash(string $string) @@ -158,10 +173,9 @@ class Auth * * One way string hashing for user passwords * - * @param string $string - * @param string $algo hashing algorithm to use - * @param array $options algo-specific options - * + * @param string $string + * @param string $algo hashing algorithm to use + * @param array $options algo-specific options * @return bool|string|null */ public static function passwordHash(string $string, string $algo, array $options = []) @@ -172,45 +186,51 @@ class Auth $options = Auth::DEFAULT_ALGO_OPTIONS; } - if (!\in_array($algo, Auth::SUPPORTED_ALGOS)) { - throw new \Exception('Hashing algorithm \'' . $algo . '\' is not supported.'); + if (! \in_array($algo, Auth::SUPPORTED_ALGOS)) { + throw new \Exception('Hashing algorithm \''.$algo.'\' is not supported.'); } switch ($algo) { case 'argon2': $hasher = new Argon2($options); + return $hasher->hash($string); case 'bcrypt': $hasher = new Bcrypt($options); + return $hasher->hash($string); case 'md5': $hasher = new Md5($options); + return $hasher->hash($string); case 'sha': $hasher = new Sha($options); + return $hasher->hash($string); case 'phpass': $hasher = new Phpass($options); + return $hasher->hash($string); case 'scrypt': $hasher = new Scrypt($options); + return $hasher->hash($string); case 'scryptMod': $hasher = new Scryptmodified($options); + return $hasher->hash($string); default: - throw new \Exception('Hashing algorithm \'' . $algo . '\' is not supported.'); + throw new \Exception('Hashing algorithm \''.$algo.'\' is not supported.'); } } /** * Password verify. * - * @param string $plain - * @param string $hash - * @param string $algo hashing algorithm used to hash - * @param array $options algo-specific options - * + * @param string $plain + * @param string $hash + * @param string $algo hashing algorithm used to hash + * @param array $options algo-specific options * @return bool */ public static function passwordVerify(string $plain, string $hash, string $algo, array $options = []) @@ -221,34 +241,41 @@ class Auth $options = Auth::DEFAULT_ALGO_OPTIONS; } - if (!\in_array($algo, Auth::SUPPORTED_ALGOS)) { - throw new \Exception('Hashing algorithm \'' . $algo . '\' is not supported.'); + if (! \in_array($algo, Auth::SUPPORTED_ALGOS)) { + throw new \Exception('Hashing algorithm \''.$algo.'\' is not supported.'); } switch ($algo) { case 'argon2': $hasher = new Argon2($options); + return $hasher->verify($plain, $hash); case 'bcrypt': $hasher = new Bcrypt($options); + return $hasher->verify($plain, $hash); case 'md5': $hasher = new Md5($options); + return $hasher->verify($plain, $hash); case 'sha': $hasher = new Sha($options); + return $hasher->verify($plain, $hash); case 'phpass': $hasher = new Phpass($options); + return $hasher->verify($plain, $hash); case 'scrypt': $hasher = new Scrypt($options); + return $hasher->verify($plain, $hash); case 'scryptMod': $hasher = new Scryptmodified($options); + return $hasher->verify($plain, $hash); default: - throw new \Exception('Hashing algorithm \'' . $algo . '\' is not supported.'); + throw new \Exception('Hashing algorithm \''.$algo.'\' is not supported.'); } } @@ -257,8 +284,7 @@ class Auth * * Generate random password string * - * @param int $length - * + * @param int $length * @return string */ public static function passwordGenerator(int $length = 20): string @@ -271,8 +297,7 @@ class Auth * * Generate random password string * - * @param int $length - * + * @param int $length * @return string */ public static function tokenGenerator(int $length = 128): string @@ -285,8 +310,7 @@ class Auth * * Generate random code string * - * @param int $length - * + * @param int $length * @return string */ public static function codeGenerator(int $length = 6): string @@ -303,10 +327,9 @@ class Auth /** * Verify token and check that its not expired. * - * @param array $tokens - * @param int $type - * @param string $secret - * + * @param array $tokens + * @param int $type + * @param string $secret * @return bool|string */ public static function tokenVerify(array $tokens, int $type, string $secret) @@ -321,7 +344,7 @@ class Auth $token->getAttribute('secret') === self::hash($secret) && DateTime::formatTz($token->getAttribute('expire')) >= DateTime::formatTz(DateTime::now()) ) { - return (string)$token->getId(); + return (string) $token->getId(); } } @@ -350,10 +373,9 @@ class Auth /** * Verify session and check that its not expired. * - * @param array $sessions - * @param string $secret - * @param string $expires - * + * @param array $sessions + * @param string $secret + * @param string $expires * @return bool|string */ public static function sessionVerify(array $sessions, string $secret, int $expires) @@ -376,8 +398,7 @@ class Auth /** * Is Privileged User? * - * @param array $roles - * + * @param array $roles * @return bool */ public static function isPrivilegedUser(array $roles): bool @@ -396,8 +417,7 @@ class Auth /** * Is App User? * - * @param array $roles - * + * @param array $roles * @return bool */ public static function isAppUser(array $roles): bool @@ -412,14 +432,14 @@ class Auth /** * Returns all roles for a user. * - * @param Document $user + * @param Document $user * @return array */ public static function getRoles(Document $user): array { $roles = []; - if (!self::isPrivilegedUser(Authorization::getRoles()) && !self::isAppUser(Authorization::getRoles())) { + if (! self::isPrivilegedUser(Authorization::getRoles()) && ! self::isAppUser(Authorization::getRoles())) { if ($user->getId()) { $roles[] = Role::user($user->getId())->toString(); $roles[] = Role::users()->toString(); @@ -440,7 +460,7 @@ class Auth } foreach ($user->getAttribute('memberships', []) as $node) { - if (!isset($node['confirm']) || !$node['confirm']) { + if (! isset($node['confirm']) || ! $node['confirm']) { continue; } diff --git a/src/Appwrite/Auth/Hash.php b/src/Appwrite/Auth/Hash.php index 7134057581..caf4771fcd 100644 --- a/src/Appwrite/Auth/Hash.php +++ b/src/Appwrite/Auth/Hash.php @@ -5,13 +5,13 @@ namespace Appwrite\Auth; abstract class Hash { /** - * @var array $options Hashing-algo specific options - */ + * @var array Hashing-algo specific options + */ protected array $options = []; /** - * @param array $options Hashing-algo specific options - */ + * @param array $options Hashing-algo specific options + */ public function __construct(array $options = []) { $this->setOptions($options); @@ -20,11 +20,12 @@ abstract class Hash /** * Set hashing algo options * - * @param array $options Hashing-algo specific options - */ + * @param array $options Hashing-algo specific options + */ public function setOptions(array $options): self { $this->options = \array_merge([], $this->getDefaultOptions(), $options); + return $this; } @@ -32,24 +33,22 @@ abstract class Hash * Get hashing algo options * * @return array $options Hashing-algo specific options - */ + */ public function getOptions(): array { return $this->options; } /** - * @param string $password Input password to hash - * + * @param string $password Input password to hash * @return string hash */ abstract public function hash(string $password): string; /** - * @param string $password Input password to validate - * @param string $hash Hash to verify password against - * - * @return boolean true if password matches hash + * @param string $password Input password to validate + * @param string $hash Hash to verify password against + * @return bool true if password matches hash */ abstract public function verify(string $password, string $hash): bool; diff --git a/src/Appwrite/Auth/Hash/Argon2.php b/src/Appwrite/Auth/Hash/Argon2.php index c723b077b1..0e9c2fcf36 100644 --- a/src/Appwrite/Auth/Hash/Argon2.php +++ b/src/Appwrite/Auth/Hash/Argon2.php @@ -15,8 +15,7 @@ use Appwrite\Auth\Hash; class Argon2 extends Hash { /** - * @param string $password Input password to hash - * + * @param string $password Input password to hash * @return string hash */ public function hash(string $password): string @@ -25,10 +24,9 @@ class Argon2 extends Hash } /** - * @param string $password Input password to validate - * @param string $hash Hash to verify password against - * - * @return boolean true if password matches hash + * @param string $password Input password to validate + * @param string $hash Hash to verify password against + * @return bool true if password matches hash */ public function verify(string $password, string $hash): bool { diff --git a/src/Appwrite/Auth/Hash/Bcrypt.php b/src/Appwrite/Auth/Hash/Bcrypt.php index 8b6177f33a..c54cf3d452 100644 --- a/src/Appwrite/Auth/Hash/Bcrypt.php +++ b/src/Appwrite/Auth/Hash/Bcrypt.php @@ -14,8 +14,7 @@ use Appwrite\Auth\Hash; class Bcrypt extends Hash { /** - * @param string $password Input password to hash - * + * @param string $password Input password to hash * @return string hash */ public function hash(string $password): string @@ -24,10 +23,9 @@ class Bcrypt extends Hash } /** - * @param string $password Input password to validate - * @param string $hash Hash to verify password against - * - * @return boolean true if password matches hash + * @param string $password Input password to validate + * @param string $hash Hash to verify password against + * @return bool true if password matches hash */ public function verify(string $password, string $hash): bool { @@ -41,6 +39,6 @@ class Bcrypt extends Hash */ public function getDefaultOptions(): array { - return [ 'cost' => 8 ]; + return ['cost' => 8]; } } diff --git a/src/Appwrite/Auth/Hash/Md5.php b/src/Appwrite/Auth/Hash/Md5.php index 8ade3dd5e2..0f6fe5c30d 100644 --- a/src/Appwrite/Auth/Hash/Md5.php +++ b/src/Appwrite/Auth/Hash/Md5.php @@ -12,8 +12,7 @@ use Appwrite\Auth\Hash; class Md5 extends Hash { /** - * @param string $password Input password to hash - * + * @param string $password Input password to hash * @return string hash */ public function hash(string $password): string @@ -22,10 +21,9 @@ class Md5 extends Hash } /** - * @param string $password Input password to validate - * @param string $hash Hash to verify password against - * - * @return boolean true if password matches hash + * @param string $password Input password to validate + * @param string $hash Hash to verify password against + * @return bool true if password matches hash */ public function verify(string $password, string $hash): bool { diff --git a/src/Appwrite/Auth/Hash/Phpass.php b/src/Appwrite/Auth/Hash/Phpass.php index 187e4a27a6..ded4e407ff 100644 --- a/src/Appwrite/Auth/Hash/Phpass.php +++ b/src/Appwrite/Auth/Hash/Phpass.php @@ -39,6 +39,7 @@ class Phpass extends Hash * Alphabet used in itoa64 conversions. * * @var string + * * @since 0.1.0 */ protected string $itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; @@ -59,8 +60,7 @@ class Phpass extends Hash } /** - * @param string $password Input password to hash - * + * @param string $password Input password to hash * @return string hash */ public function hash(string $password): string @@ -68,7 +68,7 @@ class Phpass extends Hash $options = $this->getDefaultOptions(); $random = ''; - if (CRYPT_BLOWFISH === 1 && !$options['portable_hashes']) { + if (CRYPT_BLOWFISH === 1 && ! $options['portable_hashes']) { $random = $this->getRandomBytes(16, $options); $hash = crypt($password, $this->gensaltBlowfish($random, $options)); if (strlen($hash) === 60) { @@ -92,10 +92,9 @@ class Phpass extends Hash } /** - * @param string $password Input password to validate - * @param string $hash Hash to verify password against - * - * @return boolean true if password matches hash + * @param string $password Input password to validate + * @param string $hash Hash to verify password against + * @return bool true if password matches hash */ public function verify(string $password, string $hash): bool { @@ -114,15 +113,16 @@ class Phpass extends Hash } /** - * @param int $count + * @param int $count + * @return string $output * - * @return String $output * @since 0.1.0 + * * @throws Exception Thows an Exception if the $count parameter is not a positive integer. */ protected function getRandomBytes(int $count, array $options): string { - if (!is_int($count) || $count < 1) { + if (! is_int($count) || $count < 1) { throw new \Exception('Argument count must be a positive integer'); } $output = ''; @@ -135,7 +135,7 @@ class Phpass extends Hash $output = ''; for ($i = 0; $i < $count; $i += 16) { - $options['iteration_count_log2'] = md5(microtime() . $options['iteration_count_log2']); + $options['iteration_count_log2'] = md5(microtime().$options['iteration_count_log2']); $output .= md5($options['iteration_count_log2'], true); } @@ -146,47 +146,48 @@ class Phpass extends Hash } /** - * @param String $input - * @param int $count + * @param string $input + * @param int $count + * @return string $output * - * @return String $output * @since 0.1.0 + * * @throws Exception Thows an Exception if the $count parameter is not a positive integer. */ protected function encode64($input, $count) { - if (!is_int($count) || $count < 1) { + if (! is_int($count) || $count < 1) { throw new \Exception('Argument count must be a positive integer'); } $output = ''; $i = 0; do { $value = ord($input[$i++]); - $output .= $this->itoa64[$value & 0x3f]; + $output .= $this->itoa64[$value & 0x3F]; if ($i < $count) { $value |= ord($input[$i]) << 8; } - $output .= $this->itoa64[($value >> 6) & 0x3f]; + $output .= $this->itoa64[($value >> 6) & 0x3F]; if ($i++ >= $count) { break; } if ($i < $count) { $value |= ord($input[$i]) << 16; } - $output .= $this->itoa64[($value >> 12) & 0x3f]; + $output .= $this->itoa64[($value >> 12) & 0x3F]; if ($i++ >= $count) { break; } - $output .= $this->itoa64[($value >> 18) & 0x3f]; + $output .= $this->itoa64[($value >> 18) & 0x3F]; } while ($i < $count); return $output; } /** - * @param String $input + * @param string $input + * @return string $output * - * @return String $output * @since 0.1.0 */ private function gensaltPrivate($input, $options) @@ -199,10 +200,10 @@ class Phpass extends Hash } /** - * @param String $password - * @param String $setting + * @param string $password + * @param string $setting + * @return string $output * - * @return String $output * @since 0.1.0 */ private function cryptPrivate($password, $setting) @@ -233,9 +234,9 @@ class Phpass extends Hash * consequently in lower iteration counts and hashes that are * quicker to crack (by non-PHP code). */ - $hash = md5($salt . $password, true); + $hash = md5($salt.$password, true); do { - $hash = md5($hash . $password, true); + $hash = md5($hash.$password, true); } while (--$count); $output = substr($setting, 0, 12); $output .= $this->encode64($hash, 16); @@ -244,9 +245,9 @@ class Phpass extends Hash } /** - * @param String $input + * @param string $input + * @return string $output * - * @return String $output * @since 0.1.0 */ private function gensaltBlowfish($input, $options) @@ -278,11 +279,11 @@ class Phpass extends Hash $c2 = ord($input[$i++]); $c1 |= $c2 >> 4; $output .= $itoa64[$c1]; - $c1 = ($c2 & 0x0f) << 2; + $c1 = ($c2 & 0x0F) << 2; $c2 = ord($input[$i++]); $c1 |= $c2 >> 6; $output .= $itoa64[$c1]; - $output .= $itoa64[$c2 & 0x3f]; + $output .= $itoa64[$c2 & 0x3F]; } while (1); return $output; diff --git a/src/Appwrite/Auth/Hash/Scrypt.php b/src/Appwrite/Auth/Hash/Scrypt.php index 821b1fba69..8c50c16341 100644 --- a/src/Appwrite/Auth/Hash/Scrypt.php +++ b/src/Appwrite/Auth/Hash/Scrypt.php @@ -17,8 +17,7 @@ use Appwrite\Auth\Hash; class Scrypt extends Hash { /** - * @param string $password Input password to hash - * + * @param string $password Input password to hash * @return string hash */ public function hash(string $password): string @@ -29,10 +28,9 @@ class Scrypt extends Hash } /** - * @param string $password Input password to validate - * @param string $hash Hash to verify password against - * - * @return boolean true if password matches hash + * @param string $password Input password to validate + * @param string $hash Hash to verify password against + * @return bool true if password matches hash */ public function verify(string $password, string $hash): bool { @@ -46,6 +44,6 @@ class Scrypt extends Hash */ public function getDefaultOptions(): array { - return [ 'costCpu' => 8, 'costMemory' => 14, 'costParallel' => 1, 'length' => 64 ]; + return ['costCpu' => 8, 'costMemory' => 14, 'costParallel' => 1, 'length' => 64]; } } diff --git a/src/Appwrite/Auth/Hash/Scryptmodified.php b/src/Appwrite/Auth/Hash/Scryptmodified.php index 2d1cd4f165..9260913aed 100644 --- a/src/Appwrite/Auth/Hash/Scryptmodified.php +++ b/src/Appwrite/Auth/Hash/Scryptmodified.php @@ -16,8 +16,7 @@ use Appwrite\Auth\Hash; class Scryptmodified extends Hash { /** - * @param string $password Input password to hash - * + * @param string $password Input password to hash * @return string hash */ public function hash(string $password): string @@ -33,10 +32,9 @@ class Scryptmodified extends Hash } /** - * @param string $password Input password to validate - * @param string $hash Hash to verify password against - * - * @return boolean true if password matches hash + * @param string $password Input password to validate + * @param string $hash Hash to verify password against + * @return bool true if password matches hash */ public function verify(string $password, string $hash): bool { @@ -50,7 +48,7 @@ class Scryptmodified extends Hash */ public function getDefaultOptions(): array { - return [ ]; + return []; } private function generateDerivedKey(string $password) @@ -60,7 +58,7 @@ class Scryptmodified extends Hash $saltBytes = \base64_decode($options['salt']); $saltSeparatorBytes = \base64_decode($options['saltSeparator']); - $derivedKey = \scrypt(\utf8_encode($password), $saltBytes . $saltSeparatorBytes, 16384, 8, 1, 64); + $derivedKey = \scrypt(\utf8_encode($password), $saltBytes.$saltSeparatorBytes, 16384, 8, 1, 64); $derivedKey = \hex2bin($derivedKey); return $derivedKey; diff --git a/src/Appwrite/Auth/Hash/Sha.php b/src/Appwrite/Auth/Hash/Sha.php index c2ae3b52c1..331c4fe6f2 100644 --- a/src/Appwrite/Auth/Hash/Sha.php +++ b/src/Appwrite/Auth/Hash/Sha.php @@ -16,8 +16,7 @@ use Appwrite\Auth\Hash; class Sha extends Hash { /** - * @param string $password Input password to hash - * + * @param string $password Input password to hash * @return string hash */ public function hash(string $password): string @@ -28,10 +27,9 @@ class Sha extends Hash } /** - * @param string $password Input password to validate - * @param string $hash Hash to verify password against - * - * @return boolean true if password matches hash + * @param string $password Input password to validate + * @param string $hash Hash to verify password against + * @return bool true if password matches hash */ public function verify(string $password, string $hash): bool { @@ -45,6 +43,6 @@ class Sha extends Hash */ public function getDefaultOptions(): array { - return [ 'version' => 'sha3-512' ]; + return ['version' => 'sha3-512']; } } diff --git a/src/Appwrite/Auth/OAuth2.php b/src/Appwrite/Auth/OAuth2.php index d7c1c99546..ab56e10901 100644 --- a/src/Appwrite/Auth/OAuth2.php +++ b/src/Appwrite/Auth/OAuth2.php @@ -32,11 +32,11 @@ abstract class OAuth2 /** * OAuth2 constructor. * - * @param string $appId - * @param string $appSecret - * @param string $callback - * @param array $state - * @param array $scopes + * @param string $appId + * @param string $appSecret + * @param string $callback + * @param array $state + * @param array $scopes */ public function __construct(string $appId, string $appSecret, string $callback, array $state = [], array $scopes = []) { @@ -60,22 +60,19 @@ abstract class OAuth2 abstract public function getLoginURL(): string; /** - * @param string $code - * + * @param string $code * @return array */ abstract protected function getTokens(string $code): array; /** - * @param string $refreshToken - * + * @param string $refreshToken * @return array */ abstract public function refreshTokens(string $refreshToken): array; /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ abstract public function getUserEmail(string $accessToken): string; @@ -83,28 +80,25 @@ abstract class OAuth2 /** * Check if the OAuth email is verified * - * @param string $accessToken - * + * @param string $accessToken * @return bool */ abstract public function isEmailVerified(string $accessToken): bool; /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ abstract public function getUserName(string $accessToken): string; /** * @param $scope - * * @return $this */ protected function addScope(string $scope): OAuth2 { // Add a scope to the scopes array if it isn't already present - if (!\in_array($scope, $this->scopes)) { + if (! \in_array($scope, $this->scopes)) { $this->scopes[] = $scope; } @@ -120,8 +114,7 @@ abstract class OAuth2 } /** - * @param string $code - * + * @param string $code * @return string */ public function getAccessToken(string $code): string @@ -132,8 +125,7 @@ abstract class OAuth2 } /** - * @param string $code - * + * @param string $code * @return string */ public function getRefreshToken(string $code): string @@ -144,8 +136,7 @@ abstract class OAuth2 } /** - * @param string $code - * + * @param string $code * @return string */ public function getAccessTokenExpiry(string $code): string @@ -160,7 +151,6 @@ abstract class OAuth2 // json_decoding /** * @param $state - * * @return array */ public function parseState(string $state) @@ -169,11 +159,10 @@ abstract class OAuth2 } /** - * @param string $method - * @param string $url - * @param array $headers - * @param string $payload - * + * @param string $method + * @param string $url + * @param array $headers + * @param string $payload * @return string */ protected function request(string $method, string $url = '', array $headers = [], string $payload = ''): string @@ -185,11 +174,11 @@ abstract class OAuth2 \curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); \curl_setopt($ch, CURLOPT_USERAGENT, 'Appwrite OAuth2'); - if (!empty($payload)) { + if (! empty($payload)) { \curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); } - $headers[] = 'Content-length: ' . \strlen($payload); + $headers[] = 'Content-length: '.\strlen($payload); \curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); // Send the request & save response to $response @@ -197,6 +186,6 @@ abstract class OAuth2 \curl_close($ch); - return (string)$response; + return (string) $response; } } diff --git a/src/Appwrite/Auth/OAuth2/Amazon.php b/src/Appwrite/Auth/OAuth2/Amazon.php index d1d2cb5a38..c2cdedf2f1 100644 --- a/src/Appwrite/Auth/OAuth2/Amazon.php +++ b/src/Appwrite/Auth/OAuth2/Amazon.php @@ -25,7 +25,7 @@ class Amazon extends OAuth2 * @var array */ protected array $scopes = [ - "profile" + 'profile', ]; /** @@ -37,8 +37,7 @@ class Amazon extends OAuth2 } /** - * @param string $state - * + * @param string $state * @return array */ public function parseState(string $state) @@ -46,24 +45,22 @@ class Amazon extends OAuth2 return \json_decode(\html_entity_decode($state), true); } - /** * @return string */ public function getLoginURL(): string { - return 'https://www.amazon.com/ap/oa?' . \http_build_query([ + return 'https://www.amazon.com/ap/oa?'.\http_build_query([ 'response_type' => 'code', 'client_id' => $this->appID, 'scope' => \implode(' ', $this->getScopes()), 'state' => \json_encode($this->state), - 'redirect_uri' => $this->callback + 'redirect_uri' => $this->callback, ]); } /** - * @param string $code - * + * @param string $code * @return array */ protected function getTokens(string $code): array @@ -79,7 +76,7 @@ class Amazon extends OAuth2 'client_id' => $this->appID, 'client_secret' => $this->appSecret, 'redirect_uri' => $this->callback, - 'grant_type' => 'authorization_code' + 'grant_type' => 'authorization_code', ]) ), true); } @@ -88,8 +85,7 @@ class Amazon extends OAuth2 } /** - * @param string $refreshToken - * + * @param string $refreshToken * @return array */ public function refreshTokens(string $refreshToken): array @@ -103,7 +99,7 @@ class Amazon extends OAuth2 'client_id' => $this->appID, 'client_secret' => $this->appSecret, 'grant_type' => 'refresh_token', - 'refresh_token' => $refreshToken + 'refresh_token' => $refreshToken, ]) ), true); @@ -115,8 +111,7 @@ class Amazon extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserID(string $accessToken): string @@ -127,8 +122,7 @@ class Amazon extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserEmail(string $accessToken): string @@ -143,20 +137,18 @@ class Amazon extends OAuth2 * * If present, the email is verified. This was verfied through a manual Amazon sign up process * - * @param string $accessToken - * + * @param string $accessToken * @return bool */ public function isEmailVerified(string $accessToken): bool { $email = $this->getUserEmail($accessToken); - return !empty($email); + return ! empty($email); } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserName(string $accessToken): string @@ -167,16 +159,16 @@ class Amazon extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return array */ protected function getUser(string $accessToken): array { if (empty($this->user)) { - $user = $this->request('GET', 'https://api.amazon.com/user/profile?access_token=' . \urlencode($accessToken)); + $user = $this->request('GET', 'https://api.amazon.com/user/profile?access_token='.\urlencode($accessToken)); $this->user = \json_decode($user, true); } + return $this->user; } } diff --git a/src/Appwrite/Auth/OAuth2/Apple.php b/src/Appwrite/Auth/OAuth2/Apple.php index 2abf61c947..27f41543ae 100644 --- a/src/Appwrite/Auth/OAuth2/Apple.php +++ b/src/Appwrite/Auth/OAuth2/Apple.php @@ -24,8 +24,8 @@ class Apple extends OAuth2 * @var array */ protected array $scopes = [ - "name", - "email" + 'name', + 'email', ]; /** @@ -46,19 +46,18 @@ class Apple extends OAuth2 */ public function getLoginURL(): string { - return 'https://appleid.apple.com/auth/authorize?' . \http_build_query([ + return 'https://appleid.apple.com/auth/authorize?'.\http_build_query([ 'client_id' => $this->appID, 'redirect_uri' => $this->callback, 'state' => \json_encode($this->state), 'response_type' => 'code', 'response_mode' => 'form_post', - 'scope' => \implode(' ', $this->getScopes()) + 'scope' => \implode(' ', $this->getScopes()), ]); } /** - * @param string $code - * + * @param string $code * @return array */ protected function getTokens(string $code): array @@ -86,8 +85,7 @@ class Apple extends OAuth2 } /** - * @param string $refreshToken - * + * @param string $refreshToken * @return array */ public function refreshTokens(string $refreshToken): array @@ -116,8 +114,7 @@ class Apple extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserID(string $accessToken): string @@ -126,8 +123,7 @@ class Apple extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserEmail(string $accessToken): string @@ -140,8 +136,7 @@ class Apple extends OAuth2 * * @link https://developer.apple.com/forums/thread/121411 * - * @param string $accessToken - * + * @param string $accessToken * @return bool */ public function isEmailVerified(string $accessToken): bool @@ -154,15 +149,14 @@ class Apple extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserName(string $accessToken): string { if ( isset($this->claims['email']) && - !empty($this->claims['email']) && + ! empty($this->claims['email']) && isset($this->claims['email_verified']) && $this->claims['email_verified'] === 'true' ) { @@ -183,7 +177,7 @@ class Apple extends OAuth2 $keyfile = (isset($secret['p8'])) ? $secret['p8'] : ''; // Your p8 Key file $keyID = (isset($secret['keyID'])) ? $secret['keyID'] : ''; // Your Key ID $teamID = (isset($secret['teamID'])) ? $secret['teamID'] : ''; // Your Team ID (see Developer Portal) - $bundleID = $this->appID; // Your Bundle ID + $bundleID = $this->appID; // Your Bundle ID $headers = [ 'alg' => 'ES256', @@ -200,22 +194,21 @@ class Apple extends OAuth2 $pkey = \openssl_pkey_get_private($keyfile); - $payload = $this->encode(\json_encode($headers)) . '.' . $this->encode(\json_encode($claims)); + $payload = $this->encode(\json_encode($headers)).'.'.$this->encode(\json_encode($claims)); $signature = ''; $success = \openssl_sign($payload, $signature, $pkey, OPENSSL_ALGO_SHA256); - if (!$success) { + if (! $success) { return ''; } - return $payload . '.' . $this->encode($this->fromDER($signature, 64)); + return $payload.'.'.$this->encode($this->fromDER($signature, 64)); } /** - * @param string $data - * + * @param string $data * @return string */ protected function encode($data): string @@ -224,7 +217,7 @@ class Apple extends OAuth2 } /** - * @param string $data + * @param string $data */ protected function retrievePositiveInteger(string $data): string { @@ -236,8 +229,8 @@ class Apple extends OAuth2 } /** - * @param string $der - * @param int $partLength + * @param string $der + * @param int $partLength */ protected function fromDER(string $der, int $partLength): string { @@ -270,6 +263,6 @@ class Apple extends OAuth2 $S = $this->retrievePositiveInteger(\mb_substr($hex, 4, $Sl * 2, '8bit')); $S = \str_pad($S, $partLength, '0', STR_PAD_LEFT); - return \pack('H*', $R . $S); + return \pack('H*', $R.$S); } } diff --git a/src/Appwrite/Auth/OAuth2/Auth0.php b/src/Appwrite/Auth/OAuth2/Auth0.php index eba7d18b5f..e2615017bd 100644 --- a/src/Appwrite/Auth/OAuth2/Auth0.php +++ b/src/Appwrite/Auth/OAuth2/Auth0.php @@ -16,7 +16,7 @@ class Auth0 extends OAuth2 'openid', 'profile', 'email', - 'offline_access' + 'offline_access', ]; /** @@ -42,18 +42,17 @@ class Auth0 extends OAuth2 */ public function getLoginURL(): string { - return 'https://' . $this->getAuth0Domain() . '/authorize?' . \http_build_query([ + return 'https://'.$this->getAuth0Domain().'/authorize?'.\http_build_query([ 'client_id' => $this->appID, 'redirect_uri' => $this->callback, 'state' => \json_encode($this->state), 'scope' => \implode(' ', $this->getScopes()), - 'response_type' => 'code' + 'response_type' => 'code', ]); } /** - * @param string $code - * + * @param string $code * @return array */ protected function getTokens(string $code): array @@ -62,7 +61,7 @@ class Auth0 extends OAuth2 $headers = ['Content-Type: application/x-www-form-urlencoded']; $this->tokens = \json_decode($this->request( 'POST', - 'https://' . $this->getAuth0Domain() . '/oauth/token', + 'https://'.$this->getAuth0Domain().'/oauth/token', $headers, \http_build_query([ 'code' => $code, @@ -70,7 +69,7 @@ class Auth0 extends OAuth2 'client_secret' => $this->getClientSecret(), 'redirect_uri' => $this->callback, 'scope' => \implode(' ', $this->getScopes()), - 'grant_type' => 'authorization_code' + 'grant_type' => 'authorization_code', ]) ), true); } @@ -78,10 +77,8 @@ class Auth0 extends OAuth2 return $this->tokens; } - /** - * @param string $refreshToken - * + * @param string $refreshToken * @return array */ public function refreshTokens(string $refreshToken): array @@ -89,13 +86,13 @@ class Auth0 extends OAuth2 $headers = ['Content-Type: application/x-www-form-urlencoded']; $this->tokens = \json_decode($this->request( 'POST', - 'https://' . $this->getAuth0Domain() . '/oauth/token', + 'https://'.$this->getAuth0Domain().'/oauth/token', $headers, \http_build_query([ 'refresh_token' => $refreshToken, 'client_id' => $this->appID, 'client_secret' => $this->getClientSecret(), - 'grant_type' => 'refresh_token' + 'grant_type' => 'refresh_token', ]) ), true); @@ -107,8 +104,7 @@ class Auth0 extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserID(string $accessToken): string @@ -119,8 +115,7 @@ class Auth0 extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserEmail(string $accessToken): string @@ -135,8 +130,7 @@ class Auth0 extends OAuth2 * * @link https://auth0.com/docs/api/authentication?javascript#user-profile * - * @param string $accessToken - * + * @param string $accessToken * @return bool */ public function isEmailVerified(string $accessToken): bool @@ -151,8 +145,7 @@ class Auth0 extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserName(string $accessToken): string @@ -163,15 +156,14 @@ class Auth0 extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return array */ protected function getUser(string $accessToken): array { if (empty($this->user)) { - $headers = ['Authorization: Bearer ' . \urlencode($accessToken)]; - $user = $this->request('GET', 'https://' . $this->getAuth0Domain() . '/userinfo', $headers); + $headers = ['Authorization: Bearer '.\urlencode($accessToken)]; + $user = $this->request('GET', 'https://'.$this->getAuth0Domain().'/userinfo', $headers); $this->user = \json_decode($user, true); } @@ -214,6 +206,7 @@ class Auth0 extends OAuth2 } catch (\Throwable $th) { throw new \Exception('Invalid secret'); } + return $secret; } } diff --git a/src/Appwrite/Auth/OAuth2/Authentik.php b/src/Appwrite/Auth/OAuth2/Authentik.php index 16822e2c9f..8a6b13cdef 100644 --- a/src/Appwrite/Auth/OAuth2/Authentik.php +++ b/src/Appwrite/Auth/OAuth2/Authentik.php @@ -16,7 +16,7 @@ class Authentik extends OAuth2 'openid', 'profile', 'email', - 'offline_access' + 'offline_access', ]; /** @@ -42,18 +42,17 @@ class Authentik extends OAuth2 */ public function getLoginURL(): string { - return 'https://' . $this->getAuthentikDomain() . '/application/o/authorize?' . \http_build_query([ + return 'https://'.$this->getAuthentikDomain().'/application/o/authorize?'.\http_build_query([ 'client_id' => $this->appID, 'redirect_uri' => $this->callback, 'state' => \json_encode($this->state), 'scope' => \implode(' ', $this->getScopes()), - 'response_type' => 'code' + 'response_type' => 'code', ]); } /** - * @param string $code - * + * @param string $code * @return array */ protected function getTokens(string $code): array @@ -62,7 +61,7 @@ class Authentik extends OAuth2 $headers = ['Content-Type: application/x-www-form-urlencoded']; $this->tokens = \json_decode($this->request( 'POST', - 'https://' . $this->getAuthentikDomain() . '/application/o/token/', + 'https://'.$this->getAuthentikDomain().'/application/o/token/', $headers, \http_build_query([ 'code' => $code, @@ -70,17 +69,16 @@ class Authentik extends OAuth2 'client_secret' => $this->getClientSecret(), 'redirect_uri' => $this->callback, 'scope' => \implode(' ', $this->getScopes()), - 'grant_type' => 'authorization_code' + 'grant_type' => 'authorization_code', ]) ), true); } + return $this->tokens; } - /** - * @param string $refreshToken - * + * @param string $refreshToken * @return array */ public function refreshTokens(string $refreshToken): array @@ -88,13 +86,13 @@ class Authentik extends OAuth2 $headers = ['Content-Type: application/x-www-form-urlencoded']; $this->tokens = \json_decode($this->request( 'POST', - 'https://' . $this->getAuthentikDomain() . '/application/o/token/', + 'https://'.$this->getAuthentikDomain().'/application/o/token/', $headers, \http_build_query([ 'refresh_token' => $refreshToken, 'client_id' => $this->appID, 'client_secret' => $this->getClientSecret(), - 'grant_type' => 'refresh_token' + 'grant_type' => 'refresh_token', ]) ), true); @@ -106,8 +104,7 @@ class Authentik extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserID(string $accessToken): string @@ -122,8 +119,7 @@ class Authentik extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserEmail(string $accessToken): string @@ -140,8 +136,7 @@ class Authentik extends OAuth2 /** * Check if the User email is verified * - * @param string $accessToken - * + * @param string $accessToken * @return bool */ public function isEmailVerified(string $accessToken): bool @@ -156,8 +151,7 @@ class Authentik extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserName(string $accessToken): string @@ -171,16 +165,15 @@ class Authentik extends OAuth2 return ''; } - /** - * @param string $accessToken - * + /** + * @param string $accessToken * @return array */ protected function getUser(string $accessToken): array { if (empty($this->user)) { - $headers = ['Authorization: Bearer ' . \urlencode($accessToken)]; - $user = $this->request('GET', 'https://' . $this->getAuthentikDomain() . '/application/o/userinfo/', $headers); + $headers = ['Authorization: Bearer '.\urlencode($accessToken)]; + $user = $this->request('GET', 'https://'.$this->getAuthentikDomain().'/application/o/userinfo/', $headers); $this->user = \json_decode($user, true); } @@ -199,7 +192,7 @@ class Authentik extends OAuth2 return $secret['clientSecret'] ?? ''; } - /** + /** * Extracts the authentik Domain from the JSON stored in appSecret * * @return string @@ -207,6 +200,7 @@ class Authentik extends OAuth2 protected function getAuthentikDomain(): string { $secret = $this->getAppSecret(); + return $secret['authentikDomain'] ?? ''; } @@ -222,6 +216,7 @@ class Authentik extends OAuth2 } catch (\Throwable $th) { throw new \Exception('Invalid secret'); } + return $secret; } } diff --git a/src/Appwrite/Auth/OAuth2/Autodesk.php b/src/Appwrite/Auth/OAuth2/Autodesk.php index 0b268ead3b..071eee7dcb 100644 --- a/src/Appwrite/Auth/OAuth2/Autodesk.php +++ b/src/Appwrite/Auth/OAuth2/Autodesk.php @@ -36,18 +36,17 @@ class Autodesk extends OAuth2 */ public function getLoginURL(): string { - return 'https://developer.api.autodesk.com/authentication/v1/authorize?' . \http_build_query([ + return 'https://developer.api.autodesk.com/authentication/v1/authorize?'.\http_build_query([ 'client_id' => $this->appID, 'scope' => \implode(' ', $this->getScopes()), 'state' => \json_encode($this->state), 'redirect_uri' => $this->callback, - 'response_type' => 'code' + 'response_type' => 'code', ]); } /** - * @param string $code - * + * @param string $code * @return array */ protected function getTokens(string $code): array @@ -63,7 +62,7 @@ class Autodesk extends OAuth2 'redirect_uri' => $this->callback, 'client_secret' => $this->appSecret, 'code' => $code, - 'grant_type' => 'authorization_code' + 'grant_type' => 'authorization_code', ]) ); @@ -74,8 +73,7 @@ class Autodesk extends OAuth2 } /** - * @param string $refreshToken - * + * @param string $refreshToken * @return array */ public function refreshTokens(string $refreshToken): array @@ -105,8 +103,7 @@ class Autodesk extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserID(string $accessToken): string @@ -117,8 +114,7 @@ class Autodesk extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserEmail(string $accessToken): string @@ -133,8 +129,7 @@ class Autodesk extends OAuth2 * * @link https://docs.github.com/en/rest/users/emails#list-email-addresses-for-the-authenticated-user * - * @param string $accessToken - * + * @param string $accessToken * @return bool */ public function isEmailVerified(string $accessToken): bool @@ -149,8 +144,7 @@ class Autodesk extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserName(string $accessToken): string @@ -161,14 +155,13 @@ class Autodesk extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return array */ protected function getUser(string $accessToken): array { if (empty($this->user)) { - $headers = ['Authorization: Bearer ' . \urlencode($accessToken)]; + $headers = ['Authorization: Bearer '.\urlencode($accessToken)]; $user = $this->request('GET', 'https://developer.api.autodesk.com/userprofile/v1/users/@me', $headers); $this->user = \json_decode($user, true); } diff --git a/src/Appwrite/Auth/OAuth2/Bitbucket.php b/src/Appwrite/Auth/OAuth2/Bitbucket.php index 361bc22b65..eea5af4c1b 100644 --- a/src/Appwrite/Auth/OAuth2/Bitbucket.php +++ b/src/Appwrite/Auth/OAuth2/Bitbucket.php @@ -37,7 +37,7 @@ class Bitbucket extends OAuth2 */ public function getLoginURL(): string { - return 'https://bitbucket.org/site/oauth2/authorize?' . \http_build_query([ + return 'https://bitbucket.org/site/oauth2/authorize?'.\http_build_query([ 'response_type' => 'code', 'client_id' => $this->appID, 'scope' => \implode(' ', $this->getScopes()), @@ -46,8 +46,7 @@ class Bitbucket extends OAuth2 } /** - * @param string $code - * + * @param string $code * @return array */ protected function getTokens(string $code): array @@ -63,7 +62,7 @@ class Bitbucket extends OAuth2 'code' => $code, 'client_id' => $this->appID, 'client_secret' => $this->appSecret, - 'grant_type' => 'authorization_code' + 'grant_type' => 'authorization_code', ]) ), true); } @@ -72,8 +71,7 @@ class Bitbucket extends OAuth2 } /** - * @param string $refreshToken - * + * @param string $refreshToken * @return array */ public function refreshTokens(string $refreshToken): array @@ -87,7 +85,7 @@ class Bitbucket extends OAuth2 'client_id' => $this->appID, 'client_secret' => $this->appSecret, 'grant_type' => 'refresh_token', - 'refresh_token' => $refreshToken + 'refresh_token' => $refreshToken, ]) ), true); @@ -99,8 +97,7 @@ class Bitbucket extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserID(string $accessToken): string @@ -111,8 +108,7 @@ class Bitbucket extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserEmail(string $accessToken): string @@ -125,8 +121,7 @@ class Bitbucket extends OAuth2 /** * Check if the OAuth email is verified * - * @param string $accessToken - * + * @param string $accessToken * @return bool */ public function isEmailVerified(string $accessToken): bool @@ -141,8 +136,7 @@ class Bitbucket extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserName(string $accessToken): string @@ -153,17 +147,16 @@ class Bitbucket extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return array */ protected function getUser(string $accessToken): array { if (empty($this->user)) { - $user = $this->request('GET', 'https://api.bitbucket.org/2.0/user?access_token=' . \urlencode($accessToken)); + $user = $this->request('GET', 'https://api.bitbucket.org/2.0/user?access_token='.\urlencode($accessToken)); $this->user = \json_decode($user, true); - $emails = $this->request('GET', 'https://api.bitbucket.org/2.0/user/emails?access_token=' . \urlencode($accessToken)); + $emails = $this->request('GET', 'https://api.bitbucket.org/2.0/user/emails?access_token='.\urlencode($accessToken)); $emails = \json_decode($emails, true); if (isset($emails['values'])) { foreach ($emails['values'] as $email) { @@ -175,6 +168,7 @@ class Bitbucket extends OAuth2 } } } + return $this->user; } } diff --git a/src/Appwrite/Auth/OAuth2/Bitly.php b/src/Appwrite/Auth/OAuth2/Bitly.php index 290876a8cb..b5521cad39 100644 --- a/src/Appwrite/Auth/OAuth2/Bitly.php +++ b/src/Appwrite/Auth/OAuth2/Bitly.php @@ -47,17 +47,16 @@ class Bitly extends OAuth2 */ public function getLoginURL(): string { - return $this->endpoint . 'authorize?' . + return $this->endpoint.'authorize?'. \http_build_query([ 'client_id' => $this->appID, 'redirect_uri' => $this->callback, - 'state' => \json_encode($this->state) + 'state' => \json_encode($this->state), ]); } /** - * @param string $code - * + * @param string $code * @return array */ protected function getTokens(string $code): array @@ -65,14 +64,14 @@ class Bitly extends OAuth2 if (empty($this->tokens)) { $response = $this->request( 'POST', - $this->resourceEndpoint . 'oauth/access_token', - ["Content-Type: application/x-www-form-urlencoded"], + $this->resourceEndpoint.'oauth/access_token', + ['Content-Type: application/x-www-form-urlencoded'], \http_build_query([ - "client_id" => $this->appID, - "client_secret" => $this->appSecret, - "code" => $code, - "redirect_uri" => $this->callback, - "state" => \json_encode($this->state) + 'client_id' => $this->appID, + 'client_secret' => $this->appSecret, + 'code' => $code, + 'redirect_uri' => $this->callback, + 'state' => \json_encode($this->state), ]) ); @@ -85,21 +84,20 @@ class Bitly extends OAuth2 } /** - * @param string $refreshToken - * + * @param string $refreshToken * @return array */ public function refreshTokens(string $refreshToken): array { $response = $this->request( 'POST', - $this->resourceEndpoint . 'oauth/access_token', - ["Content-Type: application/x-www-form-urlencoded"], + $this->resourceEndpoint.'oauth/access_token', + ['Content-Type: application/x-www-form-urlencoded'], \http_build_query([ - "client_id" => $this->appID, - "client_secret" => $this->appSecret, - "refresh_token" => $refreshToken, - 'grant_type' => 'refresh_token' + 'client_id' => $this->appID, + 'client_secret' => $this->appSecret, + 'refresh_token' => $refreshToken, + 'grant_type' => 'refresh_token', ]) ); @@ -115,8 +113,7 @@ class Bitly extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserID(string $accessToken): string @@ -127,8 +124,7 @@ class Bitly extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserEmail(string $accessToken): string @@ -151,8 +147,7 @@ class Bitly extends OAuth2 * * @link https://dev.bitly.com/api-reference#getUser * - * @param string $accessToken - * + * @param string $accessToken * @return bool */ public function isEmailVerified(string $accessToken): bool @@ -161,8 +156,7 @@ class Bitly extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserName(string $accessToken): string @@ -173,19 +167,18 @@ class Bitly extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return array */ protected function getUser(string $accessToken) { $headers = [ - 'Authorization: Bearer ' . \urlencode($accessToken), - "Accept: application/json" + 'Authorization: Bearer '.\urlencode($accessToken), + 'Accept: application/json', ]; if (empty($this->user)) { - $this->user = \json_decode($this->request('GET', $this->resourceEndpoint . "v4/user", $headers), true); + $this->user = \json_decode($this->request('GET', $this->resourceEndpoint.'v4/user', $headers), true); } return $this->user; diff --git a/src/Appwrite/Auth/OAuth2/Box.php b/src/Appwrite/Auth/OAuth2/Box.php index e88c165833..5d2c5e2b38 100644 --- a/src/Appwrite/Auth/OAuth2/Box.php +++ b/src/Appwrite/Auth/OAuth2/Box.php @@ -49,7 +49,7 @@ class Box extends OAuth2 */ public function getLoginURL(): string { - $url = $this->endpoint . 'authorize?' . + $url = $this->endpoint.'authorize?'. \http_build_query([ 'response_type' => 'code', 'client_id' => $this->appID, @@ -62,8 +62,7 @@ class Box extends OAuth2 } /** - * @param string $code - * + * @param string $code * @return array */ protected function getTokens(string $code): array @@ -72,15 +71,15 @@ class Box extends OAuth2 $headers = ['Content-Type: application/x-www-form-urlencoded']; $this->tokens = \json_decode($this->request( 'POST', - $this->endpoint . 'token', + $this->endpoint.'token', $headers, \http_build_query([ - "client_id" => $this->appID, - "client_secret" => $this->appSecret, - "code" => $code, - "grant_type" => "authorization_code", - "scope" => \implode(',', $this->getScopes()), - "redirect_uri" => $this->callback + 'client_id' => $this->appID, + 'client_secret' => $this->appSecret, + 'code' => $code, + 'grant_type' => 'authorization_code', + 'scope' => \implode(',', $this->getScopes()), + 'redirect_uri' => $this->callback, ]) ), true); } @@ -89,8 +88,7 @@ class Box extends OAuth2 } /** - * @param string $refreshToken - * + * @param string $refreshToken * @return array */ public function refreshTokens(string $refreshToken): array @@ -98,13 +96,13 @@ class Box extends OAuth2 $headers = ['Content-Type: application/x-www-form-urlencoded']; $this->tokens = \json_decode($this->request( 'POST', - $this->endpoint . 'token', + $this->endpoint.'token', $headers, \http_build_query([ - "client_id" => $this->appID, - "client_secret" => $this->appSecret, - "refresh_token" => $refreshToken, - "grant_type" => "refresh_token", + 'client_id' => $this->appID, + 'client_secret' => $this->appSecret, + 'refresh_token' => $refreshToken, + 'grant_type' => 'refresh_token', ]) ), true); @@ -116,8 +114,7 @@ class Box extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserID(string $accessToken): string @@ -128,8 +125,7 @@ class Box extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserEmail(string $accessToken): string @@ -144,20 +140,18 @@ class Box extends OAuth2 * * If present, the email is verified. This was verfied through a manual Box sign up process * - * @param string $accessToken - * + * @param string $accessToken * @return bool */ public function isEmailVerified(string $accessToken): bool { $email = $this->getUserEmail($accessToken); - return !empty($email); + return ! empty($email); } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserName(string $accessToken): string @@ -168,19 +162,18 @@ class Box extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return array */ protected function getUser(string $accessToken): array { $header = [ - 'Authorization: Bearer ' . \urlencode($accessToken), + 'Authorization: Bearer '.\urlencode($accessToken), ]; if (empty($this->user)) { $user = $this->request( 'GET', - $this->resourceEndpoint . 'me', + $this->resourceEndpoint.'me', $header ); $this->user = \json_decode($user, true); diff --git a/src/Appwrite/Auth/OAuth2/Dailymotion.php b/src/Appwrite/Auth/OAuth2/Dailymotion.php index 0fc90e3ca1..5ead308fbe 100644 --- a/src/Appwrite/Auth/OAuth2/Dailymotion.php +++ b/src/Appwrite/Auth/OAuth2/Dailymotion.php @@ -24,7 +24,7 @@ class Dailymotion extends OAuth2 */ protected array $scopes = [ 'userinfo', - 'email' + 'email', ]; /** @@ -34,7 +34,7 @@ class Dailymotion extends OAuth2 'email', 'id', 'fullname', - 'verified' + 'verified', ]; /** @@ -68,21 +68,20 @@ class Dailymotion extends OAuth2 */ public function getLoginURL(): string { - $url = $this->authEndpoint . '?' . + $url = $this->authEndpoint.'?'. \http_build_query([ 'response_type' => 'code', 'client_id' => $this->appID, 'state' => \json_encode($this->state), 'redirect_uri' => $this->callback, - 'scope' => \implode(' ', $this->getScopes()) + 'scope' => \implode(' ', $this->getScopes()), ]); return $url; } /** - * @param string $code - * + * @param string $code * @return array */ protected function getTokens(string $code): array @@ -90,33 +89,31 @@ class Dailymotion extends OAuth2 if (empty($this->tokens)) { $this->tokens = \json_decode($this->request( 'POST', - $this->endpoint . '/oauth/token', - ["Content-Type: application/x-www-form-urlencoded"], + $this->endpoint.'/oauth/token', + ['Content-Type: application/x-www-form-urlencoded'], \http_build_query([ 'grant_type' => 'authorization_code', - "client_id" => $this->appID, - "client_secret" => $this->appSecret, - "redirect_uri" => $this->callback, + 'client_id' => $this->appID, + 'client_secret' => $this->appSecret, + 'redirect_uri' => $this->callback, 'code' => $code, 'scope' => \implode(' ', $this->getScopes()), ]) ), true); } + return $this->tokens; } - /** - * @param string $refreshToken - * + * @param string $refreshToken * @return array */ public function refreshTokens(string $refreshToken): array { - $this->tokens = \json_decode($this->request( 'POST', - $this->endpoint . '/oauth/token', + $this->endpoint.'/oauth/token', ['Content-Type: application/x-www-form-urlencoded'], \http_build_query([ 'grant_type' => 'refresh_token', @@ -130,13 +127,11 @@ class Dailymotion extends OAuth2 $this->tokens['refresh_token'] = $refreshToken; } - return $this->tokens; } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserID(string $accessToken): string @@ -149,8 +144,7 @@ class Dailymotion extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserEmail(string $accessToken): string @@ -166,8 +160,7 @@ class Dailymotion extends OAuth2 * * @link https://developers.dailymotion.com/api/#user-fields * - * @param string $accessToken - * + * @param string $accessToken * @return bool */ public function isEmailVerified(string $accessToken): bool @@ -178,23 +171,20 @@ class Dailymotion extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserName(string $accessToken): string { $user = $this->getUser($accessToken); - $username = $user['fullname'] ?? ''; return $username; } /** - * @param string $accessToken - * + * @param string $accessToken * @return array */ protected function getUser(string $accessToken): array @@ -202,8 +192,8 @@ class Dailymotion extends OAuth2 if (empty($this->user)) { $user = $this->request( 'GET', - $this->endpoint . '/user/me?fields=' . \implode(',', $this->getFields()), - ['Authorization: Bearer ' . \urlencode($accessToken)], + $this->endpoint.'/user/me?fields='.\implode(',', $this->getFields()), + ['Authorization: Bearer '.\urlencode($accessToken)], ); $this->user = \json_decode($user, true); } diff --git a/src/Appwrite/Auth/OAuth2/Discord.php b/src/Appwrite/Auth/OAuth2/Discord.php index b77ce6a236..b98d5bdc0c 100644 --- a/src/Appwrite/Auth/OAuth2/Discord.php +++ b/src/Appwrite/Auth/OAuth2/Discord.php @@ -28,8 +28,8 @@ class Discord extends OAuth2 * @var array */ protected array $scopes = [ - 'identify', - 'email' + 'identify', + 'email', ]; /** @@ -45,21 +45,20 @@ class Discord extends OAuth2 */ public function getLoginURL(): string { - $url = $this->endpoint . '/oauth2/authorize?' . + $url = $this->endpoint.'/oauth2/authorize?'. \http_build_query([ 'response_type' => 'code', 'client_id' => $this->appID, 'state' => \json_encode($this->state), 'scope' => \implode(' ', $this->getScopes()), - 'redirect_uri' => $this->callback + 'redirect_uri' => $this->callback, ]); return $url; } /** - * @param string $code - * + * @param string $code * @return array */ protected function getTokens(string $code): array @@ -67,7 +66,7 @@ class Discord extends OAuth2 if (empty($this->tokens)) { $this->tokens = \json_decode($this->request( 'POST', - $this->endpoint . '/oauth2/token', + $this->endpoint.'/oauth2/token', ['Content-Type: application/x-www-form-urlencoded'], \http_build_query([ 'grant_type' => 'authorization_code', @@ -75,7 +74,7 @@ class Discord extends OAuth2 'redirect_uri' => $this->callback, 'client_id' => $this->appID, 'client_secret' => $this->appSecret, - 'scope' => \implode(' ', $this->getScopes()) + 'scope' => \implode(' ', $this->getScopes()), ]) ), true); } @@ -84,15 +83,14 @@ class Discord extends OAuth2 } /** - * @param string $refreshToken - * + * @param string $refreshToken * @return array */ public function refreshTokens(string $refreshToken): array { $this->tokens = \json_decode($this->request( 'POST', - $this->endpoint . '/oauth2/token', + $this->endpoint.'/oauth2/token', ['Content-Type: application/x-www-form-urlencoded'], \http_build_query([ 'grant_type' => 'refresh_token', @@ -110,8 +108,7 @@ class Discord extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserID(string $accessToken): string @@ -122,8 +119,7 @@ class Discord extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserEmail(string $accessToken): string @@ -138,8 +134,7 @@ class Discord extends OAuth2 * * @link https://discord.com/developers/docs/resources/user * - * @param string $accessToken - * + * @param string $accessToken * @return bool */ public function isEmailVerified(string $accessToken): bool @@ -154,8 +149,7 @@ class Discord extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserName(string $accessToken): string @@ -166,8 +160,7 @@ class Discord extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return array */ protected function getUser(string $accessToken): array @@ -175,8 +168,8 @@ class Discord extends OAuth2 if (empty($this->user)) { $user = $this->request( 'GET', - $this->endpoint . '/users/@me', - ['Authorization: Bearer ' . \urlencode($accessToken)] + $this->endpoint.'/users/@me', + ['Authorization: Bearer '.\urlencode($accessToken)] ); $this->user = \json_decode($user, true); } diff --git a/src/Appwrite/Auth/OAuth2/Disqus.php b/src/Appwrite/Auth/OAuth2/Disqus.php index 58b7f48914..eb657298cd 100644 --- a/src/Appwrite/Auth/OAuth2/Disqus.php +++ b/src/Appwrite/Auth/OAuth2/Disqus.php @@ -45,21 +45,20 @@ class Disqus extends OAuth2 */ public function getLoginURL(): string { - $url = $this->endpoint . 'oauth/2.0/authorize/?' . + $url = $this->endpoint.'oauth/2.0/authorize/?'. \http_build_query([ 'response_type' => 'code', 'client_id' => $this->appID, 'state' => \json_encode($this->state), 'redirect_uri' => $this->callback, - 'scope' => \implode(',', $this->getScopes()) + 'scope' => \implode(',', $this->getScopes()), ]); return $url; } /** - * @param string $code - * + * @param string $code * @return array */ protected function getTokens(string $code): array @@ -67,7 +66,7 @@ class Disqus extends OAuth2 if (empty($this->tokens)) { $this->tokens = \json_decode($this->request( 'POST', - $this->endpoint . 'oauth/2.0/access_token/', + $this->endpoint.'oauth/2.0/access_token/', ['Content-Type: application/x-www-form-urlencoded'], \http_build_query([ 'grant_type' => 'authorization_code', @@ -79,19 +78,19 @@ class Disqus extends OAuth2 ]) ), true); } + return $this->tokens; } /** - * @param string $refreshToken - * + * @param string $refreshToken * @return array */ public function refreshTokens(string $refreshToken): array { $this->tokens = \json_decode($this->request( 'POST', - $this->endpoint . 'oauth/2.0/access_token/?', + $this->endpoint.'oauth/2.0/access_token/?', ['Content-Type: application/x-www-form-urlencoded'], \http_build_query([ 'grant_type' => 'refresh_token', @@ -104,12 +103,12 @@ class Disqus extends OAuth2 if (empty($this->tokens['refresh_token'])) { $this->tokens['refresh_token'] = $refreshToken; } + return $this->tokens; } /** - * @param string $token - * + * @param string $token * @return string */ public function getUserID(string $accessToken): string @@ -122,8 +121,7 @@ class Disqus extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserEmail(string $accessToken): string @@ -136,13 +134,11 @@ class Disqus extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return bool */ public function isEmailVerified(string $accessToken): bool { - // Look out for the change in their enpoint. // It's in Beta so they may provide a parameter in the future. // https://disqus.com/api/docs/users/details/ @@ -151,8 +147,7 @@ class Disqus extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserName(string $accessToken): string @@ -165,8 +160,7 @@ class Disqus extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return array */ protected function getUser(string $accessToken): array @@ -174,10 +168,10 @@ class Disqus extends OAuth2 if (empty($this->user)) { $user = $this->request( 'GET', - $this->endpoint . '3.0/users/details.json?' . \http_build_query([ + $this->endpoint.'3.0/users/details.json?'.\http_build_query([ 'access_token' => $accessToken, 'api_key' => $this->appID, - 'api_secret' => $this->appSecret + 'api_secret' => $this->appSecret, ]), ); $this->user = \json_decode($user, true)['response']; diff --git a/src/Appwrite/Auth/OAuth2/Dropbox.php b/src/Appwrite/Auth/OAuth2/Dropbox.php index ff30b87d8a..156f93e0ee 100644 --- a/src/Appwrite/Auth/OAuth2/Dropbox.php +++ b/src/Appwrite/Auth/OAuth2/Dropbox.php @@ -38,17 +38,16 @@ class Dropbox extends OAuth2 */ public function getLoginURL(): string { - return 'https://www.dropbox.com/oauth2/authorize?' . \http_build_query([ + return 'https://www.dropbox.com/oauth2/authorize?'.\http_build_query([ 'client_id' => $this->appID, 'redirect_uri' => $this->callback, 'state' => \json_encode($this->state), - 'response_type' => 'code' + 'response_type' => 'code', ]); } /** - * @param string $code - * + * @param string $code * @return array */ protected function getTokens(string $code): array @@ -64,7 +63,7 @@ class Dropbox extends OAuth2 'client_id' => $this->appID, 'client_secret' => $this->appSecret, 'redirect_uri' => $this->callback, - 'grant_type' => 'authorization_code' + 'grant_type' => 'authorization_code', ]) ), true); } @@ -73,8 +72,7 @@ class Dropbox extends OAuth2 } /** - * @param string $refreshToken - * + * @param string $refreshToken * @return array */ public function refreshTokens(string $refreshToken): array @@ -88,7 +86,7 @@ class Dropbox extends OAuth2 'refresh_token' => $refreshToken, 'client_id' => $this->appID, 'client_secret' => $this->appSecret, - 'grant_type' => 'refresh_token' + 'grant_type' => 'refresh_token', ]) ), true); @@ -100,8 +98,7 @@ class Dropbox extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserID(string $accessToken): string @@ -112,8 +109,7 @@ class Dropbox extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserEmail(string $accessToken): string @@ -128,8 +124,7 @@ class Dropbox extends OAuth2 * * @link https://www.dropbox.com/developers/documentation/http/documentation#users-get_current_account * - * @param string $accessToken - * + * @param string $accessToken * @return bool */ public function isEmailVerified(string $accessToken): bool @@ -144,8 +139,7 @@ class Dropbox extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserName(string $accessToken): string @@ -156,14 +150,13 @@ class Dropbox extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return array */ protected function getUser(string $accessToken): array { if (empty($this->user)) { - $headers = ['Authorization: Bearer ' . \urlencode($accessToken)]; + $headers = ['Authorization: Bearer '.\urlencode($accessToken)]; $user = $this->request('POST', 'https://api.dropboxapi.com/2/users/get_current_account', $headers); $this->user = \json_decode($user, true); } diff --git a/src/Appwrite/Auth/OAuth2/Etsy.php b/src/Appwrite/Auth/OAuth2/Etsy.php index 7ff16fcb78..7316cdc1d5 100644 --- a/src/Appwrite/Auth/OAuth2/Etsy.php +++ b/src/Appwrite/Auth/OAuth2/Etsy.php @@ -30,8 +30,8 @@ class Etsy extends OAuth2 * @var array */ protected array $scopes = [ - "email_r", - "profile_r", + 'email_r', + 'profile_r', ]; /** @@ -64,7 +64,7 @@ class Etsy extends OAuth2 */ public function getLoginURL(): string { - return 'https://www.etsy.com/oauth/connect/oauth/authorize?' . \http_build_query([ + return 'https://www.etsy.com/oauth/connect/oauth/authorize?'.\http_build_query([ 'client_id' => $this->appID, 'redirect_uri' => $this->callback, 'response_type' => 'code', @@ -76,8 +76,7 @@ class Etsy extends OAuth2 } /** - * @param string $code - * + * @param string $code * @return array */ protected function getTokens(string $code): array @@ -87,7 +86,7 @@ class Etsy extends OAuth2 $this->tokens = \json_decode($this->request( 'POST', - $this->endpoint . '/oauth/token', + $this->endpoint.'/oauth/token', $headers, \http_build_query([ 'grant_type' => 'authorization_code', @@ -103,8 +102,7 @@ class Etsy extends OAuth2 } /** - * @param string $refreshToken - * + * @param string $refreshToken * @return array */ public function refreshTokens(string $refreshToken): array @@ -113,7 +111,7 @@ class Etsy extends OAuth2 $this->tokens = \json_decode($this->request( 'POST', - $this->endpoint . '/oauth/token', + $this->endpoint.'/oauth/token', $headers, \http_build_query([ 'grant_type' => 'refresh_token', @@ -131,7 +129,6 @@ class Etsy extends OAuth2 /** * @param $accessToken - * * @return string */ public function getUserID(string $accessToken): string @@ -143,7 +140,6 @@ class Etsy extends OAuth2 /** * @param $accessToken - * * @return string */ public function getUserEmail(string $accessToken): string @@ -156,20 +152,18 @@ class Etsy extends OAuth2 * * OAuth is only allowed if account has been verified through Etsy, itself. * - * @param string $accessToken - * + * @param string $accessToken * @return bool */ public function isEmailVerified(string $accessToken): bool { $email = $this->getUserEmail($accessToken); - return !empty($email); + return ! empty($email); } /** * @param $accessToken - * * @return string */ public function getUserName(string $accessToken): string @@ -178,21 +172,20 @@ class Etsy extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return array */ protected function getUser(string $accessToken): array { - if (!empty($this->user)) { + if (! empty($this->user)) { return $this->user; } - $headers = ['Authorization: Bearer ' . $accessToken]; + $headers = ['Authorization: Bearer '.$accessToken]; $this->user = \json_decode($this->request( 'GET', - 'https://api.etsy.com/v3/application/users/' . $this->getUserID($accessToken), + 'https://api.etsy.com/v3/application/users/'.$this->getUserID($accessToken), ), true); return $this->user; diff --git a/src/Appwrite/Auth/OAuth2/Facebook.php b/src/Appwrite/Auth/OAuth2/Facebook.php index 90fe8e7388..9b10f3be80 100644 --- a/src/Appwrite/Auth/OAuth2/Facebook.php +++ b/src/Appwrite/Auth/OAuth2/Facebook.php @@ -25,7 +25,7 @@ class Facebook extends OAuth2 * @var array */ protected array $scopes = [ - 'email' + 'email', ]; /** @@ -41,17 +41,16 @@ class Facebook extends OAuth2 */ public function getLoginURL(): string { - return 'https://www.facebook.com/' . $this->version . '/dialog/oauth?' . \http_build_query([ + return 'https://www.facebook.com/'.$this->version.'/dialog/oauth?'.\http_build_query([ 'client_id' => $this->appID, 'redirect_uri' => $this->callback, 'scope' => \implode(' ', $this->getScopes()), - 'state' => \json_encode($this->state) + 'state' => \json_encode($this->state), ]); } /** - * @param string $code - * + * @param string $code * @return array */ protected function getTokens(string $code): array @@ -59,11 +58,11 @@ class Facebook extends OAuth2 if (empty($this->tokens)) { $this->tokens = \json_decode($this->request( 'GET', - 'https://graph.facebook.com/' . $this->version . '/oauth/access_token?' . \http_build_query([ + 'https://graph.facebook.com/'.$this->version.'/oauth/access_token?'.\http_build_query([ 'client_id' => $this->appID, 'redirect_uri' => $this->callback, 'client_secret' => $this->appSecret, - 'code' => $code + 'code' => $code, ]) ), true); } @@ -72,20 +71,19 @@ class Facebook extends OAuth2 } /** - * @param string $refreshToken - * + * @param string $refreshToken * @return array */ public function refreshTokens(string $refreshToken): array { $this->tokens = \json_decode($this->request( 'GET', - 'https://graph.facebook.com/' . $this->version . '/oauth/access_token?' . \http_build_query([ + 'https://graph.facebook.com/'.$this->version.'/oauth/access_token?'.\http_build_query([ 'client_id' => $this->appID, 'redirect_uri' => $this->callback, 'client_secret' => $this->appSecret, 'refresh_token' => $refreshToken, - 'grant_type' => 'refresh_token' + 'grant_type' => 'refresh_token', ]) ), true); @@ -97,8 +95,7 @@ class Facebook extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserID(string $accessToken): string @@ -109,8 +106,7 @@ class Facebook extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserEmail(string $accessToken): string @@ -125,20 +121,18 @@ class Facebook extends OAuth2 * * If present, the email is verified. This was verfied through a manual Facebook sign up process * - * @param string $accessToken - * + * @param string $accessToken * @return bool */ public function isEmailVerified(string $accessToken): bool { $email = $this->getUserEmail($accessToken); - return !empty($email); + return ! empty($email); } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserName(string $accessToken): string @@ -149,14 +143,13 @@ class Facebook extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return array */ protected function getUser(string $accessToken): array { if (empty($this->user)) { - $user = $this->request('GET', 'https://graph.facebook.com/' . $this->version . '/me?fields=email,name&access_token=' . \urlencode($accessToken)); + $user = $this->request('GET', 'https://graph.facebook.com/'.$this->version.'/me?fields=email,name&access_token='.\urlencode($accessToken)); $this->user = \json_decode($user, true); } diff --git a/src/Appwrite/Auth/OAuth2/Github.php b/src/Appwrite/Auth/OAuth2/Github.php index c582617d67..cd58e0dbe5 100644 --- a/src/Appwrite/Auth/OAuth2/Github.php +++ b/src/Appwrite/Auth/OAuth2/Github.php @@ -36,17 +36,16 @@ class Github extends OAuth2 */ public function getLoginURL(): string { - return 'https://github.com/login/oauth/authorize?' . \http_build_query([ + return 'https://github.com/login/oauth/authorize?'.\http_build_query([ 'client_id' => $this->appID, 'redirect_uri' => $this->callback, 'scope' => \implode(' ', $this->getScopes()), - 'state' => \json_encode($this->state) + 'state' => \json_encode($this->state), ]); } /** - * @param string $code - * + * @param string $code * @return array */ protected function getTokens(string $code): array @@ -60,7 +59,7 @@ class Github extends OAuth2 'client_id' => $this->appID, 'redirect_uri' => $this->callback, 'client_secret' => $this->appSecret, - 'code' => $code + 'code' => $code, ]) ); @@ -73,8 +72,7 @@ class Github extends OAuth2 } /** - * @param string $refreshToken - * + * @param string $refreshToken * @return array */ public function refreshTokens(string $refreshToken): array @@ -87,7 +85,7 @@ class Github extends OAuth2 'client_id' => $this->appID, 'client_secret' => $this->appSecret, 'grant_type' => 'refresh_token', - 'refresh_token' => $refreshToken + 'refresh_token' => $refreshToken, ]) ); @@ -103,8 +101,7 @@ class Github extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserID(string $accessToken): string @@ -115,8 +112,7 @@ class Github extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserEmail(string $accessToken): string @@ -131,8 +127,7 @@ class Github extends OAuth2 * * @link https://docs.github.com/en/rest/users/emails#list-email-addresses-for-the-authenticated-user * - * @param string $accessToken - * + * @param string $accessToken * @return bool */ public function isEmailVerified(string $accessToken): bool @@ -147,8 +142,7 @@ class Github extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserName(string $accessToken): string @@ -159,16 +153,15 @@ class Github extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return array */ protected function getUser(string $accessToken) { if (empty($this->user)) { - $this->user = \json_decode($this->request('GET', 'https://api.github.com/user', ['Authorization: token ' . \urlencode($accessToken)]), true); + $this->user = \json_decode($this->request('GET', 'https://api.github.com/user', ['Authorization: token '.\urlencode($accessToken)]), true); - $emails = $this->request('GET', 'https://api.github.com/user/emails', ['Authorization: token ' . \urlencode($accessToken)]); + $emails = $this->request('GET', 'https://api.github.com/user/emails', ['Authorization: token '.\urlencode($accessToken)]); $emails = \json_decode($emails, true); foreach ($emails as $email) { diff --git a/src/Appwrite/Auth/OAuth2/Gitlab.php b/src/Appwrite/Auth/OAuth2/Gitlab.php index 7d98bf1921..f96348c98b 100644 --- a/src/Appwrite/Auth/OAuth2/Gitlab.php +++ b/src/Appwrite/Auth/OAuth2/Gitlab.php @@ -23,7 +23,7 @@ class Gitlab extends OAuth2 * @var array */ protected array $scopes = [ - 'read_user' + 'read_user', ]; /** @@ -39,18 +39,17 @@ class Gitlab extends OAuth2 */ public function getLoginURL(): string { - return $this->getEndpoint() . '/oauth/authorize?' . \http_build_query([ + return $this->getEndpoint().'/oauth/authorize?'.\http_build_query([ 'client_id' => $this->appID, 'redirect_uri' => $this->callback, 'scope' => \implode(' ', $this->getScopes()), 'state' => \json_encode($this->state), - 'response_type' => 'code' + 'response_type' => 'code', ]); } /** - * @param string $code - * + * @param string $code * @return array */ protected function getTokens(string $code): array @@ -58,12 +57,12 @@ class Gitlab extends OAuth2 if (empty($this->tokens)) { $this->tokens = \json_decode($this->request( 'POST', - $this->getEndpoint() . '/oauth/token?' . \http_build_query([ + $this->getEndpoint().'/oauth/token?'.\http_build_query([ 'code' => $code, 'client_id' => $this->appID, 'client_secret' => $this->getAppSecret()['clientSecret'], 'redirect_uri' => $this->callback, - 'grant_type' => 'authorization_code' + 'grant_type' => 'authorization_code', ]) ), true); } @@ -72,19 +71,18 @@ class Gitlab extends OAuth2 } /** - * @param string $refreshToken - * + * @param string $refreshToken * @return array */ public function refreshTokens(string $refreshToken): array { $this->tokens = \json_decode($this->request( 'POST', - $this->getEndpoint() . '/oauth/token?' . \http_build_query([ + $this->getEndpoint().'/oauth/token?'.\http_build_query([ 'refresh_token' => $refreshToken, 'client_id' => $this->appID, 'client_secret' => $this->getAppSecret()['clientSecret'], - 'grant_type' => 'refresh_token' + 'grant_type' => 'refresh_token', ]) ), true); @@ -96,8 +94,7 @@ class Gitlab extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserID(string $accessToken): string @@ -112,8 +109,7 @@ class Gitlab extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserEmail(string $accessToken): string @@ -128,8 +124,7 @@ class Gitlab extends OAuth2 * * @link https://docs.gitlab.com/ee/api/users.html#list-current-user-for-normal-users * - * @param string $accessToken - * + * @param string $accessToken * @return bool */ public function isEmailVerified(string $accessToken): bool @@ -144,8 +139,7 @@ class Gitlab extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserName(string $accessToken): string @@ -156,14 +150,13 @@ class Gitlab extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return array */ protected function getUser(string $accessToken): array { if (empty($this->user)) { - $user = $this->request('GET', $this->getEndpoint() . '/api/v4/user?access_token=' . \urlencode($accessToken)); + $user = $this->request('GET', $this->getEndpoint().'/api/v4/user?access_token='.\urlencode($accessToken)); $this->user = \json_decode($user, true); } @@ -182,10 +175,10 @@ class Gitlab extends OAuth2 } catch (\Throwable $th) { throw new \Exception('Invalid secret'); } + return $secret; } - /** * Extracts the Tenant Id from the JSON stored in appSecret. Defaults to 'common' as a fallback * @@ -196,6 +189,7 @@ class Gitlab extends OAuth2 $defaultEndpoint = 'https://gitlab.com'; $secret = $this->getAppSecret(); $endpoint = $secret['endpoint'] ?? $defaultEndpoint; + return empty($endpoint) ? $defaultEndpoint : $endpoint; } } diff --git a/src/Appwrite/Auth/OAuth2/Google.php b/src/Appwrite/Auth/OAuth2/Google.php index c6f621b814..c56f1660c4 100644 --- a/src/Appwrite/Auth/OAuth2/Google.php +++ b/src/Appwrite/Auth/OAuth2/Google.php @@ -22,7 +22,7 @@ class Google extends OAuth2 protected array $scopes = [ 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', - 'openid' + 'openid', ]; /** @@ -48,18 +48,17 @@ class Google extends OAuth2 */ public function getLoginURL(): string { - return 'https://accounts.google.com/o/oauth2/v2/auth?' . \http_build_query([ + return 'https://accounts.google.com/o/oauth2/v2/auth?'.\http_build_query([ 'client_id' => $this->appID, 'redirect_uri' => $this->callback, 'scope' => \implode(' ', $this->getScopes()), 'state' => \json_encode($this->state), - 'response_type' => 'code' + 'response_type' => 'code', ]); } /** - * @param string $code - * + * @param string $code * @return array */ protected function getTokens(string $code): array @@ -67,13 +66,13 @@ class Google extends OAuth2 if (empty($this->tokens)) { $this->tokens = \json_decode($this->request( 'POST', - 'https://oauth2.googleapis.com/token?' . \http_build_query([ + 'https://oauth2.googleapis.com/token?'.\http_build_query([ 'code' => $code, 'client_id' => $this->appID, 'client_secret' => $this->appSecret, 'redirect_uri' => $this->callback, 'scope' => null, - 'grant_type' => 'authorization_code' + 'grant_type' => 'authorization_code', ]) ), true); } @@ -82,19 +81,18 @@ class Google extends OAuth2 } /** - * @param string $refreshToken - * + * @param string $refreshToken * @return array */ public function refreshTokens(string $refreshToken): array { $this->tokens = \json_decode($this->request( 'POST', - 'https://oauth2.googleapis.com/token?' . \http_build_query([ + 'https://oauth2.googleapis.com/token?'.\http_build_query([ 'refresh_token' => $refreshToken, 'client_id' => $this->appID, 'client_secret' => $this->appSecret, - 'grant_type' => 'refresh_token' + 'grant_type' => 'refresh_token', ]) ), true); @@ -106,8 +104,7 @@ class Google extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserID(string $accessToken): string @@ -118,8 +115,7 @@ class Google extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserEmail(string $accessToken): string @@ -134,8 +130,7 @@ class Google extends OAuth2 * * @link https://www.oauth.com/oauth2-servers/signing-in-with-google/verifying-the-user-info/ * - * @param string $accessToken - * + * @param string $accessToken * @return bool */ public function isEmailVerified(string $accessToken): bool @@ -150,8 +145,7 @@ class Google extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserName(string $accessToken): string @@ -162,14 +156,13 @@ class Google extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return array */ protected function getUser(string $accessToken): array { if (empty($this->user)) { - $user = $this->request('GET', 'https://www.googleapis.com/oauth2/v3/userinfo?access_token=' . \urlencode($accessToken)); + $user = $this->request('GET', 'https://www.googleapis.com/oauth2/v3/userinfo?access_token='.\urlencode($accessToken)); $this->user = \json_decode($user, true); } diff --git a/src/Appwrite/Auth/OAuth2/Linkedin.php b/src/Appwrite/Auth/OAuth2/Linkedin.php index 340cab2df0..c4e899b5ca 100644 --- a/src/Appwrite/Auth/OAuth2/Linkedin.php +++ b/src/Appwrite/Auth/OAuth2/Linkedin.php @@ -50,7 +50,7 @@ class Linkedin extends OAuth2 */ public function getLoginURL(): string { - return 'https://www.linkedin.com/oauth/v2/authorization?' . \http_build_query([ + return 'https://www.linkedin.com/oauth/v2/authorization?'.\http_build_query([ 'response_type' => 'code', 'client_id' => $this->appID, 'redirect_uri' => $this->callback, @@ -60,8 +60,7 @@ class Linkedin extends OAuth2 } /** - * @param string $code - * + * @param string $code * @return array */ protected function getTokens(string $code): array @@ -80,12 +79,12 @@ class Linkedin extends OAuth2 ]) ), true); } + return $this->tokens; } /** - * @param string $refreshToken - * + * @param string $refreshToken * @return array */ public function refreshTokens(string $refreshToken): array @@ -106,12 +105,12 @@ class Linkedin extends OAuth2 if (empty($this->tokens['refresh_token'])) { $this->tokens['refresh_token'] = $refreshToken; } + return $this->tokens; } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserID(string $accessToken): string @@ -122,13 +121,12 @@ class Linkedin extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserEmail(string $accessToken): string { - $email = \json_decode($this->request('GET', 'https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))', ['Authorization: Bearer ' . \urlencode($accessToken)]), true); + $email = \json_decode($this->request('GET', 'https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))', ['Authorization: Bearer '.\urlencode($accessToken)]), true); return $email['elements'][0]['handle~']['emailAddress'] ?? ''; } @@ -138,20 +136,18 @@ class Linkedin extends OAuth2 * * If present, the email is verified. This was verfied through a manual Linkedin sign up process * - * @param string $accessToken - * + * @param string $accessToken * @return bool */ public function isEmailVerified(string $accessToken): bool { $email = $this->getUserEmail($accessToken); - return !empty($email); + return ! empty($email); } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserName(string $accessToken): string @@ -164,21 +160,20 @@ class Linkedin extends OAuth2 } if (isset($user['localizedLastName'])) { - $name = (empty($name)) ? $user['localizedLastName'] : $name . ' ' . $user['localizedLastName']; + $name = (empty($name)) ? $user['localizedLastName'] : $name.' '.$user['localizedLastName']; } return $name; } /** - * @param string $accessToken - * + * @param string $accessToken * @return array */ protected function getUser(string $accessToken) { if (empty($this->user)) { - $this->user = \json_decode($this->request('GET', 'https://api.linkedin.com/v2/me', ['Authorization: Bearer ' . \urlencode($accessToken)]), true); + $this->user = \json_decode($this->request('GET', 'https://api.linkedin.com/v2/me', ['Authorization: Bearer '.\urlencode($accessToken)]), true); } return $this->user; diff --git a/src/Appwrite/Auth/OAuth2/Microsoft.php b/src/Appwrite/Auth/OAuth2/Microsoft.php index bc05843b37..89b77c1925 100644 --- a/src/Appwrite/Auth/OAuth2/Microsoft.php +++ b/src/Appwrite/Auth/OAuth2/Microsoft.php @@ -25,7 +25,7 @@ class Microsoft extends OAuth2 */ protected array $scopes = [ 'offline_access', - 'user.read' + 'user.read', ]; /** @@ -41,19 +41,18 @@ class Microsoft extends OAuth2 */ public function getLoginURL(): string { - return 'https://login.microsoftonline.com/' . $this->getTenantID() . '/oauth2/v2.0/authorize?' . \http_build_query([ + return 'https://login.microsoftonline.com/'.$this->getTenantID().'/oauth2/v2.0/authorize?'.\http_build_query([ 'client_id' => $this->appID, 'redirect_uri' => $this->callback, 'state' => \json_encode($this->state), 'scope' => \implode(' ', $this->getScopes()), 'response_type' => 'code', - 'response_mode' => 'query' + 'response_mode' => 'query', ]); } /** - * @param string $code - * + * @param string $code * @return array */ protected function getTokens(string $code): array @@ -62,7 +61,7 @@ class Microsoft extends OAuth2 $headers = ['Content-Type: application/x-www-form-urlencoded']; $this->tokens = \json_decode($this->request( 'POST', - 'https://login.microsoftonline.com/' . $this->getTenantID() . '/oauth2/v2.0/token', + 'https://login.microsoftonline.com/'.$this->getTenantID().'/oauth2/v2.0/token', $headers, \http_build_query([ 'code' => $code, @@ -70,7 +69,7 @@ class Microsoft extends OAuth2 'client_secret' => $this->getClientSecret(), 'redirect_uri' => $this->callback, 'scope' => \implode(' ', $this->getScopes()), - 'grant_type' => 'authorization_code' + 'grant_type' => 'authorization_code', ]) ), true); } @@ -79,8 +78,7 @@ class Microsoft extends OAuth2 } /** - * @param string $refreshToken - * + * @param string $refreshToken * @return array */ public function refreshTokens(string $refreshToken): array @@ -88,13 +86,13 @@ class Microsoft extends OAuth2 $headers = ['Content-Type: application/x-www-form-urlencoded']; $this->tokens = \json_decode($this->request( 'POST', - 'https://login.microsoftonline.com/' . $this->getTenantID() . '/oauth2/v2.0/token', + 'https://login.microsoftonline.com/'.$this->getTenantID().'/oauth2/v2.0/token', $headers, \http_build_query([ 'refresh_token' => $refreshToken, 'client_id' => $this->appID, 'client_secret' => $this->getClientSecret(), - 'grant_type' => 'refresh_token' + 'grant_type' => 'refresh_token', ]) ), true); @@ -106,8 +104,7 @@ class Microsoft extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserID(string $accessToken): string @@ -118,8 +115,7 @@ class Microsoft extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserEmail(string $accessToken): string @@ -134,20 +130,18 @@ class Microsoft extends OAuth2 * * If present, the email is verified. This was verfied through a manual Microsoft sign up process * - * @param string $accessToken - * + * @param string $accessToken * @return bool */ public function isEmailVerified(string $accessToken): bool { $email = $this->getUserEmail($accessToken); - return !empty($email); + return ! empty($email); } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserName(string $accessToken): string @@ -158,14 +152,13 @@ class Microsoft extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return array */ protected function getUser(string $accessToken): array { if (empty($this->user)) { - $headers = ['Authorization: Bearer ' . \urlencode($accessToken)]; + $headers = ['Authorization: Bearer '.\urlencode($accessToken)]; $user = $this->request('GET', 'https://graph.microsoft.com/v1.0/me', $headers); $this->user = \json_decode($user, true); } @@ -185,6 +178,7 @@ class Microsoft extends OAuth2 } catch (\Throwable $th) { throw new \Exception('Invalid secret'); } + return $secret; } diff --git a/src/Appwrite/Auth/OAuth2/Mock.php b/src/Appwrite/Auth/OAuth2/Mock.php index d2cb8c1c2a..b0b2e3b8d1 100644 --- a/src/Appwrite/Auth/OAuth2/Mock.php +++ b/src/Appwrite/Auth/OAuth2/Mock.php @@ -3,7 +3,6 @@ namespace Appwrite\Auth\OAuth2; use Appwrite\Auth\OAuth2; -use Utopia\Exception; class Mock extends OAuth2 { @@ -16,7 +15,7 @@ class Mock extends OAuth2 * @var array */ protected array $scopes = [ - 'email' + 'email', ]; /** @@ -42,17 +41,16 @@ class Mock extends OAuth2 */ public function getLoginURL(): string { - return 'http://localhost/' . $this->version . '/mock/tests/general/oauth2?' . \http_build_query([ + return 'http://localhost/'.$this->version.'/mock/tests/general/oauth2?'.\http_build_query([ 'client_id' => $this->appID, 'redirect_uri' => $this->callback, 'scope' => \implode(' ', $this->getScopes()), - 'state' => \json_encode($this->state) + 'state' => \json_encode($this->state), ]); } /** - * @param string $code - * + * @param string $code * @return array */ protected function getTokens(string $code): array @@ -60,12 +58,12 @@ class Mock extends OAuth2 if (empty($this->tokens)) { $this->tokens = \json_decode($this->request( 'GET', - 'http://localhost/' . $this->version . '/mock/tests/general/oauth2/token?' . + 'http://localhost/'.$this->version.'/mock/tests/general/oauth2/token?'. \http_build_query([ 'client_id' => $this->appID, 'redirect_uri' => $this->callback, 'client_secret' => $this->appSecret, - 'code' => $code + 'code' => $code, ]) ), true); } @@ -74,20 +72,19 @@ class Mock extends OAuth2 } /** - * @param string $refreshToken - * + * @param string $refreshToken * @return array */ public function refreshTokens(string $refreshToken): array { $this->tokens = \json_decode($this->request( 'GET', - 'http://localhost/' . $this->version . '/mock/tests/general/oauth2/token?' . + 'http://localhost/'.$this->version.'/mock/tests/general/oauth2/token?'. \http_build_query([ 'client_id' => $this->appID, 'client_secret' => $this->appSecret, 'refresh_token' => $refreshToken, - 'grant_type' => 'refresh_token' + 'grant_type' => 'refresh_token', ]) ), true); @@ -99,8 +96,7 @@ class Mock extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserID(string $accessToken): string @@ -111,8 +107,7 @@ class Mock extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserEmail(string $accessToken): string @@ -125,8 +120,7 @@ class Mock extends OAuth2 /** * Check if the OAuth email is verified * - * @param string $accessToken - * + * @param string $accessToken * @return bool */ public function isEmailVerified(string $accessToken): bool @@ -135,8 +129,7 @@ class Mock extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserName(string $accessToken): string @@ -147,14 +140,13 @@ class Mock extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return array */ protected function getUser(string $accessToken): array { if (empty($this->user)) { - $user = $this->request('GET', 'http://localhost/' . $this->version . '/mock/tests/general/oauth2/user?token=' . \urlencode($accessToken)); + $user = $this->request('GET', 'http://localhost/'.$this->version.'/mock/tests/general/oauth2/user?token='.\urlencode($accessToken)); $this->user = \json_decode($user, true); } diff --git a/src/Appwrite/Auth/OAuth2/Notion.php b/src/Appwrite/Auth/OAuth2/Notion.php index c2f1ee98e4..17c1dd7f18 100644 --- a/src/Appwrite/Auth/OAuth2/Notion.php +++ b/src/Appwrite/Auth/OAuth2/Notion.php @@ -44,32 +44,31 @@ class Notion extends OAuth2 */ public function getLoginURL(): string { - return $this->endpoint . '/oauth/authorize?' . \http_build_query([ + return $this->endpoint.'/oauth/authorize?'.\http_build_query([ 'client_id' => $this->appID, 'redirect_uri' => $this->callback, 'response_type' => 'code', 'state' => \json_encode($this->state), - 'owner' => 'user' + 'owner' => 'user', ]); } /** - * @param string $code - * + * @param string $code * @return array */ protected function getTokens(string $code): array { if (empty($this->tokens)) { - $headers = ['Authorization: Basic ' . \base64_encode($this->appID . ':' . $this->appSecret)]; + $headers = ['Authorization: Basic '.\base64_encode($this->appID.':'.$this->appSecret)]; $this->tokens = \json_decode($this->request( 'POST', - $this->endpoint . '/oauth/token', + $this->endpoint.'/oauth/token', $headers, \http_build_query([ 'grant_type' => 'authorization_code', 'redirect_uri' => $this->callback, - 'code' => $code + 'code' => $code, ]) ), true); } @@ -78,16 +77,15 @@ class Notion extends OAuth2 } /** - * @param string $refreshToken - * + * @param string $refreshToken * @return array */ public function refreshTokens(string $refreshToken): array { - $headers = ['Authorization: Basic ' . \base64_encode($this->appID . ':' . $this->appSecret)]; + $headers = ['Authorization: Basic '.\base64_encode($this->appID.':'.$this->appSecret)]; $this->tokens = \json_decode($this->request( 'POST', - $this->endpoint . '/oauth/token', + $this->endpoint.'/oauth/token', $headers, \http_build_query([ 'grant_type' => 'refresh_token', @@ -103,8 +101,7 @@ class Notion extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserID(string $accessToken): string @@ -115,8 +112,7 @@ class Notion extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserEmail(string $accessToken): string @@ -131,20 +127,18 @@ class Notion extends OAuth2 * * If present, the email is verified. This was verfied through a manual Notion sign up process * - * @param string $accessToken - * + * @param string $accessToken * @return bool */ public function isEmailVerified(string $accessToken): bool { $email = $this->getUserEmail($accessToken); - return !empty($email); + return ! empty($email); } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserName(string $accessToken): string @@ -155,19 +149,18 @@ class Notion extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return array */ protected function getUser(string $accessToken): array { $headers = [ - 'Notion-Version: ' . $this->version, - 'Authorization: Bearer ' . \urlencode($accessToken) + 'Notion-Version: '.$this->version, + 'Authorization: Bearer '.\urlencode($accessToken), ]; if (empty($this->user)) { - $this->user = \json_decode($this->request('GET', $this->endpoint . '/users/me', $headers), true); + $this->user = \json_decode($this->request('GET', $this->endpoint.'/users/me', $headers), true); } return $this->user; diff --git a/src/Appwrite/Auth/OAuth2/Okta.php b/src/Appwrite/Auth/OAuth2/Okta.php index 610d9847f2..367c64e764 100644 --- a/src/Appwrite/Auth/OAuth2/Okta.php +++ b/src/Appwrite/Auth/OAuth2/Okta.php @@ -16,7 +16,7 @@ class Okta extends OAuth2 'openid', 'profile', 'email', - 'offline_access' + 'offline_access', ]; /** @@ -42,18 +42,17 @@ class Okta extends OAuth2 */ public function getLoginURL(): string { - return 'https://' . $this->getOktaDomain() . '/oauth2/' . $this->getAuthorizationServerId() . '/v1/authorize?' . \http_build_query([ + return 'https://'.$this->getOktaDomain().'/oauth2/'.$this->getAuthorizationServerId().'/v1/authorize?'.\http_build_query([ 'client_id' => $this->appID, 'redirect_uri' => $this->callback, 'state' => \json_encode($this->state), 'scope' => \implode(' ', $this->getScopes()), - 'response_type' => 'code' + 'response_type' => 'code', ]); } /** - * @param string $code - * + * @param string $code * @return array */ protected function getTokens(string $code): array @@ -62,7 +61,7 @@ class Okta extends OAuth2 $headers = ['Content-Type: application/x-www-form-urlencoded']; $this->tokens = \json_decode($this->request( 'POST', - 'https://' . $this->getOktaDomain() . '/oauth2/' . $this->getAuthorizationServerId() . '/v1/token', + 'https://'.$this->getOktaDomain().'/oauth2/'.$this->getAuthorizationServerId().'/v1/token', $headers, \http_build_query([ 'code' => $code, @@ -70,7 +69,7 @@ class Okta extends OAuth2 'client_secret' => $this->getClientSecret(), 'redirect_uri' => $this->callback, 'scope' => \implode(' ', $this->getScopes()), - 'grant_type' => 'authorization_code' + 'grant_type' => 'authorization_code', ]) ), true); } @@ -78,10 +77,8 @@ class Okta extends OAuth2 return $this->tokens; } - /** - * @param string $refreshToken - * + * @param string $refreshToken * @return array */ public function refreshTokens(string $refreshToken): array @@ -89,13 +86,13 @@ class Okta extends OAuth2 $headers = ['Content-Type: application/x-www-form-urlencoded']; $this->tokens = \json_decode($this->request( 'POST', - 'https://' . $this->getOktaDomain() . '/oauth2/' . $this->getAuthorizationServerId() . '/v1/token', + 'https://'.$this->getOktaDomain().'/oauth2/'.$this->getAuthorizationServerId().'/v1/token', $headers, \http_build_query([ 'refresh_token' => $refreshToken, 'client_id' => $this->appID, 'client_secret' => $this->getClientSecret(), - 'grant_type' => 'refresh_token' + 'grant_type' => 'refresh_token', ]) ), true); @@ -107,8 +104,7 @@ class Okta extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserID(string $accessToken): string @@ -119,8 +115,7 @@ class Okta extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserEmail(string $accessToken): string @@ -135,8 +130,7 @@ class Okta extends OAuth2 * * @link https://developer.okta.com/docs/reference/api/oidc/#userinfo * - * @param string $accessToken - * + * @param string $accessToken * @return bool */ public function isEmailVerified(string $accessToken): bool @@ -151,8 +145,7 @@ class Okta extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserName(string $accessToken): string @@ -163,15 +156,14 @@ class Okta extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return array */ protected function getUser(string $accessToken): array { if (empty($this->user)) { - $headers = ['Authorization: Bearer ' . \urlencode($accessToken)]; - $user = $this->request('GET', 'https://' . $this->getOktaDomain() . '/oauth2/' . $this->getAuthorizationServerId() . '/v1/userinfo', $headers); + $headers = ['Authorization: Bearer '.\urlencode($accessToken)]; + $user = $this->request('GET', 'https://'.$this->getOktaDomain().'/oauth2/'.$this->getAuthorizationServerId().'/v1/userinfo', $headers); $this->user = \json_decode($user, true); } @@ -226,6 +218,7 @@ class Okta extends OAuth2 } catch (\Throwable $th) { throw new \Exception('Invalid secret'); } + return $secret; } } diff --git a/src/Appwrite/Auth/OAuth2/Paypal.php b/src/Appwrite/Auth/OAuth2/Paypal.php index 5d5bd0a06f..e55ed05ac4 100644 --- a/src/Appwrite/Auth/OAuth2/Paypal.php +++ b/src/Appwrite/Auth/OAuth2/Paypal.php @@ -46,7 +46,7 @@ class Paypal extends OAuth2 protected array $scopes = [ 'openid', 'profile', - 'email' + 'email', ]; /** @@ -62,14 +62,14 @@ class Paypal extends OAuth2 */ public function getLoginURL(): string { - $url = $this->endpoint[$this->environment] . 'connect/?' . + $url = $this->endpoint[$this->environment].'connect/?'. \http_build_query([ 'flowEntry' => 'static', 'response_type' => 'code', 'client_id' => $this->appID, 'scope' => \implode(' ', $this->getScopes()), // paypal is not accepting localhost string into return uri - 'redirect_uri' => \str_replace("localhost", "127.0.0.1", $this->callback), + 'redirect_uri' => \str_replace('localhost', '127.0.0.1', $this->callback), 'state' => \json_encode($this->state), ]); @@ -77,8 +77,7 @@ class Paypal extends OAuth2 } /** - * @param string $code - * + * @param string $code * @return array */ protected function getTokens(string $code): array @@ -86,8 +85,8 @@ class Paypal extends OAuth2 if (empty($this->tokens)) { $this->tokens = \json_decode($this->request( 'POST', - $this->resourceEndpoint[$this->environment] . 'oauth2/token', - ['Authorization: Basic ' . \base64_encode($this->appID . ':' . $this->appSecret)], + $this->resourceEndpoint[$this->environment].'oauth2/token', + ['Authorization: Basic '.\base64_encode($this->appID.':'.$this->appSecret)], \http_build_query([ 'code' => $code, 'grant_type' => 'authorization_code', @@ -99,16 +98,15 @@ class Paypal extends OAuth2 } /** - * @param string $refreshToken - * + * @param string $refreshToken * @return array */ public function refreshTokens(string $refreshToken): array { $this->tokens = \json_decode($this->request( 'POST', - $this->resourceEndpoint[$this->environment] . 'oauth2/token', - ['Authorization: Basic ' . \base64_encode($this->appID . ':' . $this->appSecret)], + $this->resourceEndpoint[$this->environment].'oauth2/token', + ['Authorization: Basic '.\base64_encode($this->appID.':'.$this->appSecret)], \http_build_query([ 'refresh_token' => $refreshToken, 'grant_type' => 'refresh_token', @@ -123,8 +121,7 @@ class Paypal extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserID(string $accessToken): string @@ -135,8 +132,7 @@ class Paypal extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserEmail(string $accessToken): string @@ -148,7 +144,7 @@ class Paypal extends OAuth2 return $email['primary'] === true; }); - if (!empty($email)) { + if (! empty($email)) { return $email[0]['value']; } } @@ -161,8 +157,7 @@ class Paypal extends OAuth2 * * @link https://developer.paypal.com/docs/api/identity/v1/#userinfo_get * - * @param string $accessToken - * + * @param string $accessToken * @return bool */ public function isEmailVerified(string $accessToken): bool @@ -177,8 +172,7 @@ class Paypal extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserName(string $accessToken): string @@ -189,20 +183,19 @@ class Paypal extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return array */ protected function getUser(string $accessToken): array { $header = [ 'Content-Type: application/json', - 'Authorization: Bearer ' . \urlencode($accessToken), + 'Authorization: Bearer '.\urlencode($accessToken), ]; if (empty($this->user)) { $user = $this->request( 'GET', - $this->resourceEndpoint[$this->environment] . 'identity/oauth2/userinfo?schema=paypalv1.1', + $this->resourceEndpoint[$this->environment].'identity/oauth2/userinfo?schema=paypalv1.1', $header ); $this->user = \json_decode($user, true); diff --git a/src/Appwrite/Auth/OAuth2/PaypalSandbox.php b/src/Appwrite/Auth/OAuth2/PaypalSandbox.php index 0f56a09c21..e5ab612c0d 100644 --- a/src/Appwrite/Auth/OAuth2/PaypalSandbox.php +++ b/src/Appwrite/Auth/OAuth2/PaypalSandbox.php @@ -2,8 +2,6 @@ namespace Appwrite\Auth\OAuth2; -use Appwrite\Auth\OAuth2\Paypal; - class PaypalSandbox extends Paypal { protected string $environment = 'sandbox'; diff --git a/src/Appwrite/Auth/OAuth2/Podio.php b/src/Appwrite/Auth/OAuth2/Podio.php index e4194238d1..f3ba81968e 100644 --- a/src/Appwrite/Auth/OAuth2/Podio.php +++ b/src/Appwrite/Auth/OAuth2/Podio.php @@ -51,19 +51,18 @@ class Podio extends OAuth2 */ public function getLoginURL(): string { - $url = $this->endpoint . '/authorize?' . + $url = $this->endpoint.'/authorize?'. \http_build_query([ 'client_id' => $this->appID, 'state' => \json_encode($this->state), - 'redirect_uri' => $this->callback + 'redirect_uri' => $this->callback, ]); return $url; } /** - * @param string $code - * + * @param string $code * @return array */ protected function getTokens(string $code): array @@ -71,14 +70,14 @@ class Podio extends OAuth2 if (empty($this->tokens)) { $this->tokens = \json_decode($this->request( 'POST', - $this->apiEndpoint . '/oauth/token', + $this->apiEndpoint.'/oauth/token', ['Content-Type: application/x-www-form-urlencoded'], \http_build_query([ 'grant_type' => 'authorization_code', 'code' => $code, 'redirect_uri' => $this->callback, 'client_id' => $this->appID, - 'client_secret' => $this->appSecret + 'client_secret' => $this->appSecret, ]) ), true); } @@ -87,15 +86,14 @@ class Podio extends OAuth2 } /** - * @param string $refreshToken - * + * @param string $refreshToken * @return array */ public function refreshTokens(string $refreshToken): array { $this->tokens = \json_decode($this->request( 'POST', - $this->apiEndpoint . '/oauth/token', + $this->apiEndpoint.'/oauth/token', ['Content-Type: application/x-www-form-urlencoded'], \http_build_query([ 'grant_type' => 'refresh_token', @@ -113,8 +111,7 @@ class Podio extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserID(string $accessToken): string @@ -125,8 +122,7 @@ class Podio extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserEmail(string $accessToken): string @@ -139,8 +135,7 @@ class Podio extends OAuth2 /** * Check if the OAuth email is verified * - * @param string $accessToken - * + * @param string $accessToken * @return bool */ public function isEmailVerified(string $accessToken): bool @@ -148,7 +143,7 @@ class Podio extends OAuth2 $user = $this->getUser($accessToken); $mails = $user['mails']; - $mainMailIndex = \array_search($user['mail'], \array_map(fn($m) => $m['mail'], $mails)); + $mainMailIndex = \array_search($user['mail'], \array_map(fn ($m) => $m['mail'], $mails)); $mainMain = $mails[$mainMailIndex]; if ($mainMain['verified'] ?? false) { @@ -159,8 +154,7 @@ class Podio extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserName(string $accessToken): string @@ -171,8 +165,7 @@ class Podio extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return array */ protected function getUser(string $accessToken): array @@ -180,14 +173,14 @@ class Podio extends OAuth2 if (empty($this->user)) { $user = \json_decode($this->request( 'GET', - $this->apiEndpoint . '/user', - ['Authorization: Bearer ' . \urlencode($accessToken)] + $this->apiEndpoint.'/user', + ['Authorization: Bearer '.\urlencode($accessToken)] ), true); $profile = \json_decode($this->request( 'GET', - $this->apiEndpoint . '/user/profile', - ['Authorization: Bearer ' . \urlencode($accessToken)] + $this->apiEndpoint.'/user/profile', + ['Authorization: Bearer '.\urlencode($accessToken)] ), true); $this->user = $user; diff --git a/src/Appwrite/Auth/OAuth2/Salesforce.php b/src/Appwrite/Auth/OAuth2/Salesforce.php index 564fc51139..5fede655df 100644 --- a/src/Appwrite/Auth/OAuth2/Salesforce.php +++ b/src/Appwrite/Auth/OAuth2/Salesforce.php @@ -25,7 +25,7 @@ class Salesforce extends OAuth2 * @var array */ protected array $scopes = [ - "openid" + 'openid', ]; /** @@ -37,8 +37,7 @@ class Salesforce extends OAuth2 } /** - * @param string $state - * + * @param string $state * @return array */ public function parseState(string $state) @@ -46,31 +45,29 @@ class Salesforce extends OAuth2 return \json_decode(\html_entity_decode($state), true); } - /** * @return string */ public function getLoginURL(): string { - return 'https://login.salesforce.com/services/oauth2/authorize?' . \http_build_query([ + return 'https://login.salesforce.com/services/oauth2/authorize?'.\http_build_query([ 'response_type' => 'code', 'client_id' => $this->appID, 'redirect_uri' => $this->callback, 'scope' => \implode(' ', $this->getScopes()), - 'state' => \json_encode($this->state) + 'state' => \json_encode($this->state), ]); } /** - * @param string $code - * + * @param string $code * @return array */ protected function getTokens(string $code): array { if (empty($this->tokens)) { $headers = [ - 'Authorization: Basic ' . \base64_encode($this->appID . ':' . $this->appSecret), + 'Authorization: Basic '.\base64_encode($this->appID.':'.$this->appSecret), 'Content-Type: application/x-www-form-urlencoded', ]; $this->tokens = \json_decode($this->request( @@ -80,7 +77,7 @@ class Salesforce extends OAuth2 \http_build_query([ 'code' => $code, 'redirect_uri' => $this->callback, - 'grant_type' => 'authorization_code' + 'grant_type' => 'authorization_code', ]) ), true); } @@ -89,14 +86,13 @@ class Salesforce extends OAuth2 } /** - * @param string $refreshToken - * + * @param string $refreshToken * @return array */ public function refreshTokens(string $refreshToken): array { $headers = [ - 'Authorization: Basic ' . \base64_encode($this->appID . ':' . $this->appSecret), + 'Authorization: Basic '.\base64_encode($this->appID.':'.$this->appSecret), 'Content-Type: application/x-www-form-urlencoded', ]; $this->tokens = \json_decode($this->request( @@ -105,7 +101,7 @@ class Salesforce extends OAuth2 $headers, \http_build_query([ 'refresh_token' => $refreshToken, - 'grant_type' => 'refresh_token' + 'grant_type' => 'refresh_token', ]) ), true); @@ -117,8 +113,7 @@ class Salesforce extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserID(string $accessToken): string @@ -129,8 +124,7 @@ class Salesforce extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserEmail(string $accessToken): string @@ -145,8 +139,7 @@ class Salesforce extends OAuth2 * * @link https://help.salesforce.com/s/articleView?id=sf.remoteaccess_using_userinfo_endpoint.htm&type=5 * - * @param string $accessToken - * + * @param string $accessToken * @return bool */ public function isEmailVerified(string $accessToken): bool @@ -161,8 +154,7 @@ class Salesforce extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserName(string $accessToken): string @@ -173,16 +165,16 @@ class Salesforce extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return array */ protected function getUser(string $accessToken): array { if (empty($this->user)) { - $user = $this->request('GET', 'https://login.salesforce.com/services/oauth2/userinfo?access_token=' . \urlencode($accessToken)); + $user = $this->request('GET', 'https://login.salesforce.com/services/oauth2/userinfo?access_token='.\urlencode($accessToken)); $this->user = \json_decode($user, true); } + return $this->user; } } diff --git a/src/Appwrite/Auth/OAuth2/Slack.php b/src/Appwrite/Auth/OAuth2/Slack.php index 8898f4d1f7..ee6d43c0cc 100644 --- a/src/Appwrite/Auth/OAuth2/Slack.php +++ b/src/Appwrite/Auth/OAuth2/Slack.php @@ -23,7 +23,7 @@ class Slack extends OAuth2 'identity.avatar', 'identity.basic', 'identity.email', - 'identity.team' + 'identity.team', ]; /** @@ -40,17 +40,16 @@ class Slack extends OAuth2 public function getLoginURL(): string { // https://api.slack.com/docs/oauth#step_1_-_sending_users_to_authorize_and_or_install - return 'https://slack.com/oauth/authorize?' . \http_build_query([ + return 'https://slack.com/oauth/authorize?'.\http_build_query([ 'client_id' => $this->appID, 'scope' => \implode(' ', $this->getScopes()), 'redirect_uri' => $this->callback, - 'state' => \json_encode($this->state) + 'state' => \json_encode($this->state), ]); } /** - * @param string $code - * + * @param string $code * @return array */ protected function getTokens(string $code): array @@ -59,11 +58,11 @@ class Slack extends OAuth2 // https://api.slack.com/docs/oauth#step_3_-_exchanging_a_verification_code_for_an_access_token $this->tokens = \json_decode($this->request( 'GET', - 'https://slack.com/api/oauth.access?' . \http_build_query([ + 'https://slack.com/api/oauth.access?'.\http_build_query([ 'client_id' => $this->appID, 'client_secret' => $this->appSecret, 'code' => $code, - 'redirect_uri' => $this->callback + 'redirect_uri' => $this->callback, ]) ), true); } @@ -72,19 +71,18 @@ class Slack extends OAuth2 } /** - * @param string $refreshToken - * + * @param string $refreshToken * @return array */ public function refreshTokens(string $refreshToken): array { $this->tokens = \json_decode($this->request( 'GET', - 'https://slack.com/api/oauth.access?' . \http_build_query([ + 'https://slack.com/api/oauth.access?'.\http_build_query([ 'client_id' => $this->appID, 'client_secret' => $this->appSecret, 'refresh_token' => $refreshToken, - 'grant_type' => 'refresh_token' + 'grant_type' => 'refresh_token', ]) ), true); @@ -96,8 +94,7 @@ class Slack extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserID(string $accessToken): string @@ -108,8 +105,7 @@ class Slack extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserEmail(string $accessToken): string @@ -126,20 +122,18 @@ class Slack extends OAuth2 * * @link https://slack.com/help/articles/207262907-Change-your-email-address * - * @param string $accessToken - * + * @param string $accessToken * @return bool */ public function isEmailVerified(string $accessToken): bool { $email = $this->getUserEmail($accessToken); - return !empty($email); + return ! empty($email); } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserName(string $accessToken): string @@ -152,8 +146,7 @@ class Slack extends OAuth2 /** * @link https://api.slack.com/methods/users.identity * - * @param string $accessToken - * + * @param string $accessToken * @return array */ protected function getUser(string $accessToken): array @@ -161,7 +154,7 @@ class Slack extends OAuth2 if (empty($this->user)) { $user = $this->request( 'GET', - 'https://slack.com/api/users.identity?token=' . \urlencode($accessToken) + 'https://slack.com/api/users.identity?token='.\urlencode($accessToken) ); $this->user = \json_decode($user, true); diff --git a/src/Appwrite/Auth/OAuth2/Spotify.php b/src/Appwrite/Auth/OAuth2/Spotify.php index d8e23cf0f0..a8d5c531ab 100644 --- a/src/Appwrite/Auth/OAuth2/Spotify.php +++ b/src/Appwrite/Auth/OAuth2/Spotify.php @@ -49,33 +49,32 @@ class Spotify extends OAuth2 */ public function getLoginURL(): string { - return $this->endpoint . 'authorize?' . + return $this->endpoint.'authorize?'. \http_build_query([ 'response_type' => 'code', 'client_id' => $this->appID, 'scope' => \implode(' ', $this->getScopes()), 'redirect_uri' => $this->callback, - 'state' => \json_encode($this->state) + 'state' => \json_encode($this->state), ]); } /** - * @param string $code - * + * @param string $code * @return array */ protected function getTokens(string $code): array { if (empty($this->tokens)) { - $headers = ['Authorization: Basic ' . \base64_encode($this->appID . ':' . $this->appSecret)]; + $headers = ['Authorization: Basic '.\base64_encode($this->appID.':'.$this->appSecret)]; $this->tokens = \json_decode($this->request( 'POST', - $this->endpoint . 'api/token', + $this->endpoint.'api/token', $headers, \http_build_query([ - "code" => $code, - "grant_type" => "authorization_code", - "redirect_uri" => $this->callback + 'code' => $code, + 'grant_type' => 'authorization_code', + 'redirect_uri' => $this->callback, ]) ), true); } @@ -84,20 +83,19 @@ class Spotify extends OAuth2 } /** - * @param string $refreshToken - * + * @param string $refreshToken * @return array */ public function refreshTokens(string $refreshToken): array { - $headers = ['Authorization: Basic ' . \base64_encode($this->appID . ':' . $this->appSecret)]; + $headers = ['Authorization: Basic '.\base64_encode($this->appID.':'.$this->appSecret)]; $this->tokens = \json_decode($this->request( 'POST', - $this->endpoint . 'api/token', + $this->endpoint.'api/token', $headers, \http_build_query([ - "refresh_token" => $refreshToken, - "grant_type" => "refresh_token", + 'refresh_token' => $refreshToken, + 'grant_type' => 'refresh_token', ]) ), true); @@ -109,8 +107,7 @@ class Spotify extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserID(string $accessToken): string @@ -121,8 +118,7 @@ class Spotify extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserEmail(string $accessToken): string @@ -139,8 +135,7 @@ class Spotify extends OAuth2 * * @link https://developer.spotify.com/documentation/web-api/reference/#/operations/get-current-users-profile * - * @param string $accessToken - * + * @param string $accessToken * @return bool */ public function isEmailVerified(string $accessToken): bool @@ -149,8 +144,7 @@ class Spotify extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserName(string $accessToken): string @@ -161,8 +155,7 @@ class Spotify extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return array */ protected function getUser(string $accessToken) @@ -170,8 +163,8 @@ class Spotify extends OAuth2 if (empty($this->user)) { $this->user = \json_decode($this->request( 'GET', - $this->resourceEndpoint . 'me', - ['Authorization: Bearer ' . \urlencode($accessToken)] + $this->resourceEndpoint.'me', + ['Authorization: Bearer '.\urlencode($accessToken)] ), true); } diff --git a/src/Appwrite/Auth/OAuth2/Stripe.php b/src/Appwrite/Auth/OAuth2/Stripe.php index 5a959dbfcb..42260cad1e 100644 --- a/src/Appwrite/Auth/OAuth2/Stripe.php +++ b/src/Appwrite/Auth/OAuth2/Stripe.php @@ -3,7 +3,6 @@ namespace Appwrite\Auth\OAuth2; use Appwrite\Auth\OAuth2; -use Utopia\Exception; class Stripe extends OAuth2 { @@ -50,18 +49,17 @@ class Stripe extends OAuth2 */ public function getLoginURL(): string { - return 'https://connect.stripe.com/oauth/authorize?' . \http_build_query([ + return 'https://connect.stripe.com/oauth/authorize?'.\http_build_query([ 'response_type' => 'code', // The only option at the moment is "code." 'client_id' => $this->appID, 'redirect_uri' => $this->callback, 'scope' => \implode(' ', $this->getScopes()), - 'state' => \json_encode($this->state) + 'state' => \json_encode($this->state), ]); } /** - * @param string $code - * + * @param string $code * @return array */ protected function getTokens(string $code): array @@ -73,7 +71,7 @@ class Stripe extends OAuth2 [], \http_build_query([ 'grant_type' => $this->grantType['authorize'], - 'code' => $code + 'code' => $code, ]) ), true); @@ -84,8 +82,7 @@ class Stripe extends OAuth2 } /** - * @param string $refreshToken - * + * @param string $refreshToken * @return array */ public function refreshTokens(string $refreshToken): array @@ -105,12 +102,12 @@ class Stripe extends OAuth2 } $this->stripeAccountId = $this->tokens['stripe_user_id']; + return $this->tokens; } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserID(string $accessToken): string @@ -121,8 +118,7 @@ class Stripe extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserEmail(string $accessToken): string @@ -141,20 +137,18 @@ class Stripe extends OAuth2 * * If present, the email is verified. This was verfied through a manual Stripe sign up process * - * @param string $accessToken - * + * @param string $accessToken * @return bool */ public function isEmailVerified(string $accessToken): bool { $email = $this->getUserEmail($accessToken); - return !empty($email); + return ! empty($email); } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserName(string $accessToken): string @@ -165,18 +159,17 @@ class Stripe extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return array */ protected function getUser(string $accessToken) { - if (empty($this->user) && !empty($this->stripeAccountId)) { + if (empty($this->user) && ! empty($this->stripeAccountId)) { $this->user = \json_decode( $this->request( 'GET', - 'https://api.stripe.com/v1/accounts/' . $this->stripeAccountId, - ['Authorization: Bearer ' . \urlencode($accessToken)] + 'https://api.stripe.com/v1/accounts/'.$this->stripeAccountId, + ['Authorization: Bearer '.\urlencode($accessToken)] ), true ); diff --git a/src/Appwrite/Auth/OAuth2/Tradeshift.php b/src/Appwrite/Auth/OAuth2/Tradeshift.php index 8d0bfa8784..350c152e4c 100644 --- a/src/Appwrite/Auth/OAuth2/Tradeshift.php +++ b/src/Appwrite/Auth/OAuth2/Tradeshift.php @@ -10,6 +10,7 @@ use Appwrite\Auth\OAuth2; class Tradeshift extends OAuth2 { public const TRADESHIFT_SANDBOX_API_DOMAIN = 'api-sandbox.tradeshift.com'; + public const TRADESHIFT_API_DOMAIN = 'api.tradeshift.com'; private array $apiDomain = [ @@ -18,13 +19,13 @@ class Tradeshift extends OAuth2 ]; private array $endpoint = [ - 'sandbox' => 'https://' . self::TRADESHIFT_SANDBOX_API_DOMAIN . '/tradeshift/', - 'live' => 'https://' . self::TRADESHIFT_API_DOMAIN . '/tradeshift/', + 'sandbox' => 'https://'.self::TRADESHIFT_SANDBOX_API_DOMAIN.'/tradeshift/', + 'live' => 'https://'.self::TRADESHIFT_API_DOMAIN.'/tradeshift/', ]; private array $resourceEndpoint = [ - 'sandbox' => 'https://' . self::TRADESHIFT_SANDBOX_API_DOMAIN . '/tradeshift/rest/external/', - 'live' => 'https://' . self::TRADESHIFT_API_DOMAIN . '/tradeshift/rest/external/', + 'sandbox' => 'https://'.self::TRADESHIFT_SANDBOX_API_DOMAIN.'/tradeshift/rest/external/', + 'live' => 'https://'.self::TRADESHIFT_API_DOMAIN.'/tradeshift/rest/external/', ]; protected string $environment = 'live'; @@ -64,18 +65,17 @@ class Tradeshift extends OAuth2 'response_type' => 'code', 'client_id' => $this->appID, 'scope' => \implode(' ', $this->getScopes()), - 'redirect_uri' => \str_replace("localhost", "127.0.0.1", $this->callback), + 'redirect_uri' => \str_replace('localhost', '127.0.0.1', $this->callback), 'state' => \json_encode($this->state), ]); - $url = $this->endpoint[$this->environment] . 'auth/login?' . $httpQuery; + $url = $this->endpoint[$this->environment].'auth/login?'.$httpQuery; return $url; } /** - * @param string $code - * + * @param string $code * @return array */ protected function getTokens(string $code): array @@ -83,8 +83,8 @@ class Tradeshift extends OAuth2 if (empty($this->tokens)) { $this->tokens = \json_decode($this->request( 'POST', - $this->endpoint[$this->environment] . 'auth/token', - ['Authorization: Basic ' . \base64_encode($this->appID . ':' . $this->appSecret)], + $this->endpoint[$this->environment].'auth/token', + ['Authorization: Basic '.\base64_encode($this->appID.':'.$this->appSecret)], \http_build_query([ 'grant_type' => 'authorization_code', 'code' => $code, @@ -96,16 +96,15 @@ class Tradeshift extends OAuth2 } /** - * @param string $refreshToken - * + * @param string $refreshToken * @return array */ public function refreshTokens(string $refreshToken): array { $this->tokens = \json_decode($this->request( 'POST', - $this->endpoint[$this->environment] . 'auth/token', - ['Authorization: Basic ' . \base64_encode($this->appID . ':' . $this->appSecret)], + $this->endpoint[$this->environment].'auth/token', + ['Authorization: Basic '.\base64_encode($this->appID.':'.$this->appSecret)], \http_build_query([ 'grant_type' => 'refresh_token', 'refresh_token' => $refreshToken, @@ -120,8 +119,7 @@ class Tradeshift extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserID(string $accessToken): string @@ -132,8 +130,7 @@ class Tradeshift extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserEmail(string $accessToken): string @@ -148,20 +145,18 @@ class Tradeshift extends OAuth2 * * If present, the email is verified. This was verfied through a manual Tradeshift sign up process * - * @param string $accessToken - * + * @param string $accessToken * @return bool */ public function isEmailVerified(string $accessToken): bool { $email = $this->getUser($accessToken); - return !empty($email); + return ! empty($email); } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserName(string $accessToken): string @@ -171,12 +166,11 @@ class Tradeshift extends OAuth2 $firstName = $user['FirstName'] ?? ''; $lastName = $user['LastName'] ?? ''; - return $firstName . ' ' . $lastName; + return $firstName.' '.$lastName; } /** - * @param string $accessToken - * + * @param string $accessToken * @return array */ protected function getUser(string $accessToken): array @@ -184,14 +178,14 @@ class Tradeshift extends OAuth2 $header = [ 'Content-Type: application/json', 'Accept: application/json', - 'Host: ' . urlencode($this->apiDomain[$this->environment]), - 'Authorization: Bearer ' . $accessToken, + 'Host: '.urlencode($this->apiDomain[$this->environment]), + 'Authorization: Bearer '.$accessToken, ]; if (empty($this->user)) { $response = $this->request( 'GET', - $this->resourceEndpoint[$this->environment] . 'account/info/user', + $this->resourceEndpoint[$this->environment].'account/info/user', $header ); $this->user = \json_decode($response, true); diff --git a/src/Appwrite/Auth/OAuth2/TradeshiftBox.php b/src/Appwrite/Auth/OAuth2/TradeshiftBox.php index 27a4c0a456..d960acf2d3 100644 --- a/src/Appwrite/Auth/OAuth2/TradeshiftBox.php +++ b/src/Appwrite/Auth/OAuth2/TradeshiftBox.php @@ -2,8 +2,6 @@ namespace Appwrite\Auth\OAuth2; -use Appwrite\Auth\OAuth2\Tradeshift; - class TradeshiftBox extends Tradeshift { protected string $environment = 'sandbox'; diff --git a/src/Appwrite/Auth/OAuth2/Twitch.php b/src/Appwrite/Auth/OAuth2/Twitch.php index ed73054c31..dad2efe800 100644 --- a/src/Appwrite/Auth/OAuth2/Twitch.php +++ b/src/Appwrite/Auth/OAuth2/Twitch.php @@ -49,20 +49,19 @@ class Twitch extends OAuth2 */ public function getLoginURL(): string { - return $this->endpoint . 'authorize?' . + return $this->endpoint.'authorize?'. \http_build_query([ 'response_type' => 'code', 'client_id' => $this->appID, 'scope' => \implode(' ', $this->getScopes()), 'redirect_uri' => $this->callback, 'force_verify' => true, - 'state' => \json_encode($this->state) + 'state' => \json_encode($this->state), ]); } /** - * @param string $code - * + * @param string $code * @return array */ protected function getTokens(string $code): array @@ -70,12 +69,12 @@ class Twitch extends OAuth2 if (empty($this->tokens)) { $this->tokens = \json_decode($this->request( 'POST', - $this->endpoint . 'token?' . \http_build_query([ - "client_id" => $this->appID, - "client_secret" => $this->appSecret, - "code" => $code, - "grant_type" => "authorization_code", - "redirect_uri" => $this->callback + $this->endpoint.'token?'.\http_build_query([ + 'client_id' => $this->appID, + 'client_secret' => $this->appSecret, + 'code' => $code, + 'grant_type' => 'authorization_code', + 'redirect_uri' => $this->callback, ]) ), true); } @@ -84,19 +83,18 @@ class Twitch extends OAuth2 } /** - * @param string $refreshToken - * + * @param string $refreshToken * @return array */ public function refreshTokens(string $refreshToken): array { $this->tokens = \json_decode($this->request( 'POST', - $this->endpoint . 'token?' . \http_build_query([ - "client_id" => $this->appID, - "client_secret" => $this->appSecret, - "refresh_token" => $refreshToken, - "grant_type" => "refresh_token", + $this->endpoint.'token?'.\http_build_query([ + 'client_id' => $this->appID, + 'client_secret' => $this->appSecret, + 'refresh_token' => $refreshToken, + 'grant_type' => 'refresh_token', ]) ), true); @@ -108,8 +106,7 @@ class Twitch extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserID(string $accessToken): string @@ -120,8 +117,7 @@ class Twitch extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserEmail(string $accessToken): string @@ -138,20 +134,18 @@ class Twitch extends OAuth2 * * @link https://dev.twitch.tv/docs/api/reference#get-users * - * @param string $accessToken - * + * @param string $accessToken * @return bool */ public function isEmailVerified(string $accessToken): bool { $email = $this->getUserEmail($accessToken); - return !empty($email); + return ! empty($email); } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserName(string $accessToken): string @@ -162,8 +156,7 @@ class Twitch extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return array */ protected function getUser(string $accessToken) @@ -173,8 +166,8 @@ class Twitch extends OAuth2 'GET', $this->resourceEndpoint, [ - 'Authorization: Bearer ' . \urlencode($accessToken), - 'Client-Id: ' . \urlencode($this->appID) + 'Authorization: Bearer '.\urlencode($accessToken), + 'Client-Id: '.\urlencode($this->appID), ] ), true); diff --git a/src/Appwrite/Auth/OAuth2/WordPress.php b/src/Appwrite/Auth/OAuth2/WordPress.php index 1bd55916fc..084b890a5d 100644 --- a/src/Appwrite/Auth/OAuth2/WordPress.php +++ b/src/Appwrite/Auth/OAuth2/WordPress.php @@ -39,18 +39,17 @@ class WordPress extends OAuth2 */ public function getLoginURL(): string { - return 'https://public-api.wordpress.com/oauth2/authorize?' . \http_build_query([ + return 'https://public-api.wordpress.com/oauth2/authorize?'.\http_build_query([ 'client_id' => $this->appID, 'redirect_uri' => $this->callback, 'response_type' => 'code', 'scope' => $this->getScopes(), - 'state' => \json_encode($this->state) + 'state' => \json_encode($this->state), ]); } /** - * @param string $code - * + * @param string $code * @return array */ protected function getTokens(string $code): array @@ -65,7 +64,7 @@ class WordPress extends OAuth2 'redirect_uri' => $this->callback, 'client_secret' => $this->appSecret, 'grant_type' => 'authorization_code', - 'code' => $code + 'code' => $code, ]) ), true); } @@ -74,8 +73,7 @@ class WordPress extends OAuth2 } /** - * @param string $refreshToken - * + * @param string $refreshToken * @return array */ public function refreshTokens(string $refreshToken): array @@ -88,7 +86,7 @@ class WordPress extends OAuth2 'client_id' => $this->appID, 'client_secret' => $this->appSecret, 'grant_type' => 'refresh_token', - 'refresh_token' => $refreshToken + 'refresh_token' => $refreshToken, ]) ), true); @@ -100,8 +98,7 @@ class WordPress extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserID(string $accessToken): string @@ -112,8 +109,7 @@ class WordPress extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserEmail(string $accessToken): string @@ -132,8 +128,7 @@ class WordPress extends OAuth2 * * @link https://developer.wordpress.com/docs/api/1.1/get/me/ * - * @param string $accessToken - * + * @param string $accessToken * @return bool */ public function isEmailVerified(string $accessToken): bool @@ -148,8 +143,7 @@ class WordPress extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserName(string $accessToken): string @@ -160,14 +154,13 @@ class WordPress extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return array */ protected function getUser(string $accessToken) { if (empty($this->user)) { - $this->user = \json_decode($this->request('GET', 'https://public-api.wordpress.com/rest/v1/me', ['Authorization: Bearer ' . $accessToken]), true); + $this->user = \json_decode($this->request('GET', 'https://public-api.wordpress.com/rest/v1/me', ['Authorization: Bearer '.$accessToken]), true); } return $this->user; diff --git a/src/Appwrite/Auth/OAuth2/Yahoo.php b/src/Appwrite/Auth/OAuth2/Yahoo.php index c70a2fb6c9..82496d666c 100644 --- a/src/Appwrite/Auth/OAuth2/Yahoo.php +++ b/src/Appwrite/Auth/OAuth2/Yahoo.php @@ -45,10 +45,8 @@ class Yahoo extends OAuth2 return 'yahoo'; } - /** * @param $state - * * @return array */ public function parseState(string $state) @@ -61,37 +59,36 @@ class Yahoo extends OAuth2 */ public function getLoginURL(): string { - return $this->endpoint . 'request_auth?' . + return $this->endpoint.'request_auth?'. \http_build_query([ 'response_type' => 'code', 'client_id' => $this->appID, 'scope' => \implode(' ', $this->getScopes()), 'redirect_uri' => $this->callback, - 'state' => \json_encode($this->state) + 'state' => \json_encode($this->state), ]); } /** - * @param string $code - * + * @param string $code * @return array */ protected function getTokens(string $code): array { if (empty($this->tokens)) { $headers = [ - 'Authorization: Basic ' . \base64_encode($this->appID . ':' . $this->appSecret), + 'Authorization: Basic '.\base64_encode($this->appID.':'.$this->appSecret), 'Content-Type: application/x-www-form-urlencoded', ]; $this->tokens = \json_decode($this->request( 'POST', - $this->endpoint . 'get_token', + $this->endpoint.'get_token', $headers, \http_build_query([ - "code" => $code, - "grant_type" => "authorization_code", - "redirect_uri" => $this->callback + 'code' => $code, + 'grant_type' => 'authorization_code', + 'redirect_uri' => $this->callback, ]) ), true); } @@ -100,24 +97,23 @@ class Yahoo extends OAuth2 } /** - * @param string $refreshToken - * + * @param string $refreshToken * @return array */ public function refreshTokens(string $refreshToken): array { $headers = [ - 'Authorization: Basic ' . \base64_encode($this->appID . ':' . $this->appSecret), + 'Authorization: Basic '.\base64_encode($this->appID.':'.$this->appSecret), 'Content-Type: application/x-www-form-urlencoded', ]; $this->tokens = \json_decode($this->request( 'POST', - $this->endpoint . 'get_token', + $this->endpoint.'get_token', $headers, \http_build_query([ - "refresh_token" => $refreshToken, - "grant_type" => "refresh_token", + 'refresh_token' => $refreshToken, + 'grant_type' => 'refresh_token', ]) ), true); @@ -129,8 +125,7 @@ class Yahoo extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserID(string $accessToken): string @@ -141,8 +136,7 @@ class Yahoo extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserEmail(string $accessToken): string @@ -157,20 +151,18 @@ class Yahoo extends OAuth2 * * If present, the email is verified. This was verfied through a manual Yahoo sign up process * - * @param string $accessToken - * + * @param string $accessToken * @return bool */ public function isEmailVerified(string $accessToken): bool { $email = $this->getUserEmail($accessToken); - return !empty($email); + return ! empty($email); } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserName(string $accessToken): string @@ -181,8 +173,7 @@ class Yahoo extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return array */ protected function getUser(string $accessToken) @@ -191,7 +182,7 @@ class Yahoo extends OAuth2 $this->user = \json_decode($this->request( 'GET', $this->resourceEndpoint, - ['Authorization: Bearer ' . \urlencode($accessToken)] + ['Authorization: Bearer '.\urlencode($accessToken)] ), true); } diff --git a/src/Appwrite/Auth/OAuth2/Yammer.php b/src/Appwrite/Auth/OAuth2/Yammer.php index 9e1827bc58..c6d1ba2837 100644 --- a/src/Appwrite/Auth/OAuth2/Yammer.php +++ b/src/Appwrite/Auth/OAuth2/Yammer.php @@ -37,18 +37,17 @@ class Yammer extends OAuth2 */ public function getLoginURL(): string { - return $this->endpoint . 'oauth2/authorize?' . + return $this->endpoint.'oauth2/authorize?'. \http_build_query([ 'client_id' => $this->appID, 'response_type' => 'code', 'redirect_uri' => $this->callback, - 'state' => \json_encode($this->state) + 'state' => \json_encode($this->state), ]); } /** - * @param string $code - * + * @param string $code * @return array */ protected function getTokens(string $code): array @@ -57,13 +56,13 @@ class Yammer extends OAuth2 $headers = ['Content-Type: application/x-www-form-urlencoded']; $this->tokens = \json_decode($this->request( 'POST', - $this->endpoint . 'access_token?', + $this->endpoint.'access_token?', $headers, \http_build_query([ 'client_id' => $this->appID, 'client_secret' => $this->appSecret, 'code' => $code, - 'grant_type' => 'authorization_code' + 'grant_type' => 'authorization_code', ]) ), true); } @@ -72,8 +71,7 @@ class Yammer extends OAuth2 } /** - * @param string $refreshToken - * + * @param string $refreshToken * @return array */ public function refreshTokens(string $refreshToken): array @@ -81,13 +79,13 @@ class Yammer extends OAuth2 $headers = ['Content-Type: application/x-www-form-urlencoded']; $this->tokens = \json_decode($this->request( 'POST', - $this->endpoint . 'access_token?', + $this->endpoint.'access_token?', $headers, \http_build_query([ 'client_id' => $this->appID, 'client_secret' => $this->appSecret, 'refresh_token' => $refreshToken, - 'grant_type' => 'refresh_token' + 'grant_type' => 'refresh_token', ]) ), true); @@ -99,8 +97,7 @@ class Yammer extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserID(string $accessToken): string @@ -111,8 +108,7 @@ class Yammer extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserEmail(string $accessToken): string @@ -127,20 +123,18 @@ class Yammer extends OAuth2 * * If present, the email is verified. This was verfied through a manual Yammer sign up process * - * @param string $accessToken - * + * @param string $accessToken * @return bool */ public function isEmailVerified(string $accessToken): bool { $email = $this->getUserEmail($accessToken); - return !empty($email); + return ! empty($email); } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserName(string $accessToken): string @@ -151,14 +145,13 @@ class Yammer extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return array */ protected function getUser(string $accessToken): array { if (empty($this->user)) { - $headers = ['Authorization: Bearer ' . \urlencode($accessToken)]; + $headers = ['Authorization: Bearer '.\urlencode($accessToken)]; $user = $this->request('GET', 'https://www.yammer.com/api/v1/users/current.json', $headers); $this->user = \json_decode($user, true); } diff --git a/src/Appwrite/Auth/OAuth2/Yandex.php b/src/Appwrite/Auth/OAuth2/Yandex.php index a6a2e2e550..13e1fb4dfc 100644 --- a/src/Appwrite/Auth/OAuth2/Yandex.php +++ b/src/Appwrite/Auth/OAuth2/Yandex.php @@ -8,7 +8,6 @@ use Appwrite\Auth\OAuth2; // https://tech.yandex.com/passport/doc/dg/reference/request-docpage/ // https://tech.yandex.com/oauth/doc/dg/reference/web-client-docpage/ - class Yandex extends OAuth2 { /** @@ -35,8 +34,7 @@ class Yandex extends OAuth2 } /** - * @param string $state - * + * @param string $state * @return array */ public function parseState(string $state) @@ -44,30 +42,28 @@ class Yandex extends OAuth2 return \json_decode(\html_entity_decode($state), true); } - /** * @return string */ public function getLoginURL(): string { - return 'https://oauth.yandex.com/authorize?' . \http_build_query([ + return 'https://oauth.yandex.com/authorize?'.\http_build_query([ 'response_type' => 'code', 'client_id' => $this->appID, 'scope' => \implode(' ', $this->getScopes()), - 'state' => \json_encode($this->state) + 'state' => \json_encode($this->state), ]); } /** - * @param string $code - * + * @param string $code * @return array */ protected function getTokens(string $code): array { if (empty($this->tokens)) { $headers = [ - 'Authorization: Basic ' . \base64_encode($this->appID . ':' . $this->appSecret), + 'Authorization: Basic '.\base64_encode($this->appID.':'.$this->appSecret), 'Content-Type: application/x-www-form-urlencoded', ]; $this->tokens = \json_decode($this->request( @@ -76,7 +72,7 @@ class Yandex extends OAuth2 $headers, \http_build_query([ 'code' => $code, - 'grant_type' => 'authorization_code' + 'grant_type' => 'authorization_code', ]) ), true); } @@ -85,14 +81,13 @@ class Yandex extends OAuth2 } /** - * @param string $refreshToken - * + * @param string $refreshToken * @return array */ public function refreshTokens(string $refreshToken): array { $headers = [ - 'Authorization: Basic ' . \base64_encode($this->appID . ':' . $this->appSecret), + 'Authorization: Basic '.\base64_encode($this->appID.':'.$this->appSecret), 'Content-Type: application/x-www-form-urlencoded', ]; $this->tokens = \json_decode($this->request( @@ -101,7 +96,7 @@ class Yandex extends OAuth2 $headers, \http_build_query([ 'refresh_token' => $refreshToken, - 'grant_type' => 'authorization_code' + 'grant_type' => 'authorization_code', ]) ), true); @@ -113,8 +108,7 @@ class Yandex extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserID(string $accessToken): string @@ -125,8 +119,7 @@ class Yandex extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserEmail(string $accessToken): string @@ -139,8 +132,7 @@ class Yandex extends OAuth2 /** * Check if the OAuth email is verified * - * @param string $accessToken - * + * @param string $accessToken * @return bool */ public function isEmailVerified(string $accessToken): bool @@ -149,8 +141,7 @@ class Yandex extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserName(string $accessToken): string @@ -161,19 +152,19 @@ class Yandex extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return array */ protected function getUser(string $accessToken): array { if (empty($this->user)) { - $user = $this->request('GET', 'https://login.yandex.ru/info?' . \http_build_query([ + $user = $this->request('GET', 'https://login.yandex.ru/info?'.\http_build_query([ 'format' => 'json', - 'oauth_token' => $accessToken + 'oauth_token' => $accessToken, ])); $this->user = \json_decode($user, true); } + return $this->user; } } diff --git a/src/Appwrite/Auth/OAuth2/Zoom.php b/src/Appwrite/Auth/OAuth2/Zoom.php index 9dad22212a..01ade69a48 100644 --- a/src/Appwrite/Auth/OAuth2/Zoom.php +++ b/src/Appwrite/Auth/OAuth2/Zoom.php @@ -30,7 +30,7 @@ class Zoom extends OAuth2 * @var array */ protected array $scopes = [ - 'user_info:read' + 'user_info:read', ]; /** @@ -46,7 +46,7 @@ class Zoom extends OAuth2 */ public function getLoginURL(): string { - return $this->endpoint . '/oauth/authorize?' . \http_build_query([ + return $this->endpoint.'/oauth/authorize?'.\http_build_query([ 'client_id' => $this->appID, 'redirect_uri' => $this->callback, 'response_type' => 'code', @@ -56,22 +56,21 @@ class Zoom extends OAuth2 } /** - * @param string $code - * + * @param string $code * @return array */ protected function getTokens(string $code): array { if (empty($this->tokens)) { - $headers = ['Authorization: Basic ' . \base64_encode($this->appID . ':' . $this->appSecret), 'Content-Type: application/x-www-form-urlencoded']; + $headers = ['Authorization: Basic '.\base64_encode($this->appID.':'.$this->appSecret), 'Content-Type: application/x-www-form-urlencoded']; $this->tokens = \json_decode($this->request( 'POST', - $this->endpoint . '/oauth/token', + $this->endpoint.'/oauth/token', $headers, \http_build_query([ 'grant_type' => 'authorization_code', 'redirect_uri' => $this->callback, - 'code' => $code + 'code' => $code, ]) ), true); } @@ -80,16 +79,15 @@ class Zoom extends OAuth2 } /** - * @param string $refreshToken - * + * @param string $refreshToken * @return array */ public function refreshTokens(string $refreshToken): array { - $headers = ['Authorization: Basic ' . \base64_encode($this->appID . ':' . $this->appSecret), 'Content-Type: application/x-www-form-urlencoded']; + $headers = ['Authorization: Basic '.\base64_encode($this->appID.':'.$this->appSecret), 'Content-Type: application/x-www-form-urlencoded']; $this->tokens = \json_decode($this->request( 'POST', - $this->endpoint . '/oauth/token', + $this->endpoint.'/oauth/token', $headers, \http_build_query([ 'grant_type' => 'refresh_token', @@ -105,8 +103,7 @@ class Zoom extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserID(string $accessToken): string @@ -117,8 +114,7 @@ class Zoom extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserEmail(string $accessToken): string @@ -133,8 +129,7 @@ class Zoom extends OAuth2 * * @link https://marketplace.zoom.us/docs/api-reference/zoom-api/methods/#operation/user * - * @param string $accessToken - * + * @param string $accessToken * @return bool */ public function isEmailVerified(string $accessToken): bool @@ -149,26 +144,24 @@ class Zoom extends OAuth2 } /** - * @param string $accessToken - * + * @param string $accessToken * @return string */ public function getUserName(string $accessToken): string { $response = $this->getUser($accessToken); - return ($response['first_name'] ?? '') . ' ' . ($response['last_name'] ?? ''); + return ($response['first_name'] ?? '').' '.($response['last_name'] ?? ''); } /** - * @param string $accessToken - * + * @param string $accessToken * @return array */ protected function getUser(string $accessToken) { $headers = [ - 'Authorization: Bearer ' . \urlencode($accessToken) + 'Authorization: Bearer '.\urlencode($accessToken), ]; if (empty($this->user)) { diff --git a/src/Appwrite/Auth/Validator/Password.php b/src/Appwrite/Auth/Validator/Password.php index 93a9f74114..e997d03f81 100644 --- a/src/Appwrite/Auth/Validator/Password.php +++ b/src/Appwrite/Auth/Validator/Password.php @@ -26,13 +26,12 @@ class Password extends Validator /** * Is valid. * - * @param mixed $value - * + * @param mixed $value * @return bool */ public function isValid($value): bool { - if (!\is_string($value)) { + if (! \is_string($value)) { return false; } diff --git a/src/Appwrite/Auth/Validator/Phone.php b/src/Appwrite/Auth/Validator/Phone.php index 32c3ca3398..49d78ac8c6 100644 --- a/src/Appwrite/Auth/Validator/Phone.php +++ b/src/Appwrite/Auth/Validator/Phone.php @@ -26,13 +26,12 @@ class Phone extends Validator /** * Is valid. * - * @param mixed $value - * + * @param mixed $value * @return bool */ public function isValid($value): bool { - return is_string($value) && !!\preg_match('/^\+[1-9]\d{1,14}$/', $value); + return is_string($value) && (bool) \preg_match('/^\+[1-9]\d{1,14}$/', $value); } /** diff --git a/src/Appwrite/DSN/DSN.php b/src/Appwrite/DSN/DSN.php index 5605640989..d0571fbcee 100644 --- a/src/Appwrite/DSN/DSN.php +++ b/src/Appwrite/DSN/DSN.php @@ -44,13 +44,13 @@ class DSN * * Construct a new DSN object * - * @param string $dsn + * @param string $dsn */ public function __construct(string $dsn) { $parts = parse_url($dsn); - if (!$parts) { + if (! $parts) { throw new \InvalidArgumentException("Unable to parse DSN: $dsn"); } diff --git a/src/Appwrite/Detector/Detector.php b/src/Appwrite/Detector/Detector.php index 62f7a0a04b..ed1be7325b 100644 --- a/src/Appwrite/Detector/Detector.php +++ b/src/Appwrite/Detector/Detector.php @@ -17,7 +17,7 @@ class Detector protected $detctor; /** - * @param string $userAgent + * @param string $userAgent */ public function __construct(string $userAgent) { @@ -54,7 +54,7 @@ class Detector 'type' => 'desktop', 'short_name' => 'cli', 'name' => 'Appwrite CLI', - 'version' => $version + 'version' => $version, ]; } else { $client = $this->getDetector()->getClient(); @@ -89,7 +89,7 @@ class Detector */ protected function getDetector(): DeviceDetector { - if (!$this->detctor) { + if (! $this->detctor) { $this->detctor = new DeviceDetector($this->userAgent); $this->detctor->skipBotDetection(); // OPTIONAL: If called, bot detection will completely be skipped (bots will be detected as regular devices then) $this->detctor->parse(); @@ -103,7 +103,7 @@ class Detector * It is needed if we want bots to be processed as a simple clients. So we can detect if it is mobile client, * or desktop, or enything else. By default all this information is not retrieved for the bots. * - * @param bool $skip + * @param bool $skip */ public function skipBotDetection(bool $skip = true): void { diff --git a/src/Appwrite/Docker/Compose.php b/src/Appwrite/Docker/Compose.php index 64441805de..0b4a8b16b9 100644 --- a/src/Appwrite/Docker/Compose.php +++ b/src/Appwrite/Docker/Compose.php @@ -13,7 +13,7 @@ class Compose protected $compose = []; /** - * @var string $data + * @var string */ public function __construct(string $data) { @@ -48,7 +48,7 @@ class Compose */ public function getService(string $name): Service { - if (!isset($this->compose['services'][$name])) { + if (! isset($this->compose['services'][$name])) { throw new Exception('Service not found'); } diff --git a/src/Appwrite/Docker/Compose/Service.php b/src/Appwrite/Docker/Compose/Service.php index a3f9c91253..32c12b82b1 100644 --- a/src/Appwrite/Docker/Compose/Service.php +++ b/src/Appwrite/Docker/Compose/Service.php @@ -12,7 +12,7 @@ class Service protected $service = []; /** - * @var string $path + * @var string */ public function __construct(array $service) { @@ -54,7 +54,8 @@ class Service public function getImageVersion(): string { $image = $this->getImage(); - return substr($image, ((int)strpos($image, ':')) + 1); + + return substr($image, ((int) strpos($image, ':')) + 1); } /** diff --git a/src/Appwrite/Docker/Env.php b/src/Appwrite/Docker/Env.php index bce12a95e6..6351ce4f78 100644 --- a/src/Appwrite/Docker/Env.php +++ b/src/Appwrite/Docker/Env.php @@ -2,8 +2,6 @@ namespace Appwrite\Docker; -use Exception; - class Env { /** @@ -12,7 +10,7 @@ class Env protected $vars = []; /** - * @var string $data + * @var string */ public function __construct(string $data) { @@ -30,9 +28,8 @@ class Env } /** - * @param string $key - * @param mixed $value - * + * @param string $key + * @param mixed $value * @return $this */ public function setVar(string $key, $value): self @@ -43,8 +40,7 @@ class Env } /** - * @param string $key - * + * @param string $key * @return string */ public function getVar(string $key): string @@ -70,7 +66,7 @@ class Env $output = ''; foreach ($this->vars as $key => $value) { - $output .= $key . '=' . $value . "\n"; + $output .= $key.'='.$value."\n"; } return $output; diff --git a/src/Appwrite/Event/Audit.php b/src/Appwrite/Event/Audit.php index 254f7c294a..da396bba17 100644 --- a/src/Appwrite/Event/Audit.php +++ b/src/Appwrite/Event/Audit.php @@ -7,8 +7,11 @@ use Resque; class Audit extends Event { protected string $resource = ''; + protected string $mode = ''; + protected string $userAgent = ''; + protected string $ip = ''; public function __construct() @@ -19,7 +22,7 @@ class Audit extends Event /** * Set resource for this audit event. * - * @param string $resource + * @param string $resource * @return self */ public function setResource(string $resource): self @@ -42,7 +45,7 @@ class Audit extends Event /** * Set mode for this audit event * - * @param string $mode + * @param string $mode * @return self */ public function setMode(string $mode): self @@ -65,7 +68,7 @@ class Audit extends Event /** * Set user agent for this audit event. * - * @param string $userAgent + * @param string $userAgent * @return self */ public function setUserAgent(string $userAgent): self @@ -88,7 +91,7 @@ class Audit extends Event /** * Set IP for this audit event. * - * @param string $ip + * @param string $ip * @return self */ public function setIP(string $ip): self @@ -112,6 +115,7 @@ class Audit extends Event * Executes the event and sends it to the audit worker. * * @return string|bool + * * @throws \InvalidArgumentException */ public function trigger(): string|bool diff --git a/src/Appwrite/Event/Build.php b/src/Appwrite/Event/Build.php index 4d4b338118..92e4659dd7 100644 --- a/src/Appwrite/Event/Build.php +++ b/src/Appwrite/Event/Build.php @@ -8,7 +8,9 @@ use Utopia\Database\Document; class Build extends Event { protected string $type = ''; + protected ?Document $resource = null; + protected ?Document $deployment = null; public function __construct() @@ -19,7 +21,7 @@ class Build extends Event /** * Sets resource document for the build event. * - * @param Document $resource + * @param Document $resource * @return self */ public function setResource(Document $resource): self @@ -42,7 +44,7 @@ class Build extends Event /** * Sets deployment for the build event. * - * @param Document $deployment + * @param Document $deployment * @return self */ public function setDeployment(Document $deployment): self @@ -65,7 +67,7 @@ class Build extends Event /** * Sets type for the build event. * - * @param string $type Can be `BUILD_TYPE_DEPLOYMENT` or `BUILD_TYPE_RETRY`. + * @param string $type Can be `BUILD_TYPE_DEPLOYMENT` or `BUILD_TYPE_RETRY`. * @return self */ public function setType(string $type): self @@ -89,6 +91,7 @@ class Build extends Event * Executes the function event and sends it to the functions worker. * * @return string|bool + * * @throws \InvalidArgumentException */ public function trigger(): string|bool @@ -97,7 +100,7 @@ class Build extends Event 'project' => $this->project, 'resource' => $this->resource, 'deployment' => $this->deployment, - 'type' => $this->type + 'type' => $this->type, ]); } } diff --git a/src/Appwrite/Event/Certificate.php b/src/Appwrite/Event/Certificate.php index d3d9091804..c39adbed8f 100644 --- a/src/Appwrite/Event/Certificate.php +++ b/src/Appwrite/Event/Certificate.php @@ -8,6 +8,7 @@ use Utopia\Database\Document; class Certificate extends Event { protected bool $skipRenewCheck = false; + protected ?Document $domain = null; public function __construct() @@ -18,7 +19,7 @@ class Certificate extends Event /** * Set domain for this certificates event. * - * @param Document $domain + * @param Document $domain * @return self */ public function setDomain(Document $domain): self @@ -41,7 +42,7 @@ class Certificate extends Event /** * Set if the certificate needs to be validated. * - * @param bool $skipRenewCheck + * @param bool $skipRenewCheck * @return self */ public function setSkipRenewCheck(bool $skipRenewCheck): self @@ -65,6 +66,7 @@ class Certificate extends Event * Executes the event and sends it to the certificates worker. * * @return string|bool + * * @throws \InvalidArgumentException */ public function trigger(): string|bool @@ -72,7 +74,7 @@ class Certificate extends Event return Resque::enqueue($this->queue, $this->class, [ 'project' => $this->project, 'domain' => $this->domain, - 'skipRenewCheck' => $this->skipRenewCheck + 'skipRenewCheck' => $this->skipRenewCheck, ]); } } diff --git a/src/Appwrite/Event/Database.php b/src/Appwrite/Event/Database.php index 1822f06c71..cc83263d71 100644 --- a/src/Appwrite/Event/Database.php +++ b/src/Appwrite/Event/Database.php @@ -8,8 +8,11 @@ use Utopia\Database\Document; class Database extends Event { protected string $type = ''; + protected ?Document $database = null; + protected ?Document $collection = null; + protected ?Document $document = null; public function __construct() @@ -20,7 +23,7 @@ class Database extends Event /** * Sets the type for this database event (use the constants starting with DATABASE_TYPE_*). * - * @param string $type + * @param string $type * @return self */ public function setType(string $type): self @@ -32,6 +35,7 @@ class Database extends Event /** * Returns the set type for the database event. + * * @return string */ public function getType(): string @@ -42,19 +46,20 @@ class Database extends Event /** * Set the database for this event * - * @param Document $database + * @param Document $database * @return self */ public function setDatabase(Document $database): self { $this->database = $database; + return $this; } /** * Set the collection for this database event. * - * @param Document $collection + * @param Document $collection * @return self */ public function setCollection(Document $collection): self @@ -77,7 +82,7 @@ class Database extends Event /** * Set the document for this database event. * - * @param Document $document + * @param Document $document * @return self */ public function setDocument(Document $document): self @@ -89,6 +94,7 @@ class Database extends Event /** * Returns set document for this database event. + * * @return null|Document */ public function getDocument(): ?Document @@ -100,6 +106,7 @@ class Database extends Event * Executes the event and send it to the database worker. * * @return string|bool + * * @throws \InvalidArgumentException */ public function trigger(): string|bool @@ -111,7 +118,7 @@ class Database extends Event 'collection' => $this->collection, 'document' => $this->document, 'database' => $this->database, - 'events' => Event::generateEvents($this->getEvent(), $this->getParams()) + 'events' => Event::generateEvents($this->getEvent(), $this->getParams()), ]); } } diff --git a/src/Appwrite/Event/Delete.php b/src/Appwrite/Event/Delete.php index d1519121a6..dee01ed6bf 100644 --- a/src/Appwrite/Event/Delete.php +++ b/src/Appwrite/Event/Delete.php @@ -8,11 +8,14 @@ use Utopia\Database\Document; class Delete extends Event { protected string $type = ''; - protected ?Document $document = null; - protected ?string $resource = null; - protected ?string $datetime = null; - protected ?string $hourlyUsageRetentionDatetime = null; + protected ?Document $document = null; + + protected ?string $resource = null; + + protected ?string $datetime = null; + + protected ?string $hourlyUsageRetentionDatetime = null; public function __construct() { @@ -22,7 +25,7 @@ class Delete extends Event /** * Sets the type for the delete event (use the constants starting with DELETE_TYPE_*). * - * @param string $type + * @param string $type * @return self */ public function setType(string $type): self @@ -45,31 +48,33 @@ class Delete extends Event /** * set Datetime. * - * @param string $datetime + * @param string $datetime * @return self */ public function setDatetime(string $datetime): self { $this->datetime = $datetime; + return $this; } /** * Sets datetime for 1h interval. * - * @param string $datetime + * @param string $datetime * @return self */ public function setUsageRetentionHourlyDateTime(string $datetime): self { $this->hourlyUsageRetentionDatetime = $datetime; + return $this; } /** * Sets the document for the delete event. * - * @param Document $document + * @param Document $document * @return self */ public function setDocument(Document $document): self @@ -92,7 +97,7 @@ class Delete extends Event /** * Sets the resource for the delete event. * - * @param string $resource + * @param string $resource * @return self */ public function setResource(string $resource): self @@ -112,11 +117,11 @@ class Delete extends Event return $this->document; } - /** * Executes this event and sends it to the deletes worker. * * @return string|bool + * * @throws \InvalidArgumentException */ public function trigger(): string|bool diff --git a/src/Appwrite/Event/Event.php b/src/Appwrite/Event/Event.php index 222cf59444..d7478e556f 100644 --- a/src/Appwrite/Event/Event.php +++ b/src/Appwrite/Event/Event.php @@ -9,44 +9,60 @@ use Utopia\Database\Document; class Event { public const DATABASE_QUEUE_NAME = 'v1-database'; + public const DATABASE_CLASS_NAME = 'DatabaseV1'; public const DELETE_QUEUE_NAME = 'v1-deletes'; + public const DELETE_CLASS_NAME = 'DeletesV1'; public const AUDITS_QUEUE_NAME = 'v1-audits'; + public const AUDITS_CLASS_NAME = 'AuditsV1'; public const MAILS_QUEUE_NAME = 'v1-mails'; + public const MAILS_CLASS_NAME = 'MailsV1'; public const FUNCTIONS_QUEUE_NAME = 'v1-functions'; + public const FUNCTIONS_CLASS_NAME = 'FunctionsV1'; public const WEBHOOK_QUEUE_NAME = 'v1-webhooks'; + public const WEBHOOK_CLASS_NAME = 'WebhooksV1'; public const CERTIFICATES_QUEUE_NAME = 'v1-certificates'; + public const CERTIFICATES_CLASS_NAME = 'CertificatesV1'; public const BUILDS_QUEUE_NAME = 'v1-builds'; + public const BUILDS_CLASS_NAME = 'BuildsV1'; public const MESSAGING_QUEUE_NAME = 'v1-messaging'; + public const MESSAGING_CLASS_NAME = 'MessagingV1'; protected string $queue = ''; + protected string $class = ''; + protected string $event = ''; + protected array $params = []; + protected array $payload = []; + protected array $context = []; + protected ?Document $project = null; + protected ?Document $user = null; /** - * @param string $queue - * @param string $class + * @param string $queue + * @param string $class * @return void */ public function __construct(string $queue, string $class) @@ -58,7 +74,7 @@ class Event /** * Set queue used for this event. * - * @param string $queue + * @param string $queue * @return Event */ public function setQueue(string $queue): self @@ -80,7 +96,8 @@ class Event /** * Set event name used for this event. - * @param string $event + * + * @param string $event * @return Event */ public function setEvent(string $event): self @@ -103,7 +120,7 @@ class Event /** * Set project for this event. * - * @param Document $project + * @param Document $project * @return self */ public function setProject(Document $project): self @@ -126,7 +143,7 @@ class Event /** * Set user for this event. * - * @param Document $user + * @param Document $user * @return self */ public function setUser(Document $user): self @@ -149,7 +166,7 @@ class Event /** * Set payload for this event. * - * @param array $payload + * @param array $payload * @return self */ public function setPayload(array $payload): self @@ -172,8 +189,8 @@ class Event /** * Set context for this event. * - * @param string $key - * @param Document $context + * @param string $key + * @param Document $context * @return self */ public function setContext(string $key, Document $context): self @@ -186,8 +203,7 @@ class Event /** * Get context for this event. * - * @param string $key - * + * @param string $key * @return null|Document */ public function getContext(string $key): ?Document @@ -197,7 +213,8 @@ class Event /** * Set class used for this event. - * @param string $class + * + * @param string $class * @return self */ public function setClass(string $class): self @@ -220,8 +237,8 @@ class Event /** * Set param of event. * - * @param string $key - * @param mixed $value + * @param string $key + * @param mixed $value * @return self */ public function setParam(string $key, mixed $value): self @@ -234,7 +251,7 @@ class Event /** * Get param of event. * - * @param string $key + * @param string $key * @return mixed */ public function getParam(string $key): mixed @@ -256,6 +273,7 @@ class Event * Execute Event. * * @return string|bool + * * @throws InvalidArgumentException */ public function trigger(): string|bool @@ -265,7 +283,7 @@ class Event 'user' => $this->user, 'payload' => $this->payload, 'context' => $this->context, - 'events' => Event::generateEvents($this->getEvent(), $this->getParams()) + 'events' => Event::generateEvents($this->getEvent(), $this->getParams()), ]); } @@ -284,7 +302,7 @@ class Event /** * Parses event pattern and returns the parts in their respective section. * - * @param string $pattern + * @param string $pattern * @return array */ public static function parseEventPattern(string $pattern): array @@ -313,13 +331,13 @@ class Event } } - if ($hasSubResource && !$hasSubSubResource) { + if ($hasSubResource && ! $hasSubSubResource) { if ($count === 6) { $attribute = $parts[5]; } } - if (!$hasSubResource) { + if (! $hasSubResource) { if ($count === 4) { $attribute = $parts[3]; } @@ -331,14 +349,12 @@ class Event $subSubResource ??= false; $attribute ??= false; $action = match (true) { - !$hasSubResource && $count > 2 => $parts[2], + ! $hasSubResource && $count > 2 => $parts[2], $hasSubSubResource => $parts[6] ?? false, $hasSubResource && $count > 4 => $parts[4], default => false }; - - return [ 'type' => $type, 'resource' => $resource, @@ -354,9 +370,10 @@ class Event /** * Generates all possible events from a pattern. * - * @param string $pattern - * @param array $params + * @param string $pattern + * @param array $params * @return array + * * @throws \InvalidArgumentException */ public static function generateEvents(string $pattern, array $params = []): array @@ -377,15 +394,15 @@ class Event $action = $parsed['action']; $attribute = $parsed['attribute']; - if ($resource && !\in_array(\trim($resource, "\[\]"), $paramKeys)) { + if ($resource && ! \in_array(\trim($resource, "\[\]"), $paramKeys)) { throw new InvalidArgumentException("{$resource} is missing from the params."); } - if ($subResource && !\in_array(\trim($subResource, "\[\]"), $paramKeys)) { + if ($subResource && ! \in_array(\trim($subResource, "\[\]"), $paramKeys)) { throw new InvalidArgumentException("{$subResource} is missing from the params."); } - if ($subSubResource && !\in_array(\trim($subSubResource, "\[\]"), $paramKeys)) { + if ($subSubResource && ! \in_array(\trim($subSubResource, "\[\]"), $paramKeys)) { throw new InvalidArgumentException("{$subSubResource} is missing from the params."); } @@ -439,9 +456,9 @@ class Event if ($subCurrent === $current || $subCurrent === $key) { continue; } - $filtered1 = \array_filter($paramKeys, fn(string $k) => $k === $subCurrent); + $filtered1 = \array_filter($paramKeys, fn (string $k) => $k === $subCurrent); $events[] = \str_replace($paramKeys, $paramValues, \str_replace($filtered1, '*', $eventPattern)); - $filtered2 = \array_filter($paramKeys, fn(string $k) => $k === $current); + $filtered2 = \array_filter($paramKeys, fn (string $k) => $k === $current); $events[] = \str_replace($paramKeys, $paramValues, \str_replace($filtered2, '*', \str_replace($filtered1, '*', $eventPattern))); $events[] = \str_replace($paramKeys, $paramValues, \str_replace($filtered2, '*', $eventPattern)); } @@ -449,7 +466,7 @@ class Event if ($current === $key) { continue; } - $filtered = \array_filter($paramKeys, fn(string $k) => $k === $current); + $filtered = \array_filter($paramKeys, fn (string $k) => $k === $current); $events[] = \str_replace($paramKeys, $paramValues, \str_replace($filtered, '*', $eventPattern)); } } diff --git a/src/Appwrite/Event/Func.php b/src/Appwrite/Event/Func.php index b7531cf475..5ec7d481c4 100644 --- a/src/Appwrite/Event/Func.php +++ b/src/Appwrite/Event/Func.php @@ -10,9 +10,13 @@ use Utopia\Database\Document; class Func extends Event { protected string $jwt = ''; + protected string $type = ''; + protected string $data = ''; + protected ?Document $function = null; + protected ?Document $execution = null; public function __construct() @@ -23,7 +27,7 @@ class Func extends Event /** * Sets function document for the function event. * - * @param Document $function + * @param Document $function * @return self */ public function setFunction(Document $function): self @@ -46,7 +50,7 @@ class Func extends Event /** * Sets execution for the function event. * - * @param Document $execution + * @param Document $execution * @return self */ public function setExecution(Document $execution): self @@ -69,7 +73,7 @@ class Func extends Event /** * Sets type for the function event. * - * @param string $type Can be `schedule`, `event` or `http`. + * @param string $type Can be `schedule`, `event` or `http`. * @return self */ public function setType(string $type): self @@ -92,7 +96,7 @@ class Func extends Event /** * Sets custom data for the function event. * - * @param string $data + * @param string $data * @return self */ public function setData(string $data): self @@ -115,7 +119,7 @@ class Func extends Event /** * Sets JWT for the function event. * - * @param string $jwt + * @param string $jwt * @return self */ public function setJWT(string $jwt): self @@ -139,6 +143,7 @@ class Func extends Event * Executes the function event and sends it to the functions worker. * * @return string|bool + * * @throws \InvalidArgumentException */ public function trigger(): string|bool @@ -151,15 +156,16 @@ class Func extends Event 'type' => $this->type, 'jwt' => $this->jwt, 'payload' => $this->payload, - 'data' => $this->data + 'data' => $this->data, ]); } /** * Schedules the function event and schedules it in the functions worker queue. * - * @param \DateTime|int $at + * @param \DateTime|int $at * @return void + * * @throws \Resque_Exception * @throws \ResqueScheduler_InvalidTimestampException */ @@ -172,7 +178,7 @@ class Func extends Event 'execution' => $this->execution, 'type' => $this->type, 'payload' => $this->payload, - 'data' => $this->data + 'data' => $this->data, ]); } } diff --git a/src/Appwrite/Event/Mail.php b/src/Appwrite/Event/Mail.php index 1b7e218d69..e6a8319cfa 100644 --- a/src/Appwrite/Event/Mail.php +++ b/src/Appwrite/Event/Mail.php @@ -3,14 +3,17 @@ namespace Appwrite\Event; use Resque; -use Utopia\Database\Document; class Mail extends Event { protected string $recipient = ''; + protected string $from = ''; + protected string $name = ''; + protected string $subject = ''; + protected string $body = ''; public function __construct() @@ -21,7 +24,7 @@ class Mail extends Event /** * Sets subject for the mail event. * - * @param string $subject + * @param string $subject * @return self */ public function setSubject(string $subject): self @@ -44,7 +47,7 @@ class Mail extends Event /** * Sets recipient for the mail event. * - * @param string $recipient + * @param string $recipient * @return self */ public function setRecipient(string $recipient): self @@ -67,7 +70,7 @@ class Mail extends Event /** * Sets from for the mail event. * - * @param string $from + * @param string $from * @return self */ public function setFrom(string $from): self @@ -90,7 +93,7 @@ class Mail extends Event /** * Sets body for the mail event. * - * @param string $body + * @param string $body * @return self */ public function setBody(string $body): self @@ -113,7 +116,7 @@ class Mail extends Event /** * Sets name for the mail event. * - * @param string $name + * @param string $name * @return self */ public function setName(string $name): self @@ -137,6 +140,7 @@ class Mail extends Event * Executes the event and sends it to the mails worker. * * @return string|bool + * * @throws \InvalidArgumentException */ public function trigger(): string|bool @@ -147,7 +151,7 @@ class Mail extends Event 'name' => $this->name, 'subject' => $this->subject, 'body' => $this->body, - 'events' => Event::generateEvents($this->getEvent(), $this->getParams()) + 'events' => Event::generateEvents($this->getEvent(), $this->getParams()), ]); } } diff --git a/src/Appwrite/Event/Phone.php b/src/Appwrite/Event/Phone.php index 8baa5120c9..87bee4bc37 100644 --- a/src/Appwrite/Event/Phone.php +++ b/src/Appwrite/Event/Phone.php @@ -7,6 +7,7 @@ use Resque; class Phone extends Event { protected string $recipient = ''; + protected string $message = ''; public function __construct() @@ -17,7 +18,7 @@ class Phone extends Event /** * Sets recipient for the messaging event. * - * @param string $recipient + * @param string $recipient * @return self */ public function setRecipient(string $recipient): self @@ -40,7 +41,7 @@ class Phone extends Event /** * Sets url for the messaging event. * - * @param string $message + * @param string $message * @return self */ public function setMessage(string $message): self @@ -64,6 +65,7 @@ class Phone extends Event * Executes the event and sends it to the messaging worker. * * @return string|bool + * * @throws \InvalidArgumentException */ public function trigger(): string|bool @@ -74,7 +76,7 @@ class Phone extends Event 'payload' => $this->payload, 'recipient' => $this->recipient, 'message' => $this->message, - 'events' => Event::generateEvents($this->getEvent(), $this->getParams()) + 'events' => Event::generateEvents($this->getEvent(), $this->getParams()), ]); } } diff --git a/src/Appwrite/Event/Validator/Event.php b/src/Appwrite/Event/Validator/Event.php index 4bf501f2d3..102d6dc128 100644 --- a/src/Appwrite/Event/Validator/Event.php +++ b/src/Appwrite/Event/Validator/Event.php @@ -22,8 +22,7 @@ class Event extends Validator /** * Is valid. * - * @param mixed $value - * + * @param mixed $value * @return bool */ public function isValid($value): bool @@ -44,7 +43,7 @@ class Event extends Validator $hasSubResource = $count > 3 && ($events[$type]['$resource'] ?? false) && ($events[$type][$parts[2]]['$resource'] ?? false); $hasSubSubResource = $count > 5 && $hasSubResource && ($events[$type][$parts[2]][$parts[4]]['$resource'] ?? false); - if (!$type || !$resource) { + if (! $type || ! $resource) { return false; } @@ -61,13 +60,13 @@ class Event extends Validator } } - if ($hasSubResource && !$hasSubSubResource) { + if ($hasSubResource && ! $hasSubSubResource) { if ($count === 6) { $attribute = $parts[5]; } } - if (!$hasSubResource) { + if (! $hasSubResource) { if ($count === 4) { $attribute = $parts[3]; } @@ -80,36 +79,36 @@ class Event extends Validator $attribute ??= false; $action = match (true) { - !$hasSubResource && $count > 2 => $parts[2], + ! $hasSubResource && $count > 2 => $parts[2], $hasSubSubResource => $parts[6] ?? false, $hasSubResource && $count > 4 => $parts[4], default => false }; - if (!\array_key_exists($type, $events)) { + if (! \array_key_exists($type, $events)) { return false; } if ($subType) { - if ($action && !\array_key_exists($action, $events[$type][$subType])) { + if ($action && ! \array_key_exists($action, $events[$type][$subType])) { return false; } - if (!($subResource) || !\array_key_exists($subType, $events[$type])) { + if (! ($subResource) || ! \array_key_exists($subType, $events[$type])) { return false; } } else { - if ($action && !\array_key_exists($action, $events[$type])) { + if ($action && ! \array_key_exists($action, $events[$type])) { return false; } } if ($attribute) { if (($subType)) { - if (!\array_key_exists($attribute, $events[$type][$subType][$action])) { + if (! \array_key_exists($attribute, $events[$type][$subType][$action])) { return false; } } else { - if (!\array_key_exists($attribute, $events[$type][$action])) { + if (! \array_key_exists($attribute, $events[$type][$action])) { return false; } } diff --git a/src/Appwrite/Extend/Exception.php b/src/Appwrite/Extend/Exception.php index 9e2e8f9cb1..569caff431 100644 --- a/src/Appwrite/Extend/Exception.php +++ b/src/Appwrite/Extend/Exception.php @@ -35,153 +35,236 @@ class Exception extends \Exception */ /** General */ - public const GENERAL_UNKNOWN = 'general_unknown'; - public const GENERAL_MOCK = 'general_mock'; - public const GENERAL_ACCESS_FORBIDDEN = 'general_access_forbidden'; - public const GENERAL_UNKNOWN_ORIGIN = 'general_unknown_origin'; - public const GENERAL_SERVICE_DISABLED = 'general_service_disabled'; - public const GENERAL_UNAUTHORIZED_SCOPE = 'general_unauthorized_scope'; - public const GENERAL_RATE_LIMIT_EXCEEDED = 'general_rate_limit_exceeded'; - public const GENERAL_SMTP_DISABLED = 'general_smtp_disabled'; - public const GENERAL_PHONE_DISABLED = 'general_phone_disabled'; - public const GENERAL_ARGUMENT_INVALID = 'general_argument_invalid'; - public const GENERAL_QUERY_LIMIT_EXCEEDED = 'general_query_limit_exceeded'; - public const GENERAL_QUERY_INVALID = 'general_query_invalid'; - public const GENERAL_ROUTE_NOT_FOUND = 'general_route_not_found'; - public const GENERAL_CURSOR_NOT_FOUND = 'general_cursor_not_found'; - public const GENERAL_SERVER_ERROR = 'general_server_error'; - public const GENERAL_PROTOCOL_UNSUPPORTED = 'general_protocol_unsupported'; + public const GENERAL_UNKNOWN = 'general_unknown'; + + public const GENERAL_MOCK = 'general_mock'; + + public const GENERAL_ACCESS_FORBIDDEN = 'general_access_forbidden'; + + public const GENERAL_UNKNOWN_ORIGIN = 'general_unknown_origin'; + + public const GENERAL_SERVICE_DISABLED = 'general_service_disabled'; + + public const GENERAL_UNAUTHORIZED_SCOPE = 'general_unauthorized_scope'; + + public const GENERAL_RATE_LIMIT_EXCEEDED = 'general_rate_limit_exceeded'; + + public const GENERAL_SMTP_DISABLED = 'general_smtp_disabled'; + + public const GENERAL_PHONE_DISABLED = 'general_phone_disabled'; + + public const GENERAL_ARGUMENT_INVALID = 'general_argument_invalid'; + + public const GENERAL_QUERY_LIMIT_EXCEEDED = 'general_query_limit_exceeded'; + + public const GENERAL_QUERY_INVALID = 'general_query_invalid'; + + public const GENERAL_ROUTE_NOT_FOUND = 'general_route_not_found'; + + public const GENERAL_CURSOR_NOT_FOUND = 'general_cursor_not_found'; + + public const GENERAL_SERVER_ERROR = 'general_server_error'; + + public const GENERAL_PROTOCOL_UNSUPPORTED = 'general_protocol_unsupported'; /** Users */ - public const USER_COUNT_EXCEEDED = 'user_count_exceeded'; - public const USER_JWT_INVALID = 'user_jwt_invalid'; - public const USER_ALREADY_EXISTS = 'user_already_exists'; - public const USER_BLOCKED = 'user_blocked'; - public const USER_INVALID_TOKEN = 'user_invalid_token'; - public const USER_PASSWORD_RESET_REQUIRED = 'user_password_reset_required'; - public const USER_EMAIL_NOT_WHITELISTED = 'user_email_not_whitelisted'; - public const USER_IP_NOT_WHITELISTED = 'user_ip_not_whitelisted'; - public const USER_INVALID_CREDENTIALS = 'user_invalid_credentials'; + public const USER_COUNT_EXCEEDED = 'user_count_exceeded'; + + public const USER_JWT_INVALID = 'user_jwt_invalid'; + + public const USER_ALREADY_EXISTS = 'user_already_exists'; + + public const USER_BLOCKED = 'user_blocked'; + + public const USER_INVALID_TOKEN = 'user_invalid_token'; + + public const USER_PASSWORD_RESET_REQUIRED = 'user_password_reset_required'; + + public const USER_EMAIL_NOT_WHITELISTED = 'user_email_not_whitelisted'; + + public const USER_IP_NOT_WHITELISTED = 'user_ip_not_whitelisted'; + + public const USER_INVALID_CREDENTIALS = 'user_invalid_credentials'; + public const USER_ANONYMOUS_CONSOLE_PROHIBITED = 'user_anonymous_console_prohibited'; - public const USER_SESSION_ALREADY_EXISTS = 'user_session_already_exists'; - public const USER_NOT_FOUND = 'user_not_found'; - public const USER_EMAIL_ALREADY_EXISTS = 'user_email_already_exists'; - public const USER_PASSWORD_MISMATCH = 'user_password_mismatch'; - public const USER_SESSION_NOT_FOUND = 'user_session_not_found'; - public const USER_UNAUTHORIZED = 'user_unauthorized'; - public const USER_AUTH_METHOD_UNSUPPORTED = 'user_auth_method_unsupported'; - public const USER_PHONE_ALREADY_EXISTS = 'user_phone_already_exists'; - public const USER_PHONE_NOT_FOUND = 'user_phone_not_found'; - public const USER_MISSING_ID = 'user_missing_id'; + + public const USER_SESSION_ALREADY_EXISTS = 'user_session_already_exists'; + + public const USER_NOT_FOUND = 'user_not_found'; + + public const USER_EMAIL_ALREADY_EXISTS = 'user_email_already_exists'; + + public const USER_PASSWORD_MISMATCH = 'user_password_mismatch'; + + public const USER_SESSION_NOT_FOUND = 'user_session_not_found'; + + public const USER_UNAUTHORIZED = 'user_unauthorized'; + + public const USER_AUTH_METHOD_UNSUPPORTED = 'user_auth_method_unsupported'; + + public const USER_PHONE_ALREADY_EXISTS = 'user_phone_already_exists'; + + public const USER_PHONE_NOT_FOUND = 'user_phone_not_found'; + + public const USER_MISSING_ID = 'user_missing_id'; /** Teams */ - public const TEAM_NOT_FOUND = 'team_not_found'; - public const TEAM_INVITE_ALREADY_EXISTS = 'team_invite_already_exists'; - public const TEAM_INVITE_NOT_FOUND = 'team_invite_not_found'; - public const TEAM_INVALID_SECRET = 'team_invalid_secret'; - public const TEAM_MEMBERSHIP_MISMATCH = 'team_membership_mismatch'; - public const TEAM_INVITE_MISMATCH = 'team_invite_mismatch'; + public const TEAM_NOT_FOUND = 'team_not_found'; + + public const TEAM_INVITE_ALREADY_EXISTS = 'team_invite_already_exists'; + + public const TEAM_INVITE_NOT_FOUND = 'team_invite_not_found'; + + public const TEAM_INVALID_SECRET = 'team_invalid_secret'; + + public const TEAM_MEMBERSHIP_MISMATCH = 'team_membership_mismatch'; + + public const TEAM_INVITE_MISMATCH = 'team_invite_mismatch'; /** Membership */ - public const MEMBERSHIP_NOT_FOUND = 'membership_not_found'; - public const MEMBERSHIP_ALREADY_CONFIRMED = 'membership_already_confirmed'; + public const MEMBERSHIP_NOT_FOUND = 'membership_not_found'; + + public const MEMBERSHIP_ALREADY_CONFIRMED = 'membership_already_confirmed'; /** Avatars */ - public const AVATAR_SET_NOT_FOUND = 'avatar_set_not_found'; - public const AVATAR_NOT_FOUND = 'avatar_not_found'; - public const AVATAR_IMAGE_NOT_FOUND = 'avatar_image_not_found'; - public const AVATAR_REMOTE_URL_FAILED = 'avatar_remote_url_failed'; - public const AVATAR_ICON_NOT_FOUND = 'avatar_icon_not_found'; + public const AVATAR_SET_NOT_FOUND = 'avatar_set_not_found'; + + public const AVATAR_NOT_FOUND = 'avatar_not_found'; + + public const AVATAR_IMAGE_NOT_FOUND = 'avatar_image_not_found'; + + public const AVATAR_REMOTE_URL_FAILED = 'avatar_remote_url_failed'; + + public const AVATAR_ICON_NOT_FOUND = 'avatar_icon_not_found'; /** Storage */ - public const STORAGE_FILE_NOT_FOUND = 'storage_file_not_found'; - public const STORAGE_DEVICE_NOT_FOUND = 'storage_device_not_found'; - public const STORAGE_FILE_EMPTY = 'storage_file_empty'; - public const STORAGE_FILE_TYPE_UNSUPPORTED = 'storage_file_type_unsupported'; - public const STORAGE_INVALID_FILE_SIZE = 'storage_invalid_file_size'; - public const STORAGE_INVALID_FILE = 'storage_invalid_file'; - public const STORAGE_BUCKET_ALREADY_EXISTS = 'storage_bucket_already_exists'; - public const STORAGE_BUCKET_NOT_FOUND = 'storage_bucket_not_found'; - public const STORAGE_INVALID_CONTENT_RANGE = 'storage_invalid_content_range'; - public const STORAGE_INVALID_RANGE = 'storage_invalid_range'; + public const STORAGE_FILE_NOT_FOUND = 'storage_file_not_found'; + + public const STORAGE_DEVICE_NOT_FOUND = 'storage_device_not_found'; + + public const STORAGE_FILE_EMPTY = 'storage_file_empty'; + + public const STORAGE_FILE_TYPE_UNSUPPORTED = 'storage_file_type_unsupported'; + + public const STORAGE_INVALID_FILE_SIZE = 'storage_invalid_file_size'; + + public const STORAGE_INVALID_FILE = 'storage_invalid_file'; + + public const STORAGE_BUCKET_ALREADY_EXISTS = 'storage_bucket_already_exists'; + + public const STORAGE_BUCKET_NOT_FOUND = 'storage_bucket_not_found'; + + public const STORAGE_INVALID_CONTENT_RANGE = 'storage_invalid_content_range'; + + public const STORAGE_INVALID_RANGE = 'storage_invalid_range'; /** Functions */ - public const FUNCTION_NOT_FOUND = 'function_not_found'; - public const FUNCTION_RUNTIME_UNSUPPORTED = 'function_runtime_unsupported'; + public const FUNCTION_NOT_FOUND = 'function_not_found'; + + public const FUNCTION_RUNTIME_UNSUPPORTED = 'function_runtime_unsupported'; /** Deployments */ - public const DEPLOYMENT_NOT_FOUND = 'deployment_not_found'; + public const DEPLOYMENT_NOT_FOUND = 'deployment_not_found'; /** Builds */ - public const BUILD_NOT_FOUND = 'build_not_found'; - public const BUILD_NOT_READY = 'build_not_ready'; - public const BUILD_IN_PROGRESS = 'build_in_progress'; + public const BUILD_NOT_FOUND = 'build_not_found'; + + public const BUILD_NOT_READY = 'build_not_ready'; + + public const BUILD_IN_PROGRESS = 'build_in_progress'; /** Execution */ - public const EXECUTION_NOT_FOUND = 'execution_not_found'; + public const EXECUTION_NOT_FOUND = 'execution_not_found'; /** Databases */ - public const DATABASE_NOT_FOUND = 'database_not_found'; - public const DATABASE_ALREADY_EXISTS = 'database_already_exists'; + public const DATABASE_NOT_FOUND = 'database_not_found'; + + public const DATABASE_ALREADY_EXISTS = 'database_already_exists'; /** Collections */ - public const COLLECTION_NOT_FOUND = 'collection_not_found'; - public const COLLECTION_ALREADY_EXISTS = 'collection_already_exists'; - public const COLLECTION_LIMIT_EXCEEDED = 'collection_limit_exceeded'; + public const COLLECTION_NOT_FOUND = 'collection_not_found'; + + public const COLLECTION_ALREADY_EXISTS = 'collection_already_exists'; + + public const COLLECTION_LIMIT_EXCEEDED = 'collection_limit_exceeded'; /** Documents */ - public const DOCUMENT_NOT_FOUND = 'document_not_found'; - public const DOCUMENT_INVALID_STRUCTURE = 'document_invalid_structure'; - public const DOCUMENT_MISSING_PAYLOAD = 'document_missing_payload'; - public const DOCUMENT_ALREADY_EXISTS = 'document_already_exists'; + public const DOCUMENT_NOT_FOUND = 'document_not_found'; + + public const DOCUMENT_INVALID_STRUCTURE = 'document_invalid_structure'; + + public const DOCUMENT_MISSING_PAYLOAD = 'document_missing_payload'; + + public const DOCUMENT_ALREADY_EXISTS = 'document_already_exists'; /** Attribute */ - public const ATTRIBUTE_NOT_FOUND = 'attribute_not_found'; - public const ATTRIBUTE_UNKNOWN = 'attribute_unknown'; - public const ATTRIBUTE_NOT_AVAILABLE = 'attribute_not_available'; - public const ATTRIBUTE_FORMAT_UNSUPPORTED = 'attribute_format_unsupported'; - public const ATTRIBUTE_DEFAULT_UNSUPPORTED = 'attribute_default_unsupported'; - public const ATTRIBUTE_ALREADY_EXISTS = 'attribute_already_exists'; - public const ATTRIBUTE_LIMIT_EXCEEDED = 'attribute_limit_exceeded'; - public const ATTRIBUTE_VALUE_INVALID = 'attribute_value_invalid'; + public const ATTRIBUTE_NOT_FOUND = 'attribute_not_found'; + + public const ATTRIBUTE_UNKNOWN = 'attribute_unknown'; + + public const ATTRIBUTE_NOT_AVAILABLE = 'attribute_not_available'; + + public const ATTRIBUTE_FORMAT_UNSUPPORTED = 'attribute_format_unsupported'; + + public const ATTRIBUTE_DEFAULT_UNSUPPORTED = 'attribute_default_unsupported'; + + public const ATTRIBUTE_ALREADY_EXISTS = 'attribute_already_exists'; + + public const ATTRIBUTE_LIMIT_EXCEEDED = 'attribute_limit_exceeded'; + + public const ATTRIBUTE_VALUE_INVALID = 'attribute_value_invalid'; /** Indexes */ - public const INDEX_NOT_FOUND = 'index_not_found'; - public const INDEX_LIMIT_EXCEEDED = 'index_limit_exceeded'; - public const INDEX_ALREADY_EXISTS = 'index_already_exists'; + public const INDEX_NOT_FOUND = 'index_not_found'; + + public const INDEX_LIMIT_EXCEEDED = 'index_limit_exceeded'; + + public const INDEX_ALREADY_EXISTS = 'index_already_exists'; /** Projects */ - public const PROJECT_NOT_FOUND = 'project_not_found'; - public const PROJECT_UNKNOWN = 'project_unknown'; - public const PROJECT_PROVIDER_DISABLED = 'project_provider_disabled'; - public const PROJECT_PROVIDER_UNSUPPORTED = 'project_provider_unsupported'; - public const PROJECT_INVALID_SUCCESS_URL = 'project_invalid_success_url'; - public const PROJECT_INVALID_FAILURE_URL = 'project_invalid_failure_url'; - public const PROJECT_RESERVED_PROJECT = 'project_reserved_project'; - public const PROJECT_KEY_EXPIRED = 'project_key_expired'; + public const PROJECT_NOT_FOUND = 'project_not_found'; + + public const PROJECT_UNKNOWN = 'project_unknown'; + + public const PROJECT_PROVIDER_DISABLED = 'project_provider_disabled'; + + public const PROJECT_PROVIDER_UNSUPPORTED = 'project_provider_unsupported'; + + public const PROJECT_INVALID_SUCCESS_URL = 'project_invalid_success_url'; + + public const PROJECT_INVALID_FAILURE_URL = 'project_invalid_failure_url'; + + public const PROJECT_RESERVED_PROJECT = 'project_reserved_project'; + + public const PROJECT_KEY_EXPIRED = 'project_key_expired'; /** Webhooks */ - public const WEBHOOK_NOT_FOUND = 'webhook_not_found'; + public const WEBHOOK_NOT_FOUND = 'webhook_not_found'; /** Keys */ - public const KEY_NOT_FOUND = 'key_not_found'; + public const KEY_NOT_FOUND = 'key_not_found'; /** Variables */ - public const VARIABLE_NOT_FOUND = 'variable_not_found'; - public const VARIABLE_ALREADY_EXISTS = 'variable_already_exists'; + public const VARIABLE_NOT_FOUND = 'variable_not_found'; + + public const VARIABLE_ALREADY_EXISTS = 'variable_already_exists'; /** Platform */ - public const PLATFORM_NOT_FOUND = 'platform_not_found'; + public const PLATFORM_NOT_FOUND = 'platform_not_found'; /** Domain */ - public const DOMAIN_NOT_FOUND = 'domain_not_found'; - public const DOMAIN_ALREADY_EXISTS = 'domain_already_exists'; - public const DOMAIN_VERIFICATION_FAILED = 'domain_verification_failed'; - public const DOMAIN_TARGET_INVALID = 'domain_target_invalid'; + public const DOMAIN_NOT_FOUND = 'domain_not_found'; + + public const DOMAIN_ALREADY_EXISTS = 'domain_already_exists'; + + public const DOMAIN_VERIFICATION_FAILED = 'domain_verification_failed'; + + public const DOMAIN_TARGET_INVALID = 'domain_target_invalid'; /** GraphqQL */ - public const GRAPHQL_NO_QUERY = 'graphql_no_query'; - public const GRAPHQL_TOO_MANY_QUERIES = 'graphql_too_many_queries'; + public const GRAPHQL_NO_QUERY = 'graphql_no_query'; + + public const GRAPHQL_TOO_MANY_QUERIES = 'graphql_too_many_queries'; protected $type = ''; @@ -214,8 +297,7 @@ class Exception extends \Exception /** * Set the type of the exception. * - * @param string $type - * + * @param string $type * @return void */ public function setType(string $type): void diff --git a/src/Appwrite/Extend/PDO.php b/src/Appwrite/Extend/PDO.php index bc3f42afb9..3a510e2a76 100644 --- a/src/Appwrite/Extend/PDO.php +++ b/src/Appwrite/Extend/PDO.php @@ -77,6 +77,7 @@ class PDO extends PDONative $result = $this->pdo->rollBack(); } catch (\Throwable $th) { $this->pdo = $this->reconnect(); + return false; } @@ -99,7 +100,7 @@ class PDO extends PDONative { $this->pdo = new PDONative($this->dsn, $this->username, $this->passwd, $this->options); - echo '[PDO] MySQL connection restarted' . PHP_EOL; + echo '[PDO] MySQL connection restarted'.PHP_EOL; // Connection settings $this->pdo->setAttribute(PDONative::ATTR_DEFAULT_FETCH_MODE, PDONative::FETCH_ASSOC); // Return arrays diff --git a/src/Appwrite/Extend/PDOStatement.php b/src/Appwrite/Extend/PDOStatement.php index 9c5a83ec34..f6b8d3e08c 100644 --- a/src/Appwrite/Extend/PDOStatement.php +++ b/src/Appwrite/Extend/PDOStatement.php @@ -101,9 +101,8 @@ class PDOStatement extends PDOStatementNative /** * Fetch All * - * @param int $fetch_style - * @param mixed $fetch_args - * + * @param int $fetch_style + * @param mixed $fetch_args * @return array|false */ public function fetchAll(int $fetch_style = PDO::FETCH_BOTH, mixed ...$fetch_args) diff --git a/src/Appwrite/GraphQL/Promises/Adapter.php b/src/Appwrite/GraphQL/Promises/Adapter.php index 86270f2a8b..0051dbe612 100644 --- a/src/Appwrite/GraphQL/Promises/Adapter.php +++ b/src/Appwrite/GraphQL/Promises/Adapter.php @@ -22,14 +22,15 @@ abstract class Adapter implements PromiseAdapter /** * Converts a {@see Promise} into a {@see GQLPromise} * - * @param mixed $thenable + * @param mixed $thenable * @return GQLPromise + * * @throws \Exception */ public function convertThenable(mixed $thenable): GQLPromise { - if (!$thenable instanceof Promise) { - throw new \Exception('Expected instance of Promise got: ' . \gettype($thenable)); + if (! $thenable instanceof Promise) { + throw new \Exception('Expected instance of Promise got: '.\gettype($thenable)); } return new GQLPromise($thenable, $this); @@ -38,9 +39,9 @@ abstract class Adapter implements PromiseAdapter /** * Returns a promise that resolves when the passed in promise resolves. * - * @param GQLPromise $promise - * @param callable|null $onFulfilled - * @param callable|null $onRejected + * @param GQLPromise $promise + * @param callable|null $onFulfilled + * @param callable|null $onRejected * @return GQLPromise */ public function then( @@ -57,7 +58,7 @@ abstract class Adapter implements PromiseAdapter /** * Create a new promise with the given resolver function. * - * @param callable $resolver + * @param callable $resolver * @return GQLPromise */ abstract public function create(callable $resolver): GQLPromise; @@ -65,7 +66,7 @@ abstract class Adapter implements PromiseAdapter /** * Create a new promise that is fulfilled with the given value. * - * @param mixed $value + * @param mixed $value * @return GQLPromise */ abstract public function createFulfilled(mixed $value = null): GQLPromise; @@ -73,7 +74,7 @@ abstract class Adapter implements PromiseAdapter /** * Create a new promise that is rejected with the given reason. * - * @param mixed $reason + * @param mixed $reason * @return GQLPromise */ abstract public function createRejected(mixed $reason): GQLPromise; @@ -81,7 +82,7 @@ abstract class Adapter implements PromiseAdapter /** * Create a new promise that resolves when all passed in promises resolve. * - * @param array $promisesOrValues + * @param array $promisesOrValues * @return GQLPromise */ abstract public function all(array $promisesOrValues): GQLPromise; diff --git a/src/Appwrite/GraphQL/Resolvers.php b/src/Appwrite/GraphQL/Resolvers.php index c143a93554..3c5ba4b310 100644 --- a/src/Appwrite/GraphQL/Resolvers.php +++ b/src/Appwrite/GraphQL/Resolvers.php @@ -15,28 +15,28 @@ class Resolvers /** * Create a resolver for a given API {@see Route}. * - * @param App $utopia - * @param ?Route $route + * @param App $utopia + * @param ?Route $route * @return callable */ public static function api( App $utopia, ?Route $route, - ): callable { - return static fn($type, $args, $context, $info) => new Swoole( - function (callable $resolve, callable $reject) use ($utopia, $route, $args, $context, $info) { + ): callable + { + return static fn ($type, $args, $context, $info) => new Swoole( + function (callable $resolve, callable $reject) use ($utopia, $route, $args) { /** @var App $utopia */ /** @var Response $response */ /** @var Request $request */ - $utopia = $utopia->getResource('utopia:graphql', true); $request = $utopia->getResource('request', true); $response = $utopia->getResource('response', true); $path = $route->getPath(); foreach ($args as $key => $value) { - if (\str_contains($path, '/:' . $key)) { - $path = \str_replace(':' . $key, $value, $path); + if (\str_contains($path, '/:'.$key)) { + $path = \str_replace(':'.$key, $value, $path); } } @@ -60,10 +60,10 @@ class Resolvers /** * Create a resolver for a document in a specified database and collection with a specific method type. * - * @param App $utopia - * @param string $databaseId - * @param string $collectionId - * @param string $methodType + * @param App $utopia + * @param string $databaseId + * @param string $collectionId + * @param string $methodType * @return callable */ public static function document( @@ -71,8 +71,9 @@ class Resolvers string $databaseId, string $collectionId, string $methodType, - ): callable { - return [self::class, 'document' . \ucfirst($methodType)]( + ): callable + { + return [self::class, 'document'.\ucfirst($methodType)]( $utopia, $databaseId, $collectionId @@ -82,10 +83,10 @@ class Resolvers /** * Create a resolver for getting a document in a specified database and collection. * - * @param App $utopia - * @param string $databaseId - * @param string $collectionId - * @param callable $url + * @param App $utopia + * @param string $databaseId + * @param string $collectionId + * @param callable $url * @return callable */ public static function documentGet( @@ -93,9 +94,10 @@ class Resolvers string $databaseId, string $collectionId, callable $url, - ): callable { - return static fn($type, $args, $context, $info) => new Swoole( - function (callable $resolve, callable $reject) use ($utopia, $databaseId, $collectionId, $url, $type, $args) { + ): callable + { + return static fn ($type, $args, $context, $info) => new Swoole( + function (callable $resolve, callable $reject) use ($utopia, $databaseId, $collectionId, $url, $args) { $utopia = $utopia->getResource('utopia:graphql', true); $request = $utopia->getResource('request', true); $response = $utopia->getResource('response', true); @@ -111,11 +113,11 @@ class Resolvers /** * Create a resolver for listing documents in a specified database and collection. * - * @param App $utopia - * @param string $databaseId - * @param string $collectionId - * @param callable $url - * @param callable $params + * @param App $utopia + * @param string $databaseId + * @param string $collectionId + * @param callable $url + * @param callable $params * @return callable */ public static function documentList( @@ -124,9 +126,10 @@ class Resolvers string $collectionId, callable $url, callable $params, - ): callable { - return static fn($type, $args, $context, $info) => new Swoole( - function (callable $resolve, callable $reject) use ($utopia, $databaseId, $collectionId, $url, $params, $type, $args) { + ): callable + { + return static fn ($type, $args, $context, $info) => new Swoole( + function (callable $resolve, callable $reject) use ($utopia, $databaseId, $collectionId, $url, $params, $args) { $utopia = $utopia->getResource('utopia:graphql', true); $request = $utopia->getResource('request', true); $response = $utopia->getResource('response', true); @@ -147,11 +150,11 @@ class Resolvers /** * Create a resolver for creating a document in a specified database and collection. * - * @param App $utopia - * @param string $databaseId - * @param string $collectionId - * @param callable $url - * @param callable $params + * @param App $utopia + * @param string $databaseId + * @param string $collectionId + * @param callable $url + * @param callable $params * @return callable */ public static function documentCreate( @@ -160,9 +163,10 @@ class Resolvers string $collectionId, callable $url, callable $params, - ): callable { - return static fn($type, $args, $context, $info) => new Swoole( - function (callable $resolve, callable $reject) use ($utopia, $databaseId, $collectionId, $url, $params, $type, $args) { + ): callable + { + return static fn ($type, $args, $context, $info) => new Swoole( + function (callable $resolve, callable $reject) use ($utopia, $databaseId, $collectionId, $url, $params, $args) { $utopia = $utopia->getResource('utopia:graphql', true); $request = $utopia->getResource('request', true); $response = $utopia->getResource('response', true); @@ -179,11 +183,11 @@ class Resolvers /** * Create a resolver for updating a document in a specified database and collection. * - * @param App $utopia - * @param string $databaseId - * @param string $collectionId - * @param callable $url - * @param callable $params + * @param App $utopia + * @param string $databaseId + * @param string $collectionId + * @param callable $url + * @param callable $params * @return callable */ public static function documentUpdate( @@ -192,9 +196,10 @@ class Resolvers string $collectionId, callable $url, callable $params, - ): callable { - return static fn($type, $args, $context, $info) => new Swoole( - function (callable $resolve, callable $reject) use ($utopia, $databaseId, $collectionId, $url, $params, $type, $args) { + ): callable + { + return static fn ($type, $args, $context, $info) => new Swoole( + function (callable $resolve, callable $reject) use ($utopia, $databaseId, $collectionId, $url, $params, $args) { $utopia = $utopia->getResource('utopia:graphql', true); $request = $utopia->getResource('request', true); $response = $utopia->getResource('response', true); @@ -211,10 +216,10 @@ class Resolvers /** * Create a resolver for deleting a document in a specified database and collection. * - * @param App $utopia - * @param string $databaseId - * @param string $collectionId - * @param callable $url + * @param App $utopia + * @param string $databaseId + * @param string $collectionId + * @param callable $url * @return callable */ public static function documentDelete( @@ -222,9 +227,10 @@ class Resolvers string $databaseId, string $collectionId, callable $url, - ): callable { - return static fn($type, $args, $context, $info) => new Swoole( - function (callable $resolve, callable $reject) use ($utopia, $databaseId, $collectionId, $url, $type, $args) { + ): callable + { + return static fn ($type, $args, $context, $info) => new Swoole( + function (callable $resolve, callable $reject) use ($utopia, $databaseId, $collectionId, $url, $args) { $utopia = $utopia->getResource('utopia:graphql', true); $request = $utopia->getResource('request', true); $response = $utopia->getResource('response', true); @@ -238,14 +244,15 @@ class Resolvers } /** - * @param App $utopia - * @param Request $request - * @param Response $response - * @param callable $resolve - * @param callable $reject - * @param callable|null $beforeResolve - * @param callable|null $beforeReject + * @param App $utopia + * @param Request $request + * @param Response $response + * @param callable $resolve + * @param callable $reject + * @param callable|null $beforeResolve + * @param callable|null $beforeReject * @return void + * * @throws Exception */ private static function resolve( @@ -263,7 +270,7 @@ class Resolvers } $request = clone $request; - $utopia->setResource('request', static fn() => $request); + $utopia->setResource('request', static fn () => $request); $response->setContentType(Response::CONTENT_TYPE_NULL); try { @@ -275,6 +282,7 @@ class Resolvers $e = $beforeReject($e); } $reject($e); + return; } @@ -288,6 +296,7 @@ class Resolvers message: $payload['message'], code: $response->getStatusCode() )); + return; } diff --git a/src/Appwrite/GraphQL/Schema.php b/src/Appwrite/GraphQL/Schema.php index 11f728e571..608369ef80 100644 --- a/src/Appwrite/GraphQL/Schema.php +++ b/src/Appwrite/GraphQL/Schema.php @@ -13,16 +13,17 @@ use Utopia\Route; class Schema { protected static ?GQLSchema $schema = null; + protected static array $dirty = []; /** - * - * @param App $utopia - * @param callable $complexity Function to calculate complexity - * @param callable $attributes Function to get attributes - * @param array $urls Array of functions to get urls for specific method types - * @param array $params Array of functions to build parameters for specific method types + * @param App $utopia + * @param callable $complexity Function to calculate complexity + * @param callable $attributes Function to get attributes + * @param array $urls Array of functions to get urls for specific method types + * @param array $params Array of functions to build parameters for specific method types * @return GQLSchema + * * @throws Exception */ public static function build( @@ -36,7 +37,7 @@ class Schema return $utopia; }); - if (!empty(self::$schema)) { + if (! empty(self::$schema)) { return self::$schema; } @@ -67,12 +68,12 @@ class Schema return static::$schema = new GQLSchema([ 'query' => new ObjectType([ 'name' => 'Query', - 'fields' => $queries + 'fields' => $queries, ]), 'mutation' => new ObjectType([ 'name' => 'Mutation', - 'fields' => $mutations - ]) + 'fields' => $mutations, + ]), ]); } @@ -80,9 +81,10 @@ class Schema * This function iterates all API routes and builds a GraphQL * schema defining types and resolvers for all response models. * - * @param App $utopia - * @param callable $complexity + * @param App $utopia + * @param callable $complexity * @return array + * * @throws Exception */ protected static function api(App $utopia, callable $complexity): array @@ -97,10 +99,9 @@ class Schema foreach ($utopia->getRoutes() as $routes) { foreach ($routes as $route) { /** @var Route $route */ - $namespace = $route->getLabel('sdk.namespace', ''); $method = $route->getLabel('sdk.method', ''); - $name = $namespace . \ucfirst($method); + $name = $namespace.\ucfirst($method); if (empty($name)) { continue; @@ -126,7 +127,7 @@ class Schema return [ 'query' => $queries, - 'mutation' => $mutations + 'mutation' => $mutations, ]; } @@ -134,12 +135,13 @@ class Schema * Iterates all of a projects attributes and builds GraphQL * queries and mutations for the collections they make up. * - * @param App $utopia - * @param callable $complexity - * @param callable $attributes - * @param array $urls - * @param array $params + * @param App $utopia + * @param callable $complexity + * @param callable $attributes + * @param array $urls + * @param array $params * @return array + * * @throws \Exception */ protected static function collections( @@ -155,7 +157,7 @@ class Schema $limit = 1000; $offset = 0; - while (!empty($attrs = $attributes($limit, $offset))) { + while (! empty($attrs = $attributes($limit, $offset))) { foreach ($attrs as $attr) { if ($attr['status'] !== 'available') { continue; @@ -182,7 +184,7 @@ class Schema $objectType = new ObjectType([ 'name' => $collectionId, 'fields' => \array_merge( - ["_id" => ['type' => Type::string()]], + ['_id' => ['type' => Type::string()]], $attributes ), ]); @@ -191,7 +193,7 @@ class Schema Mapper::args('mutate') ); - $queryFields[$collectionId . 'Get'] = [ + $queryFields[$collectionId.'Get'] = [ 'type' => $objectType, 'args' => Mapper::args('id'), 'resolve' => Resolvers::documentGet( @@ -199,9 +201,9 @@ class Schema $databaseId, $collectionId, $urls['get'], - ) + ), ]; - $queryFields[$collectionId . 'List'] = [ + $queryFields[$collectionId.'List'] = [ 'type' => Type::listOf($objectType), 'args' => Mapper::args('list'), 'resolve' => Resolvers::documentList( @@ -214,7 +216,7 @@ class Schema 'complexity' => $complexity, ]; - $mutationFields[$collectionId . 'Create'] = [ + $mutationFields[$collectionId.'Create'] = [ 'type' => $objectType, 'args' => $attributes, 'resolve' => Resolvers::documentCreate( @@ -223,14 +225,14 @@ class Schema $collectionId, $urls['create'], $params['create'], - ) + ), ]; - $mutationFields[$collectionId . 'Update'] = [ + $mutationFields[$collectionId.'Update'] = [ 'type' => $objectType, 'args' => \array_merge( Mapper::args('id'), \array_map( - fn($attr) => $attr['type'] = Type::getNullableType($attr['type']), + fn ($attr) => $attr['type'] = Type::getNullableType($attr['type']), $attributes ) ), @@ -240,9 +242,9 @@ class Schema $collectionId, $urls['update'], $params['update'], - ) + ), ]; - $mutationFields[$collectionId . 'Delete'] = [ + $mutationFields[$collectionId.'Delete'] = [ 'type' => Mapper::model('none'), 'args' => Mapper::args('id'), 'resolve' => Resolvers::documentDelete( @@ -250,7 +252,7 @@ class Schema $databaseId, $collectionId, $urls['delete'], - ) + ), ]; } $offset += $limit; @@ -258,7 +260,7 @@ class Schema return [ 'query' => $queryFields, - 'mutation' => $mutationFields + 'mutation' => $mutationFields, ]; } diff --git a/src/Appwrite/GraphQL/Types.php b/src/Appwrite/GraphQL/Types.php index 279cac2068..b20c4cb32e 100644 --- a/src/Appwrite/GraphQL/Types.php +++ b/src/Appwrite/GraphQL/Types.php @@ -22,6 +22,7 @@ class Types } $type = new Json(); Registry::set(Json::class, $type); + return $type; } @@ -37,6 +38,7 @@ class Types } $type = new Assoc(); Registry::set(Assoc::class, $type); + return $type; } @@ -52,6 +54,7 @@ class Types } $type = new InputFile(); Registry::set(InputFile::class, $type); + return $type; } } diff --git a/src/Appwrite/GraphQL/Types/Assoc.php b/src/Appwrite/GraphQL/Types/Assoc.php index a2099f9b22..58584ff60f 100644 --- a/src/Appwrite/GraphQL/Types/Assoc.php +++ b/src/Appwrite/GraphQL/Types/Assoc.php @@ -2,19 +2,13 @@ namespace Appwrite\GraphQL\Types; -use GraphQL\Language\AST\BooleanValueNode; -use GraphQL\Language\AST\FloatValueNode; -use GraphQL\Language\AST\IntValueNode; -use GraphQL\Language\AST\ListValueNode; use GraphQL\Language\AST\Node; -use GraphQL\Language\AST\ObjectValueNode; -use GraphQL\Language\AST\StringValueNode; -use GraphQL\Type\Definition\ScalarType; // https://github.com/webonyx/graphql-php/issues/129#issuecomment-309366803 class Assoc extends Json { public $name = 'Assoc'; + public $description = 'The `Assoc` scalar type represents associative array values.'; public function serialize($value) diff --git a/src/Appwrite/GraphQL/Types/InputFile.php b/src/Appwrite/GraphQL/Types/InputFile.php index 39fd4e23b3..6d55ab5359 100644 --- a/src/Appwrite/GraphQL/Types/InputFile.php +++ b/src/Appwrite/GraphQL/Types/InputFile.php @@ -9,6 +9,7 @@ use GraphQL\Type\Definition\ScalarType; class InputFile extends ScalarType { public $name = 'InputFile'; + public $description = 'The `InputFile` special type represents a file to be uploaded in the same HTTP request as specified by [graphql-multipart-request-spec](https://github.com/jaydenseric/graphql-multipart-request-spec).'; @@ -24,6 +25,6 @@ class InputFile extends ScalarType public function parseLiteral(Node $valueNode, ?array $variables = null) { - throw new Error('`InputFile` cannot be hardcoded in query, be sure to conform to GraphQL multipart request specification. Instead got: ' . $valueNode->kind, $valueNode); + throw new Error('`InputFile` cannot be hardcoded in query, be sure to conform to GraphQL multipart request specification. Instead got: '.$valueNode->kind, $valueNode); } } diff --git a/src/Appwrite/GraphQL/Types/Json.php b/src/Appwrite/GraphQL/Types/Json.php index 18d27322a1..305432cb90 100644 --- a/src/Appwrite/GraphQL/Types/Json.php +++ b/src/Appwrite/GraphQL/Types/Json.php @@ -15,6 +15,7 @@ use GraphQL\Type\Definition\ScalarType; class Json extends ScalarType { public $name = 'Json'; + public $description = 'The `JSON` scalar type represents JSON values as specified by [ECMA-404](https://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf).'; @@ -43,8 +44,9 @@ class Json extends ScalarType $value[$field->name->value] = $this->parseLiteral($field->value); } + return $value; - case ($valueNode instanceof ListValueNode): + case $valueNode instanceof ListValueNode: return array_map([$this, 'parseLiteral'], $valueNode->values); default: return null; diff --git a/src/Appwrite/GraphQL/Types/Mapper.php b/src/Appwrite/GraphQL/Types/Mapper.php index 42bdc4b149..612991baa6 100644 --- a/src/Appwrite/GraphQL/Types/Mapper.php +++ b/src/Appwrite/GraphQL/Types/Mapper.php @@ -15,7 +15,9 @@ use Utopia\Validator; class Mapper { private static array $models = []; + private static array $args = []; + private static array $blacklist = [ '/v1/mock', '/v1/graphql', @@ -42,7 +44,7 @@ class Mapper 'permissions' => [ 'type' => Type::listOf(Type::nonNull(Type::string())), 'defaultValue' => [], - ] + ], ], ]; @@ -65,7 +67,7 @@ class Mapper /** * Get the registered default arguments for a given key. * - * @param string $key + * @param string $key * @return array */ public static function args(string $key): array @@ -86,7 +88,7 @@ class Mapper $names = $route->getLabel('sdk.response.model', 'none'); $models = \is_array($names) - ? \array_map(static fn($m) => static::$models[$m], $names) + ? \array_map(static fn ($m) => static::$models[$m], $names) : [static::$models[$names]]; foreach ($models as $model) { @@ -102,7 +104,7 @@ class Mapper $parameterType = Mapper::param( $utopia, $parameter['validator'], - !$parameter['optional'], + ! $parameter['optional'], $parameter['injections'] ); $params[$name] = [ @@ -118,7 +120,7 @@ class Mapper 'type' => $type, 'description' => $description, 'args' => $params, - 'resolve' => Resolvers::api($utopia, $route) + 'resolve' => Resolvers::api($utopia, $route), ]; if ($list) { @@ -132,7 +134,7 @@ class Mapper /** * Get a type from the registry, creating it if it does not already exist. * - * @param string $name + * @param string $name * @return Type */ public static function model(string $name): Type @@ -151,23 +153,23 @@ class Mapper 'description' => 'Additional data', 'resolve' => static function ($object, $args, $context, $info) { $data = \array_filter( - (array)$object, - fn($key) => !\str_starts_with($key, '_'), + (array) $object, + fn ($key) => ! \str_starts_with($key, '_'), ARRAY_FILTER_USE_KEY ); return \json_encode($data, JSON_FORCE_OBJECT); - } + }, ]; } // If model has no properties, explicitly add a 'status' field // because GraphQL requires at least 1 field per type. - if (!$model->isAny() && empty($model->getRules())) { + if (! $model->isAny() && empty($model->getRules())) { $fields['status'] = [ 'type' => Type::string(), 'description' => 'Status', - 'resolve' => static fn($object, $args, $context, $info) => 'OK', + 'resolve' => static fn ($object, $args, $context, $info) => 'OK', ]; } @@ -189,7 +191,7 @@ class Mapper 'description' => $rule['description'], ]; - if (!$rule['required']) { + if (! $rule['required']) { $fields[$escapedKey]['defaultValue'] = $rule['default']; } } @@ -207,11 +209,12 @@ class Mapper /** * Map a {@see Route} parameter to a GraphQL Type * - * @param App $utopia - * @param Validator|callable $validator - * @param bool $required - * @param array $injections + * @param App $utopia + * @param Validator|callable $validator + * @param bool $required + * @param array $injections * @return Type + * * @throws Exception */ public static function param( @@ -224,7 +227,7 @@ class Mapper ? \call_user_func_array($validator, $utopia->getResources($injections)) : $validator; - switch ((!empty($validator)) ? $validator::class : '') { + switch ((! empty($validator)) ? $validator::class : '') { case 'Appwrite\Network\Validator\CNAME': case 'Appwrite\Task\Validator\Cron': case 'Appwrite\Utopia\Database\Validator\CustomId': @@ -304,10 +307,11 @@ class Mapper /** * Map an {@see Attribute} to a GraphQL Type * - * @param string $type - * @param bool $array - * @param bool $required + * @param string $type + * @param bool $array + * @param bool $required * @return Type + * * @throws Exception */ public static function attribute(string $type, bool $array, bool $required): Type @@ -343,6 +347,7 @@ class Mapper } $complexModel = self::$models[$type]; + return self::model(\ucfirst($complexModel->getType())); } @@ -383,7 +388,7 @@ class Mapper return static::getHashOptionsImplementation($object); } - throw new Exception('Unknown union type: ' . $name); + throw new Exception('Unknown union type: '.$name); } private static function getAttributeImplementation(array $object): Type diff --git a/src/Appwrite/GraphQL/Types/Registry.php b/src/Appwrite/GraphQL/Types/Registry.php index cd40d5c3e4..325766bb67 100644 --- a/src/Appwrite/GraphQL/Types/Registry.php +++ b/src/Appwrite/GraphQL/Types/Registry.php @@ -11,7 +11,7 @@ class Registry /** * Check if a type exists in the registry. * - * @param string $type + * @param string $type * @return bool */ public static function has(string $type): bool @@ -22,7 +22,7 @@ class Registry /** * Get a type from the registry. * - * @param string $type + * @param string $type * @return Type */ public static function get(string $type): Type @@ -33,8 +33,8 @@ class Registry /** * Set a type in the registry. * - * @param string $type - * @param Type $typeObject + * @param string $type + * @param Type $typeObject */ public static function set(string $type, Type $typeObject): void { diff --git a/src/Appwrite/Messaging/Adapter.php b/src/Appwrite/Messaging/Adapter.php index 27dd7f68eb..794fd9b3ed 100644 --- a/src/Appwrite/Messaging/Adapter.php +++ b/src/Appwrite/Messaging/Adapter.php @@ -5,6 +5,8 @@ namespace Appwrite\Messaging; abstract class Adapter { abstract public function subscribe(string $projectId, mixed $identifier, array $roles, array $channels): void; + abstract public function unsubscribe(mixed $identifier): void; + abstract public static function send(string $projectId, array $payload, array $events, array $channels, array $roles, array $options): void; } diff --git a/src/Appwrite/Messaging/Adapter/Realtime.php b/src/Appwrite/Messaging/Adapter/Realtime.php index 33fe484c13..2824f948d7 100644 --- a/src/Appwrite/Messaging/Adapter/Realtime.php +++ b/src/Appwrite/Messaging/Adapter/Realtime.php @@ -2,10 +2,10 @@ namespace Appwrite\Messaging\Adapter; -use Utopia\Database\DateTime; -use Utopia\Database\Document; use Appwrite\Messaging\Adapter; use Utopia\App; +use Utopia\Database\DateTime; +use Utopia\Database\Document; use Utopia\Database\Helpers\ID; use Utopia\Database\Helpers\Role; @@ -39,20 +39,20 @@ class Realtime extends Adapter /** * Adds a subscription. * - * @param string $projectId - * @param mixed $identifier - * @param array $roles - * @param array $channels + * @param string $projectId + * @param mixed $identifier + * @param array $roles + * @param array $channels * @return void */ public function subscribe(string $projectId, mixed $identifier, array $roles, array $channels): void { - if (!isset($this->subscriptions[$projectId])) { // Init Project + if (! isset($this->subscriptions[$projectId])) { // Init Project $this->subscriptions[$projectId] = []; } foreach ($roles as $role) { - if (!isset($this->subscriptions[$projectId][$role])) { // Add user first connection + if (! isset($this->subscriptions[$projectId][$role])) { // Add user first connection $this->subscriptions[$projectId][$role] = []; } @@ -64,14 +64,14 @@ class Realtime extends Adapter $this->connections[$identifier] = [ 'projectId' => $projectId, 'roles' => $roles, - 'channels' => $channels + 'channels' => $channels, ]; } /** * Removes Subscription. * - * @param mixed $connection + * @param mixed $connection * @return void */ public function unsubscribe(mixed $connection): void @@ -102,9 +102,10 @@ class Realtime extends Adapter /** * Checks if Channel has a subscriber. - * @param string $projectId - * @param string $role - * @param string $channel + * + * @param string $projectId + * @param string $role + * @param string $channel * @return bool */ public function hasSubscriber(string $projectId, string $role, string $channel = ''): bool @@ -122,12 +123,13 @@ class Realtime extends Adapter /** * Sends an event to the Realtime Server - * @param string $projectId - * @param array $payload - * @param string $event - * @param array $channels - * @param array $roles - * @param array $options + * + * @param string $projectId + * @param array $payload + * @param string $event + * @param array $channels + * @param array $roles + * @param array $options * @return void */ public static function send(string $projectId, array $payload, array $events, array $channels, array $roles, array $options = []): void @@ -150,8 +152,8 @@ class Realtime extends Adapter 'events' => $events, 'channels' => $channels, 'timestamp' => DateTime::formatTz(DateTime::now()), - 'payload' => $payload - ] + 'payload' => $payload, + ], ])); } @@ -166,11 +168,10 @@ class Realtime extends Adapter * - 110.201 ms (±2.32%) | 100,000 Connections / 1,000,000 Subscriptions * - 1,121.328 ms (±0.84%) | 1,000,000 Connections / 10,000,000 Subscriptions * - * @param array $event + * @param array $event */ public function getSubscribers(array $event) { - $receivers = []; /** * Check if project has subscriber. @@ -212,8 +213,9 @@ class Realtime extends Adapter /** * Converts the channels from the Query Params into an array. * Also renames the account channel to account.USER_ID and removes all illegal account channel variations. - * @param array $channels - * @param string $userId + * + * @param array $channels + * @param string $userId * @return array */ public static function convertChannels(array $channels, string $userId): array @@ -227,8 +229,8 @@ class Realtime extends Adapter break; case $key === 'account': - if (!empty($userId)) { - $channels['account.' . $userId] = $value; + if (! empty($userId)) { + $channels['account.'.$userId] = $value; } break; } @@ -240,9 +242,9 @@ class Realtime extends Adapter /** * Create channels array based on the event name and payload. * - * @param string $event - * @param Document $payload - * @param Document|null $project + * @param string $event + * @param Document $payload + * @param Document|null $project * @return array */ public static function fromPayload(string $event, Document $payload, Document $project = null, Document $database = null, Document $collection = null, Document $bucket = null): array @@ -257,18 +259,18 @@ class Realtime extends Adapter switch ($parts[0]) { case 'users': $channels[] = 'account'; - $channels[] = 'account.' . $parts[1]; + $channels[] = 'account.'.$parts[1]; $roles = [Role::user(ID::custom($parts[1]))->toString()]; break; case 'teams': if ($parts[2] === 'memberships') { $permissionsChanged = $parts[4] ?? false; $channels[] = 'memberships'; - $channels[] = 'memberships.' . $parts[3]; + $channels[] = 'memberships.'.$parts[3]; } else { $permissionsChanged = $parts[2] === 'create'; $channels[] = 'teams'; - $channels[] = 'teams.' . $parts[1]; + $channels[] = 'teams.'.$parts[1]; } $roles = [Role::team(ID::custom($parts[1]))->toString()]; break; @@ -286,8 +288,8 @@ class Realtime extends Adapter } $channels[] = 'documents'; - $channels[] = 'databases.' . $database->getId() . '.collections.' . $payload->getAttribute('$collectionId') . '.documents'; - $channels[] = 'databases.' . $database->getId() . '.collections.' . $payload->getAttribute('$collectionId') . '.documents.' . $payload->getId(); + $channels[] = 'databases.'.$database->getId().'.collections.'.$payload->getAttribute('$collectionId').'.documents'; + $channels[] = 'databases.'.$database->getId().'.collections.'.$payload->getAttribute('$collectionId').'.documents.'.$payload->getId(); $roles = $collection->getAttribute('documentSecurity', false) ? \array_merge($collection->getRead(), $payload->getRead()) @@ -300,8 +302,8 @@ class Realtime extends Adapter throw new \Exception('Bucket needs to be passed to Realtime for File events in the Storage.'); } $channels[] = 'files'; - $channels[] = 'buckets.' . $payload->getAttribute('bucketId') . '.files'; - $channels[] = 'buckets.' . $payload->getAttribute('bucketId') . '.files.' . $payload->getId(); + $channels[] = 'buckets.'.$payload->getAttribute('bucketId').'.files'; + $channels[] = 'buckets.'.$payload->getAttribute('bucketId').'.files.'.$payload->getId(); $roles = $bucket->getAttribute('fileSecurity', false) ? \array_merge($bucket->getRead(), $payload->getRead()) @@ -312,11 +314,11 @@ class Realtime extends Adapter case 'functions': if ($parts[2] === 'executions') { - if (!empty($payload->getRead())) { + if (! empty($payload->getRead())) { $channels[] = 'console'; $channels[] = 'executions'; - $channels[] = 'executions.' . $payload->getId(); - $channels[] = 'functions.' . $payload->getAttribute('functionId'); + $channels[] = 'executions.'.$payload->getId(); + $channels[] = 'functions.'.$payload->getAttribute('functionId'); $roles = $payload->getRead(); } } elseif ($parts[2] === 'deployments') { @@ -332,7 +334,7 @@ class Realtime extends Adapter 'channels' => $channels, 'roles' => $roles, 'permissionsChanged' => $permissionsChanged, - 'projectId' => $projectId + 'projectId' => $projectId, ]; } } diff --git a/src/Appwrite/Migration/Migration.php b/src/Appwrite/Migration/Migration.php index ab394f101f..05cc3f8442 100644 --- a/src/Appwrite/Migration/Migration.php +++ b/src/Appwrite/Migration/Migration.php @@ -2,15 +2,15 @@ namespace Appwrite\Migration; +use Exception; use Swoole\Runtime; -use Utopia\Database\Document; -use Utopia\Database\Database; -use Utopia\Database\Query; +use Utopia\App; use Utopia\CLI\Console; use Utopia\Config\Config; -use Exception; -use Utopia\App; +use Utopia\Database\Database; +use Utopia\Database\Document; use Utopia\Database\Helpers\ID; +use Utopia\Database\Query; use Utopia\Database\Validator\Authorization; Runtime::enableCoroutine(SWOOLE_HOOK_ALL); @@ -65,33 +65,32 @@ abstract class Migration $this->collections = array_merge([ '_metadata' => [ '$id' => ID::custom('_metadata'), - '$collection' => Database::METADATA + '$collection' => Database::METADATA, ], 'audit' => [ '$id' => ID::custom('audit'), - '$collection' => Database::METADATA + '$collection' => Database::METADATA, ], 'abuse' => [ '$id' => ID::custom('abuse'), - '$collection' => Database::METADATA - ] + '$collection' => Database::METADATA, + ], ], Config::getParam('collections', [])); } /** * Set project for migration. * - * @param Document $project - * @param Database $projectDB - * @param Database $oldConsoleDB - * + * @param Document $project + * @param Database $projectDB + * @param Database $oldConsoleDB * @return self */ public function setProject(Document $project, Database $projectDB, Database $consoleDB): self { $this->project = $project; $this->projectDB = $projectDB; - $this->projectDB->setNamespace('_' . $this->project->getId()); + $this->projectDB->setNamespace('_'.$this->project->getId()); $this->consoleDB = $consoleDB; @@ -101,7 +100,7 @@ abstract class Migration /** * Iterates through every document. * - * @param callable $callback + * @param callable $callback */ public function forEachDocument(callable $callback): void { @@ -110,7 +109,7 @@ abstract class Migration continue; } - Console::log('Migrating Collection ' . $collection['$id'] . ':'); + Console::log('Migrating Collection '.$collection['$id'].':'); \Co\run(function (array $collection, callable $callback) { foreach ($this->documentsIterator($collection['$id']) as $document) { @@ -122,14 +121,15 @@ abstract class Migration $old = $document->getArrayCopy(); $new = call_user_func($callback, $document); - if (is_null($new) || !self::hasDifference($new->getArrayCopy(), $old)) { + if (is_null($new) || ! self::hasDifference($new->getArrayCopy(), $old)) { return; } try { $new = $this->projectDB->updateDocument($document->getCollection(), $document->getId(), $document); } catch (\Throwable $th) { - Console::error('Failed to update document: ' . $th->getMessage()); + Console::error('Failed to update document: '.$th->getMessage()); + return; } }, $document, $callback); @@ -141,8 +141,9 @@ abstract class Migration /** * Provides an iterator for all documents on a collection. * - * @param string $collectionId + * @param string $collectionId * @return iterable + * * @throws \Exception */ public function documentsIterator(string $collectionId): iterable @@ -160,7 +161,7 @@ abstract class Migration $count = count($documents); $sum += $count; - Console::log($sum . ' / ' . $collectionCount); + Console::log($sum.' / '.$collectionCount); foreach ($documents as $document) { yield $document; } @@ -170,28 +171,28 @@ abstract class Migration } else { $nextDocument = end($documents); } - } while (!is_null($nextDocument)); + } while (! is_null($nextDocument)); } /** * Checks 2 arrays for differences. * - * @param array $array1 - * @param array $array2 + * @param array $array1 + * @param array $array2 * @return bool */ public static function hasDifference(array $array1, array $array2): bool { foreach ($array1 as $key => $value) { if (is_array($value)) { - if (!isset($array2[$key]) || !is_array($array2[$key])) { + if (! isset($array2[$key]) || ! is_array($array2[$key])) { return true; } else { if (self::hasDifference($value, $array2[$key])) { return true; } } - } elseif (!array_key_exists($key, $array2) || $array2[$key] !== $value) { + } elseif (! array_key_exists($key, $array2) || $array2[$key] !== $value) { return true; } } @@ -202,16 +203,17 @@ abstract class Migration /** * Creates colletion from the config collection. * - * @param string $id - * @param string|null $name + * @param string $id + * @param string|null $name * @return void + * * @throws \Throwable */ protected function createCollection(string $id, string $name = null): void { $name ??= $id; - if (!$this->projectDB->exists(App::getEnv('_APP_DB_SCHEMA', 'appwrite'), $name)) { + if (! $this->projectDB->exists(App::getEnv('_APP_DB_SCHEMA', 'appwrite'), $name)) { $attributes = []; $indexes = []; $collection = $this->collections[$id]; @@ -249,10 +251,11 @@ abstract class Migration /** * Creates attribute from collections.php * - * @param \Utopia\Database\Database $database - * @param string $collectionId - * @param string $attributeId + * @param \Utopia\Database\Database $database + * @param string $collectionId + * @param string $attributeId * @return void + * * @throws \Exception * @throws \Utopia\Database\Exception\Duplicate * @throws \Utopia\Database\Exception\Limit @@ -294,11 +297,12 @@ abstract class Migration /** * Creates index from collections.php * - * @param \Utopia\Database\Database $database - * @param string $collectionId - * @param string $indexId - * @param string|null $from + * @param \Utopia\Database\Database $database + * @param string $collectionId + * @param string $indexId + * @param string|null $from * @return void + * * @throws \Exception * @throws \Utopia\Database\Exception\Duplicate * @throws \Utopia\Database\Exception\Limit diff --git a/src/Appwrite/Migration/Version/V15.php b/src/Appwrite/Migration/Version/V15.php index ac948d01d2..335e0a26c1 100644 --- a/src/Appwrite/Migration/Version/V15.php +++ b/src/Appwrite/Migration/Version/V15.php @@ -4,8 +4,6 @@ namespace Appwrite\Migration\Version; use Appwrite\Migration\Migration; use Appwrite\OpenSSL\OpenSSL; -use Exception; -use PDO; use Utopia\App; use Utopia\CLI\Console; use Utopia\Config\Config; @@ -18,7 +16,7 @@ use Utopia\Database\Helpers\Role; class V15 extends Migration { /** - * @var \PDO $pdo + * @var \PDO */ private $pdo; @@ -38,7 +36,7 @@ class V15 extends Migration $this->providers = \array_merge( ['email', 'anonymous'], \array_map( - fn ($value) => "oauth-" . $value, + fn ($value) => 'oauth-'.$value, \array_keys(Config::getParam('providers', [])) ) ); @@ -54,7 +52,7 @@ class V15 extends Migration ); } - Console::log('Migrating Project: ' . $this->project->getAttribute('name') . ' (' . $this->project->getId() . ')'); + Console::log('Migrating Project: '.$this->project->getAttribute('name').' ('.$this->project->getId().')'); Console::info('Migrating Stats'); $this->migrateStatsMetric('requests', 'project.$all.network.requests'); $this->migrateStatsMetric('network', 'project.$all.network.bandwidth'); @@ -81,6 +79,7 @@ class V15 extends Migration * Migrating all Bucket tables. * * @return void + * * @throws \Exception * @throws \PDOException */ @@ -113,7 +112,7 @@ class V15 extends Migration addCreatePermission: true ); - if (!is_null($bucket->getAttribute('permission'))) { + if (! is_null($bucket->getAttribute('permission'))) { $bucket->setAttribute('fileSecurity', $bucket->getAttribute('permissions') === 'document'); } @@ -157,6 +156,7 @@ class V15 extends Migration * Migrating all Database and Collection tables. * * @return void + * * @throws \Exception * @throws \PDOException */ @@ -234,7 +234,7 @@ class V15 extends Migration addCreatePermission: true ); - if (!is_null($collection->getAttribute('permission'))) { + if (! is_null($collection->getAttribute('permission'))) { $collection->setAttribute('documentSecurity', $collection->getAttribute('permissions') === 'document'); } @@ -254,9 +254,10 @@ class V15 extends Migration $requiredAttributes = array_reduce($collection->getAttribute('attributes', []), function (array $carry, Document $item) { if ($item->getAttribute('required', false)) { $carry = array_merge($carry, [ - $item->getAttribute('key') => $item->getAttribute('default') + $item->getAttribute('key') => $item->getAttribute('default'), ]); } + return $carry; }, []); @@ -294,7 +295,7 @@ class V15 extends Migration /** * Removes all 'write' permissions from a table. * - * @param string $table + * @param string $table * @return void */ protected function removeWritePermissions(string $table): void @@ -309,8 +310,9 @@ class V15 extends Migration /** * Returns all columns from the Table. * - * @param string $table + * @param string $table * @return array + * * @throws \Exception * @throws \PDOException */ @@ -330,6 +332,7 @@ class V15 extends Migration * Migrates all Integer colums for timestamps to DateTime. * * @return void + * * @throws \Exception */ protected function migrateDateTimeAttribute(string $table, string $attribute): void @@ -357,7 +360,7 @@ class V15 extends Migration /** * Skip adding filter on internal attributes. */ - if (!str_starts_with($attribute, '_')) { + if (! str_starts_with($attribute, '_')) { try { /** * Add datetime filter. @@ -383,8 +386,9 @@ class V15 extends Migration /** * Create the '_permissions' column to a table. * - * @param string $table + * @param string $table * @return void + * * @throws \Exception * @throws \PDOException */ @@ -392,7 +396,7 @@ class V15 extends Migration { $columns = $this->getSQLColumnTypes($table); - if (!array_key_exists('_permissions', $columns)) { + if (! array_key_exists('_permissions', $columns)) { try { $this->pdo->prepare("ALTER TABLE IF EXISTS `{$this->projectDB->getDefaultDatabase()}`.`_{$this->project->getInternalId()}_{$table}` ADD `_permissions` MEDIUMTEXT DEFAULT NULL")->execute(); } catch (\Throwable $th) { @@ -404,10 +408,11 @@ class V15 extends Migration /** * Populate '$permissions' from '$read' and '$write'. * - * @param \Utopia\Database\Document $document - * @param null|string $table - * @param bool $addCreatePermission + * @param \Utopia\Database\Document $document + * @param null|string $table + * @param bool $addCreatePermission * @return void + * * @throws \Exception * @throws \PDOException */ @@ -448,7 +453,7 @@ class V15 extends Migration /** * Migrates a permission string * - * @param string $permission + * @param string $permission * @return string */ protected function migratePermission(string $permission): string @@ -735,7 +740,7 @@ class V15 extends Migration foreach ($this->documentsIterator($id) as $function) { $vars = $function->getAttribute('vars', []); - if (!is_array($vars)) { + if (! is_array($vars)) { continue; } @@ -756,7 +761,7 @@ class V15 extends Migration 'functionInternalId' => $function->getInternalId(), 'key' => (string) $key, 'value' => (string) $value, - 'search' => implode(' ', [$variableId, $key, $function->getId()]) + 'search' => implode(' ', [$variableId, $key, $function->getId()]), ]); $this->projectDB->createDocument('variables', $variable); } @@ -1228,7 +1233,7 @@ class V15 extends Migration /** * Fix run on each document * - * @param \Utopia\Database\Document $document + * @param \Utopia\Database\Document $document * @return \Utopia\Database\Document */ protected function fixDocument(Document $document) @@ -1479,14 +1484,14 @@ class V15 extends Migration $this->pdo->prepare("UPDATE `{$this->projectDB->getDefaultDatabase()}`.`_{$this->project->getInternalId()}_stats` SET metric = {$to} WHERE metric = {$from}")->execute(); } catch (\Throwable $th) { - Console::warning("Migrating steps from {$this->projectDB->getDefaultDatabase()}`.`_{$this->project->getInternalId()}_stats:" . $th->getMessage()); + Console::warning("Migrating steps from {$this->projectDB->getDefaultDatabase()}`.`_{$this->project->getInternalId()}_stats:".$th->getMessage()); } } /** * Filter from the 'encrypt' filter. * - * @param string $value + * @param string $value * @return string|false */ protected function encryptFilter(string $value): string diff --git a/src/Appwrite/Migration/Version/V16.php b/src/Appwrite/Migration/Version/V16.php index 1d56b246d6..4e23a8d111 100644 --- a/src/Appwrite/Migration/Version/V16.php +++ b/src/Appwrite/Migration/Version/V16.php @@ -24,7 +24,7 @@ class V16 extends Migration ); } - Console::log('Migrating Project: ' . $this->project->getAttribute('name') . ' (' . $this->project->getId() . ')'); + Console::log('Migrating Project: '.$this->project->getAttribute('name').' ('.$this->project->getId().')'); Console::info('Migrating Collections'); $this->migrateCollections(); @@ -102,7 +102,7 @@ class V16 extends Migration /** * Fix run on each document * - * @param \Utopia\Database\Document $document + * @param \Utopia\Database\Document $document * @return \Utopia\Database\Document */ protected function fixDocument(Document $document) @@ -118,7 +118,7 @@ class V16 extends Migration * Set default authDuration */ $document->setAttribute('auths', array_merge($document->getAttribute('auths', []), [ - 'duration' => Auth::TOKEN_EXPIRATION_LOGIN_LONG + 'duration' => Auth::TOKEN_EXPIRATION_LOGIN_LONG, ])); /** @@ -127,16 +127,16 @@ class V16 extends Migration $authProviders = $document->getAttribute('authProviders', []); foreach (Config::getParam('providers') as $provider => $value) { - if (!$value['enabled']) { + if (! $value['enabled']) { continue; } - if (($authProviders[$provider . 'Appid'] ?? false) && ($authProviders[$provider . 'Secret'] ?? false)) { - if (array_key_exists($provider . 'Enabled', $authProviders)) { + if (($authProviders[$provider.'Appid'] ?? false) && ($authProviders[$provider.'Secret'] ?? false)) { + if (array_key_exists($provider.'Enabled', $authProviders)) { continue; } - $authProviders[$provider . 'Enabled'] = true; + $authProviders[$provider.'Enabled'] = true; } } diff --git a/src/Appwrite/Migration/Version/V17.php b/src/Appwrite/Migration/Version/V17.php index 9a33d424bc..3c04306f00 100644 --- a/src/Appwrite/Migration/Version/V17.php +++ b/src/Appwrite/Migration/Version/V17.php @@ -23,7 +23,7 @@ class V17 extends Migration ); } - Console::log('Migrating Project: ' . $this->project->getAttribute('name') . ' (' . $this->project->getId() . ')'); + Console::log('Migrating Project: '.$this->project->getAttribute('name').' ('.$this->project->getId().')'); Console::info('Migrating Collections'); $this->migrateCollections(); @@ -33,11 +33,11 @@ class V17 extends Migration $this->forEachDocument([$this, 'fixDocument']); } - /** * Migrating all Bucket tables. * * @return void + * * @throws \Exception * @throws \PDOException */ @@ -81,7 +81,7 @@ class V17 extends Migration /** * Fix run on each document * - * @param \Utopia\Database\Document $document + * @param \Utopia\Database\Document $document * @return \Utopia\Database\Document */ protected function fixDocument(Document $document) @@ -97,15 +97,15 @@ class V17 extends Migration * Set default maxSessions */ $document->setAttribute('auths', array_merge($document->getAttribute('auths', []), [ - 'maxSessions' => APP_LIMIT_USER_SESSIONS_DEFAULT + 'maxSessions' => APP_LIMIT_USER_SESSIONS_DEFAULT, ])); break; case 'users': - /** + /** * Set hashOptions type */ $document->setAttribute('hashOptions', array_merge($document->getAttribute('hashOptions', []), [ - 'type' => $document->getAttribute('hash', Auth::DEFAULT_ALGO) + 'type' => $document->getAttribute('hash', Auth::DEFAULT_ALGO), ])); break; } diff --git a/src/Appwrite/Network/Validator/CNAME.php b/src/Appwrite/Network/Validator/CNAME.php index 678a57cecd..3840322137 100644 --- a/src/Appwrite/Network/Validator/CNAME.php +++ b/src/Appwrite/Network/Validator/CNAME.php @@ -12,7 +12,7 @@ class CNAME extends Validator protected $target; /** - * @param string $target + * @param string $target */ public function __construct($target) { @@ -30,13 +30,12 @@ class CNAME extends Validator /** * Check if CNAME record target value matches selected target * - * @param mixed $domain - * + * @param mixed $domain * @return bool */ public function isValid($domain): bool { - if (!is_string($domain)) { + if (! is_string($domain)) { return false; } @@ -46,7 +45,7 @@ class CNAME extends Validator return false; } - if (!$records) { + if (! $records) { return false; } diff --git a/src/Appwrite/Network/Validator/Email.php b/src/Appwrite/Network/Validator/Email.php index efc1a5d5b3..232437aab7 100644 --- a/src/Appwrite/Network/Validator/Email.php +++ b/src/Appwrite/Network/Validator/Email.php @@ -8,8 +8,6 @@ use Utopia\Validator; * Email * * Validate that an variable is a valid email address - * - * @package Utopia\Validator */ class Email extends Validator { @@ -30,12 +28,12 @@ class Email extends Validator * * Validation will pass when $value is valid email address. * - * @param mixed $value + * @param mixed $value * @return bool */ public function isValid($value): bool { - if (!\filter_var($value, FILTER_VALIDATE_EMAIL)) { + if (! \filter_var($value, FILTER_VALIDATE_EMAIL)) { return false; } diff --git a/src/Appwrite/Network/Validator/Origin.php b/src/Appwrite/Network/Validator/Origin.php index 508961ab9e..78065c0e48 100644 --- a/src/Appwrite/Network/Validator/Origin.php +++ b/src/Appwrite/Network/Validator/Origin.php @@ -2,35 +2,55 @@ namespace Appwrite\Network\Validator; -use Utopia\Validator\Hostname; use Utopia\Validator; +use Utopia\Validator\Hostname; class Origin extends Validator { public const CLIENT_TYPE_UNKNOWN = 'unknown'; + public const CLIENT_TYPE_WEB = 'web'; + public const CLIENT_TYPE_FLUTTER_IOS = 'flutter-ios'; + public const CLIENT_TYPE_FLUTTER_ANDROID = 'flutter-android'; + public const CLIENT_TYPE_FLUTTER_MACOS = 'flutter-macos'; + public const CLIENT_TYPE_FLUTTER_WINDOWS = 'flutter-windows'; + public const CLIENT_TYPE_FLUTTER_LINUX = 'flutter-linux'; + public const CLIENT_TYPE_FLUTTER_WEB = 'flutter-web'; + public const CLIENT_TYPE_APPLE_IOS = 'apple-ios'; + public const CLIENT_TYPE_APPLE_MACOS = 'apple-macos'; + public const CLIENT_TYPE_APPLE_WATCHOS = 'apple-watchos'; + public const CLIENT_TYPE_APPLE_TVOS = 'apple-tvos'; + public const CLIENT_TYPE_ANDROID = 'android'; + public const CLIENT_TYPE_UNITY = 'unity'; - public const SCHEME_TYPE_HTTP = 'http'; + public const SCHEME_TYPE_HTTPS = 'https'; + public const SCHEME_TYPE_IOS = 'appwrite-ios'; + public const SCHEME_TYPE_MACOS = 'appwrite-macos'; + public const SCHEME_TYPE_WATCHOS = 'appwrite-watchos'; + public const SCHEME_TYPE_TVOS = 'appwrite-tvos'; + public const SCHEME_TYPE_ANDROID = 'appwrite-android'; + public const SCHEME_TYPE_WINDOWS = 'appwrite-windows'; + public const SCHEME_TYPE_LINUX = 'appwrite-linux'; /** @@ -65,7 +85,7 @@ class Origin extends Validator protected $host = ''; /** - * @param string $target + * @param string $target */ public function __construct($platforms) { @@ -92,7 +112,7 @@ class Origin extends Validator break; default: - # code... + // code... break; } } @@ -100,25 +120,24 @@ class Origin extends Validator public function getDescription(): string { - if (!\array_key_exists($this->client, $this->platforms)) { + if (! \array_key_exists($this->client, $this->platforms)) { return 'Unsupported platform'; } - return 'Invalid Origin. Register your new client (' . $this->host . ') as a new ' - . $this->platforms[$this->client] . ' platform on your project console dashboard'; + return 'Invalid Origin. Register your new client ('.$this->host.') as a new ' + .$this->platforms[$this->client].' platform on your project console dashboard'; } /** * Check if Origin has been allowed * for access to the API * - * @param mixed $origin - * + * @param mixed $origin * @return bool */ public function isValid($origin): bool { - if (!is_string($origin)) { + if (! is_string($origin)) { return false; } diff --git a/src/Appwrite/OpenSSL/OpenSSL.php b/src/Appwrite/OpenSSL/OpenSSL.php index 1965a3c858..2eed67dd3e 100644 --- a/src/Appwrite/OpenSSL/OpenSSL.php +++ b/src/Appwrite/OpenSSL/OpenSSL.php @@ -10,12 +10,11 @@ class OpenSSL * @param $data * @param $method * @param $key - * @param int $options - * @param string $iv - * @param null $tag - * @param string $aad - * @param int $tag_length - * + * @param int $options + * @param string $iv + * @param null $tag + * @param string $aad + * @param int $tag_length * @return string */ public static function encrypt($data, $method, $key, $options = 0, $iv = '', &$tag = null, $aad = '', $tag_length = 16) @@ -27,11 +26,10 @@ class OpenSSL * @param $data * @param $method * @param $password - * @param int $options - * @param string $iv - * @param string $tag - * @param string $aad - * + * @param int $options + * @param string $iv + * @param string $tag + * @param string $aad * @return string */ public static function decrypt($data, $method, $password, $options = 1, $iv = '', $tag = '', $aad = '') @@ -40,8 +38,7 @@ class OpenSSL } /** - * @param string $method - * + * @param string $method * @return int */ public static function cipherIVLength($method) @@ -51,8 +48,7 @@ class OpenSSL /** * @param $length - * @param null $crypto_strong - * + * @param null $crypto_strong * @return false|string */ public static function randomPseudoBytes($length, &$crypto_strong = null) diff --git a/src/Appwrite/Promises/Promise.php b/src/Appwrite/Promises/Promise.php index a6b1aa79d5..95e4c7bc69 100644 --- a/src/Appwrite/Promises/Promise.php +++ b/src/Appwrite/Promises/Promise.php @@ -5,7 +5,9 @@ namespace Appwrite\Promises; abstract class Promise { protected const STATE_PENDING = 1; + protected const STATE_FULFILLED = 0; + protected const STATE_REJECTED = -1; protected int $state = self::STATE_PENDING; @@ -37,7 +39,7 @@ abstract class Promise /** * Create a new promise from the given callable. * - * @param callable $promise + * @param callable $promise * @return self */ public static function create(callable $promise): self @@ -48,7 +50,7 @@ abstract class Promise /** * Resolve promise with given value. * - * @param mixed $value + * @param mixed $value * @return self */ public static function resolve(mixed $value): self @@ -61,7 +63,7 @@ abstract class Promise /** * Rejects the promise with the given reason. * - * @param mixed $value + * @param mixed $value * @return self */ public static function reject(mixed $value): self @@ -74,7 +76,7 @@ abstract class Promise /** * Catch any exception thrown by the executor. * - * @param callable $onRejected + * @param callable $onRejected * @return self */ public function catch(callable $onRejected): self @@ -85,8 +87,8 @@ abstract class Promise /** * Execute the promise. * - * @param callable|null $onFulfilled - * @param callable|null $onRejected + * @param callable|null $onFulfilled + * @param callable|null $onRejected * @return self */ public function then( @@ -99,13 +101,15 @@ abstract class Promise if ($this->isFulfilled() && $onFulfilled === null) { return $this; } + return self::create(function (callable $resolve, callable $reject) use ($onFulfilled, $onRejected) { while ($this->isPending()) { usleep(25000); } $callable = $this->isFulfilled() ? $onFulfilled : $onRejected; - if (!\is_callable($callable)) { + if (! \is_callable($callable)) { $resolve($this->result); + return; } try { @@ -119,7 +123,7 @@ abstract class Promise /** * Returns a promise that completes when all passed in promises complete. * - * @param iterable|self[] $promises + * @param iterable|self[] $promises * @return self */ abstract public static function all(iterable $promises): self; @@ -127,13 +131,14 @@ abstract class Promise /** * Set resolved result * - * @param mixed $value + * @param mixed $value * @return void */ protected function setResult(mixed $value): void { - if (!\is_callable([$value, 'then'])) { + if (! \is_callable([$value, 'then'])) { $this->result = $value; + return; } @@ -146,7 +151,7 @@ abstract class Promise $value->then($callable, $callable); - while (!$resolved) { + while (! $resolved) { usleep(25000); } } @@ -154,7 +159,7 @@ abstract class Promise /** * Change promise state * - * @param integer $state + * @param int $state * @return void */ protected function setState(int $state): void @@ -165,7 +170,7 @@ abstract class Promise /** * Promise is pending * - * @return boolean + * @return bool */ protected function isPending(): bool { @@ -175,7 +180,7 @@ abstract class Promise /** * Promise is fulfilled * - * @return boolean + * @return bool */ protected function isFulfilled(): bool { @@ -185,7 +190,7 @@ abstract class Promise /** * Promise is rejected * - * @return boolean + * @return bool */ protected function isRejected(): bool { diff --git a/src/Appwrite/Promises/Swoole.php b/src/Appwrite/Promises/Swoole.php index c258ef6a5e..4867ed6c96 100644 --- a/src/Appwrite/Promises/Swoole.php +++ b/src/Appwrite/Promises/Swoole.php @@ -28,7 +28,7 @@ class Swoole extends Promise /** * Returns a promise that completes when all passed in promises complete. * - * @param iterable|Swoole[] $promises + * @param iterable|Swoole[] $promises * @return Promise */ public static function all(iterable $promises): Promise @@ -45,6 +45,7 @@ class Swoole extends Promise $promise->then(function ($value) use ($key, &$result, $channel) { $result[$key] = $value; $channel->push(true); + return $value; }, function ($err) use ($channel, &$error) { $channel->push(true); @@ -61,6 +62,7 @@ class Swoole extends Promise if ($error !== null) { $reject($error); + return; } diff --git a/src/Appwrite/Resque/Worker.php b/src/Appwrite/Resque/Worker.php index d7052379ff..1af47e6896 100644 --- a/src/Appwrite/Resque/Worker.php +++ b/src/Appwrite/Resque/Worker.php @@ -40,11 +40,12 @@ abstract class Worker * Function for identifying the worker needs to be set to unique name * * @return string + * * @throws Exception */ public function getName(): string { - throw new Exception("Please implement getName method in worker"); + throw new Exception('Please implement getName method in worker'); } /** @@ -52,11 +53,12 @@ abstract class Worker * Can include any preparations, such as connecting to external services or loading files * * @return void + * * @throws \Exception|\Throwable */ public function init(): void { - throw new Exception("Please implement init method in worker"); + throw new Exception('Please implement init method in worker'); } /** @@ -64,11 +66,12 @@ abstract class Worker * You can access $args here, it will contain event information * * @return void + * * @throws \Exception|\Throwable */ public function run(): void { - throw new Exception("Please implement run method in worker"); + throw new Exception('Please implement run method in worker'); } /** @@ -76,20 +79,23 @@ abstract class Worker * You can do cleanup here, such as disconnecting from services or removing temp files * * @return void + * * @throws \Exception|\Throwable */ public function shutdown(): void { - throw new Exception("Please implement shutdown method in worker"); + throw new Exception('Please implement shutdown method in worker'); } public const DATABASE_PROJECT = 'project'; + public const DATABASE_CONSOLE = 'console'; /** * A wrapper around 'init' function with non-worker-specific code * * @return void + * * @throws \Exception|\Throwable */ public function setUp(): void @@ -98,7 +104,7 @@ abstract class Worker $this->init(); } catch (\Throwable $error) { foreach (self::$errorCallbacks as $errorCallback) { - $errorCallback($error, "init", $this->getName()); + $errorCallback($error, 'init', $this->getName()); } throw $error; @@ -109,6 +115,7 @@ abstract class Worker * A wrapper around 'run' function with non-worker-specific code * * @return void + * * @throws \Exception|\Throwable */ public function perform(): void @@ -122,7 +129,7 @@ abstract class Worker $this->run(); } catch (\Throwable $error) { foreach (self::$errorCallbacks as $errorCallback) { - $errorCallback($error, "run", $this->getName(), $this->args); + $errorCallback($error, 'run', $this->getName(), $this->args); } throw $error; @@ -133,6 +140,7 @@ abstract class Worker * A wrapper around 'shutdown' function with non-worker-specific code * * @return void + * * @throws \Exception|\Throwable */ public function tearDown(): void @@ -141,17 +149,17 @@ abstract class Worker $this->shutdown(); } catch (\Throwable $error) { foreach (self::$errorCallbacks as $errorCallback) { - $errorCallback($error, "shutdown", $this->getName()); + $errorCallback($error, 'shutdown', $this->getName()); } throw $error; } } - /** * Register callback. Will be executed when error occurs. - * @param callable $callback + * + * @param callable $callback * @return void */ public static function error(callable $callback): void @@ -161,8 +169,10 @@ abstract class Worker /** * Get internal project database - * @param string $projectId + * + * @param string $projectId * @return Database + * * @throws Exception */ protected function getProjectDB(string $projectId, ?Document $project = null): Database @@ -175,7 +185,7 @@ abstract class Worker } /** @var Document $project */ - $project = Authorization::skip(fn() => $consoleDB->getDocument('projects', $projectId)); + $project = Authorization::skip(fn () => $consoleDB->getDocument('projects', $projectId)); } return $this->getDB(self::DATABASE_PROJECT, $projectId, $project->getInternalId(), $project); @@ -183,7 +193,9 @@ abstract class Worker /** * Get console database + * * @return Database + * * @throws Exception */ protected function getConsoleDB(): Database @@ -193,11 +205,13 @@ abstract class Worker /** * Get database - * @param string $type One of (project, console) - * @param string $projectId of project or console DB - * @param string $projectInternalId - * @param Document|null $project + * + * @param string $type One of (project, console) + * @param string $projectId of project or console DB + * @param string $projectInternalId + * @param Document|null $project * @return Database + * * @throws Exception */ private function getDB( @@ -217,17 +231,17 @@ abstract class Worker switch ($type) { case self::DATABASE_PROJECT: - if (!$projectId) { + if (! $projectId) { throw new \Exception('ProjectID not provided - cannot get database'); } $namespace = "_$projectInternalId"; break; case self::DATABASE_CONSOLE: - $namespace = "_console"; + $namespace = '_console'; $sleep = 5; // ConsoleDB needs extra sleep time to ensure tables are created break; default: - throw new \Exception('Unknown database type: ' . $type); + throw new \Exception('Unknown database type: '.$type); } $attempts = 0; @@ -242,13 +256,13 @@ abstract class Worker if ( $project === null - && !empty($projectId) - && !$database->getDocument('projects', $projectId)->isEmpty() + && ! empty($projectId) + && ! $database->getDocument('projects', $projectId)->isEmpty() ) { throw new \Exception("Project does not exist: $projectId"); } - if ($type === self::DATABASE_CONSOLE && !$database->exists($database->getDefaultDatabase(), Database::METADATA)) { + if ($type === self::DATABASE_CONSOLE && ! $database->exists($database->getDefaultDatabase(), Database::METADATA)) { throw new \Exception('Console project not ready'); } @@ -256,7 +270,7 @@ abstract class Worker } catch (\Exception $e) { Console::warning("Database not ready. Retrying connection ($attempts)..."); if ($attempts >= DATABASE_RECONNECT_MAX_ATTEMPTS) { - throw new \Exception('Failed to connect to database: ' . $e->getMessage()); + throw new \Exception('Failed to connect to database: '.$e->getMessage()); } sleep($sleep); } @@ -267,43 +281,46 @@ abstract class Worker /** * Get Functions Storage Device - * @param string $projectId of the project + * + * @param string $projectId of the project * @return Device */ protected function getFunctionsDevice(string $projectId): Device { - return $this->getDevice(APP_STORAGE_FUNCTIONS . '/app-' . $projectId); + return $this->getDevice(APP_STORAGE_FUNCTIONS.'/app-'.$projectId); } /** * Get Files Storage Device - * @param string $projectId of the project + * + * @param string $projectId of the project * @return Device */ protected function getFilesDevice(string $projectId): Device { - return $this->getDevice(APP_STORAGE_UPLOADS . '/app-' . $projectId); + return $this->getDevice(APP_STORAGE_UPLOADS.'/app-'.$projectId); } - /** * Get Builds Storage Device - * @param string $projectId of the project + * + * @param string $projectId of the project * @return Device */ protected function getBuildsDevice(string $projectId): Device { - return $this->getDevice(APP_STORAGE_BUILDS . '/app-' . $projectId); + return $this->getDevice(APP_STORAGE_BUILDS.'/app-'.$projectId); } protected function getCacheDevice(string $projectId): Device { - return $this->getDevice(APP_STORAGE_CACHE . '/app-' . $projectId); + return $this->getDevice(APP_STORAGE_CACHE.'/app-'.$projectId); } /** * Get Device based on selected storage environment - * @param string $root path of the device + * + * @param string $root path of the device * @return Device */ public function getDevice(string $root): Device @@ -318,6 +335,7 @@ abstract class Worker $s3Region = App::getEnv('_APP_STORAGE_S3_REGION', ''); $s3Bucket = App::getEnv('_APP_STORAGE_S3_BUCKET', ''); $s3Acl = 'private'; + return new S3($root, $s3AccessKey, $s3SecretKey, $s3Bucket, $s3Region, $s3Acl); case Storage::DEVICE_DO_SPACES: $doSpacesAccessKey = App::getEnv('_APP_STORAGE_DO_SPACES_ACCESS_KEY', ''); @@ -325,6 +343,7 @@ abstract class Worker $doSpacesRegion = App::getEnv('_APP_STORAGE_DO_SPACES_REGION', ''); $doSpacesBucket = App::getEnv('_APP_STORAGE_DO_SPACES_BUCKET', ''); $doSpacesAcl = 'private'; + return new DOSpaces($root, $doSpacesAccessKey, $doSpacesSecretKey, $doSpacesBucket, $doSpacesRegion, $doSpacesAcl); case Storage::DEVICE_BACKBLAZE: $backblazeAccessKey = App::getEnv('_APP_STORAGE_BACKBLAZE_ACCESS_KEY', ''); @@ -332,6 +351,7 @@ abstract class Worker $backblazeRegion = App::getEnv('_APP_STORAGE_BACKBLAZE_REGION', ''); $backblazeBucket = App::getEnv('_APP_STORAGE_BACKBLAZE_BUCKET', ''); $backblazeAcl = 'private'; + return new Backblaze($root, $backblazeAccessKey, $backblazeSecretKey, $backblazeBucket, $backblazeRegion, $backblazeAcl); case Storage::DEVICE_LINODE: $linodeAccessKey = App::getEnv('_APP_STORAGE_LINODE_ACCESS_KEY', ''); @@ -339,6 +359,7 @@ abstract class Worker $linodeRegion = App::getEnv('_APP_STORAGE_LINODE_REGION', ''); $linodeBucket = App::getEnv('_APP_STORAGE_LINODE_BUCKET', ''); $linodeAcl = 'private'; + return new Linode($root, $linodeAccessKey, $linodeSecretKey, $linodeBucket, $linodeRegion, $linodeAcl); case Storage::DEVICE_WASABI: $wasabiAccessKey = App::getEnv('_APP_STORAGE_WASABI_ACCESS_KEY', ''); @@ -346,6 +367,7 @@ abstract class Worker $wasabiRegion = App::getEnv('_APP_STORAGE_WASABI_REGION', ''); $wasabiBucket = App::getEnv('_APP_STORAGE_WASABI_BUCKET', ''); $wasabiAcl = 'private'; + return new Wasabi($root, $wasabiAccessKey, $wasabiSecretKey, $wasabiBucket, $wasabiRegion, $wasabiAcl); } } diff --git a/src/Appwrite/Specification/Format.php b/src/Appwrite/Specification/Format.php index 91120e74c6..cac255d76e 100644 --- a/src/Appwrite/Specification/Format.php +++ b/src/Appwrite/Specification/Format.php @@ -2,9 +2,9 @@ namespace Appwrite\Specification; +use Appwrite\Utopia\Response\Model; use Utopia\App; use Utopia\Route; -use Appwrite\Utopia\Response\Model; abstract class Format { @@ -21,8 +21,11 @@ abstract class Format protected array $models; protected array $services; + protected array $keys; + protected int $authCount; + protected array $params = [ 'name' => '', 'description' => '', @@ -71,9 +74,8 @@ abstract class Format * * Set param value * - * @param string $key - * @param string $value - * + * @param string $key + * @param string $value * @return self */ public function setParam(string $key, string $value): self @@ -88,9 +90,8 @@ abstract class Format * * Get param value * - * @param string $key - * @param string $default - * + * @param string $key + * @param string $default * @return string */ public function getParam(string $key, string $default = ''): string diff --git a/src/Appwrite/Specification/Format/OpenAPI3.php b/src/Appwrite/Specification/Format/OpenAPI3.php index 0e4cef5fb3..a236f19ccf 100644 --- a/src/Appwrite/Specification/Format/OpenAPI3.php +++ b/src/Appwrite/Specification/Format/OpenAPI3.php @@ -19,30 +19,32 @@ class OpenAPI3 extends Format protected function getNestedModels(Model $model, array &$usedModels): void { foreach ($model->getRules() as $rule) { - if (!in_array($model->getType(), $usedModels)) { + if (! in_array($model->getType(), $usedModels)) { continue; } if (\is_array($rule['type'])) { foreach ($rule['type'] as $ruleType) { - if (!in_array($ruleType, ['string', 'integer', 'boolean', 'json', 'float', 'double'])) { + if (! in_array($ruleType, ['string', 'integer', 'boolean', 'json', 'float', 'double'])) { $usedModels[] = $ruleType; foreach ($this->models as $m) { if ($m->getType() === $ruleType) { $this->getNestedModels($m, $usedModels); + continue; } } } } } else { - if (!in_array($rule['type'], ['string', 'integer', 'boolean', 'json', 'float', 'double'])) { + if (! in_array($rule['type'], ['string', 'integer', 'boolean', 'json', 'float', 'double'])) { $usedModels[] = $rule['type']; foreach ($this->models as $m) { if ($m->getType() === $rule['type']) { $this->getNestedModels($m, $usedModels); + continue; } } @@ -124,7 +126,7 @@ class OpenAPI3 extends Format } $id = $route->getLabel('sdk.method', \uniqid()); - $desc = (!empty($route->getLabel('sdk.description', ''))) ? \realpath(__DIR__ . '/../../../../' . $route->getLabel('sdk.description', '')) : null; + $desc = (! empty($route->getLabel('sdk.description', ''))) ? \realpath(__DIR__.'/../../../../'.$route->getLabel('sdk.description', '')) : null; $produces = $route->getLabel('sdk.response.type', null); $model = $route->getLabel('sdk.response.model', 'none'); $routeSecurity = $route->getLabel('sdk.auth', []); @@ -153,7 +155,7 @@ class OpenAPI3 extends Format $temp = [ 'summary' => $route->getDesc(), - 'operationId' => $route->getLabel('sdk.namespace', 'default') . ucfirst($id), + 'operationId' => $route->getLabel('sdk.namespace', 'default').ucfirst($id), 'tags' => [$route->getLabel('sdk.namespace', 'default')], 'description' => ($desc) ? \file_get_contents($desc) : '', 'responses' => [], @@ -162,8 +164,8 @@ class OpenAPI3 extends Format 'weight' => $route->getOrder(), 'cookies' => $route->getLabel('sdk.cookies', false), 'type' => $route->getLabel('sdk.methodType', ''), - 'demo' => Template::fromCamelCaseToDash($route->getLabel('sdk.namespace', 'default')) . '/' . Template::fromCamelCaseToDash($id) . '.md', - 'edit' => 'https://github.com/appwrite/appwrite/edit/master' . $route->getLabel('sdk.description', ''), + 'demo' => Template::fromCamelCaseToDash($route->getLabel('sdk.namespace', 'default')).'/'.Template::fromCamelCaseToDash($id).'.md', + 'edit' => 'https://github.com/appwrite/appwrite/edit/master'.$route->getLabel('sdk.description', ''), 'rate-limit' => $route->getLabel('abuse-limit', 0), 'rate-time' => $route->getLabel('abuse-time', 3600), 'rate-key' => $route->getLabel('abuse-key', 'url:{url},ip:{ip}'), @@ -187,8 +189,8 @@ class OpenAPI3 extends Format } } - if (!(\is_array($model)) && $model->isNone()) { - $temp['responses'][(string)$route->getLabel('sdk.response.code', '500')] = [ + if (! (\is_array($model)) && $model->isNone()) { + $temp['responses'][(string) $route->getLabel('sdk.response.code', '500')] = [ 'description' => in_array($produces, [ 'image/*', 'image/jpeg', @@ -202,19 +204,19 @@ class OpenAPI3 extends Format ]; } else { if (\is_array($model)) { - $modelDescription = \join(', or ', \array_map(fn ($m) => $m->getName(), $model)); + $modelDescription = \implode(', or ', \array_map(fn ($m) => $m->getName(), $model)); // model has multiple possible responses, we will use oneOf foreach ($model as $m) { $usedModels[] = $m->getType(); } - $temp['responses'][(string)$route->getLabel('sdk.response.code', '500')] = [ + $temp['responses'][(string) $route->getLabel('sdk.response.code', '500')] = [ 'description' => $modelDescription, 'content' => [ $produces => [ 'schema' => [ - 'oneOf' => \array_map(fn ($m) => ['$ref' => '#/components/schemas/' . $m->getType()], $model) + 'oneOf' => \array_map(fn ($m) => ['$ref' => '#/components/schemas/'.$m->getType()], $model), ], ], ], @@ -222,12 +224,12 @@ class OpenAPI3 extends Format } else { // Response definition using one type $usedModels[] = $model->getType(); - $temp['responses'][(string)$route->getLabel('sdk.response.code', '500')] = [ + $temp['responses'][(string) $route->getLabel('sdk.response.code', '500')] = [ 'description' => $model->getName(), 'content' => [ $produces => [ 'schema' => [ - '$ref' => '#/components/schemas/' . $model->getType(), + '$ref' => '#/components/schemas/'.$model->getType(), ], ], ], @@ -236,11 +238,11 @@ class OpenAPI3 extends Format } if ($route->getLabel('sdk.response.code', 500) === 204) { - $temp['responses'][(string)$route->getLabel('sdk.response.code', '500')]['description'] = 'No content'; - unset($temp['responses'][(string)$route->getLabel('sdk.response.code', '500')]['schema']); + $temp['responses'][(string) $route->getLabel('sdk.response.code', '500')]['description'] = 'No content'; + unset($temp['responses'][(string) $route->getLabel('sdk.response.code', '500')]['schema']); } - if ((!empty($scope))) { // && 'public' != $scope + if ((! empty($scope))) { // && 'public' != $scope $securities = ['Project' => []]; foreach ($route->getLabel('sdk.auth', []) as $security) { @@ -255,8 +257,8 @@ class OpenAPI3 extends Format $body = [ 'content' => [ - $consumes[0] => [ - 'schema' => [ + $consumes[0] => [ + 'schema' => [ 'type' => 'object', 'properties' => [], ], @@ -275,7 +277,7 @@ class OpenAPI3 extends Format $node = [ 'name' => $name, 'description' => $param['description'], - 'required' => !$param['optional'], + 'required' => ! $param['optional'], ]; foreach ($this->services as $service) { @@ -284,10 +286,10 @@ class OpenAPI3 extends Format } } - switch ((!empty($validator)) ? \get_class($validator) : '') { + switch ((! empty($validator)) ? \get_class($validator) : '') { case 'Utopia\Validator\Text': $node['schema']['type'] = $validator->getType(); - $node['schema']['x-example'] = '[' . \strtoupper(Template::fromCamelCaseToSnake($node['name'])) . ']'; + $node['schema']['x-example'] = '['.\strtoupper(Template::fromCamelCaseToSnake($node['name'])).']'; break; case 'Utopia\Validator\Boolean': $node['schema']['type'] = $validator->getType(); @@ -295,14 +297,14 @@ class OpenAPI3 extends Format break; case 'Utopia\Database\Validator\UID': $node['schema']['type'] = $validator->getType(); - $node['schema']['x-example'] = '[' . \strtoupper(Template::fromCamelCaseToSnake($node['name'])) . ']'; + $node['schema']['x-example'] = '['.\strtoupper(Template::fromCamelCaseToSnake($node['name'])).']'; break; case 'Appwrite\Utopia\Database\Validator\CustomId': if ($route->getLabel('sdk.methodType', '') === 'upload') { $node['schema']['x-upload-id'] = true; } $node['schema']['type'] = $validator->getType(); - $node['schema']['x-example'] = '[' . \strtoupper(Template::fromCamelCaseToSnake($node['name'])) . ']'; + $node['schema']['x-example'] = '['.\strtoupper(Template::fromCamelCaseToSnake($node['name'])).']'; break; case 'Utopia\Database\Validator\DatetimeValidator': $node['schema']['type'] = $validator->getType(); @@ -357,14 +359,14 @@ class OpenAPI3 extends Format $node['schema']['items'] = [ 'type' => 'string', ]; - $node['schema']['x-example'] = '["' . Permission::read(Role::any()) . '"]'; + $node['schema']['x-example'] = '["'.Permission::read(Role::any()).'"]'; break; case 'Utopia\Database\Validator\Roles': $node['schema']['type'] = $validator->getType(); $node['schema']['items'] = [ 'type' => 'string', ]; - $node['schema']['x-example'] = '["' . Role::any()->toString() . '"]'; + $node['schema']['x-example'] = '["'.Role::any()->toString().'"]'; break; case 'Appwrite\Auth\Validator\Password': $node['schema']['type'] = $validator->getType(); @@ -413,25 +415,25 @@ class OpenAPI3 extends Format break; } - if ($param['optional'] && !\is_null($param['default'])) { // Param has default value + if ($param['optional'] && ! \is_null($param['default'])) { // Param has default value $node['schema']['default'] = $param['default']; } - if (false !== \strpos($url, ':' . $name)) { // Param is in URL path + if (false !== \strpos($url, ':'.$name)) { // Param is in URL path $node['in'] = 'path'; $temp['parameters'][] = $node; } elseif ($route->getMethod() == 'GET') { // Param is in query $node['in'] = 'query'; $temp['parameters'][] = $node; } else { // Param is in payload - if (!$param['optional']) { + if (! $param['optional']) { $bodyRequired[] = $name; } $body['content'][$consumes[0]]['schema']['properties'][$name] = [ 'type' => $node['schema']['type'], 'description' => $node['description'], - 'x-example' => $node['schema']['x-example'] ?? null + 'x-example' => $node['schema']['x-example'] ?? null, ]; if ($node['schema']['x-upload-id'] ?? false) { @@ -451,14 +453,14 @@ class OpenAPI3 extends Format } } - $url = \str_replace(':' . $name, '{' . $name . '}', $url); + $url = \str_replace(':'.$name, '{'.$name.'}', $url); } - if (!empty($bodyRequired)) { + if (! empty($bodyRequired)) { $body['content'][$consumes[0]]['schema']['required'] = $bodyRequired; } - if (!empty($body['content'][$consumes[0]]['schema']['properties'])) { + if (! empty($body['content'][$consumes[0]]['schema']['properties'])) { $temp['requestBody'] = $body; } @@ -470,7 +472,7 @@ class OpenAPI3 extends Format } foreach ($this->models as $model) { - if (!in_array($model->getType(), $usedModels) && $model->getType() !== 'error') { + if (! in_array($model->getType(), $usedModels) && $model->getType() !== 'error') { continue; } @@ -482,7 +484,7 @@ class OpenAPI3 extends Format 'type' => 'object', ]; - if (!empty($rules)) { + if (! empty($rules)) { $output['components']['schemas'][$model->getType()]['properties'] = []; } @@ -490,7 +492,7 @@ class OpenAPI3 extends Format $output['components']['schemas'][$model->getType()]['additionalProperties'] = true; } - if (!empty($required)) { + if (! empty($required)) { $output['components']['schemas'][$model->getType()]['required'] = $required; } @@ -537,19 +539,19 @@ class OpenAPI3 extends Format if ($rule['array']) { $items = [ 'anyOf' => \array_map(function ($type) { - return ['$ref' => '#/components/schemas/' . $type]; - }, $rule['type']) + return ['$ref' => '#/components/schemas/'.$type]; + }, $rule['type']), ]; } else { $items = [ 'oneOf' => \array_map(function ($type) { - return ['$ref' => '#/components/schemas/' . $type]; - }, $rule['type']) + return ['$ref' => '#/components/schemas/'.$type]; + }, $rule['type']), ]; } } else { $items = [ - '$ref' => '#/components/schemas/' . $rule['type'], + '$ref' => '#/components/schemas/'.$rule['type'], ]; } break; @@ -582,7 +584,7 @@ class OpenAPI3 extends Format if ($items) { $output['components']['schemas'][$model->getType()]['properties'][$name]['items'] = $items; } - if (!in_array($name, $required)) { + if (! in_array($name, $required)) { $output['components']['schemas'][$model->getType()]['properties'][$name]['nullable'] = true; } } diff --git a/src/Appwrite/Specification/Format/Swagger2.php b/src/Appwrite/Specification/Format/Swagger2.php index 13422aab1f..7b4a1f709b 100644 --- a/src/Appwrite/Specification/Format/Swagger2.php +++ b/src/Appwrite/Specification/Format/Swagger2.php @@ -19,30 +19,32 @@ class Swagger2 extends Format protected function getNestedModels(Model $model, array &$usedModels): void { foreach ($model->getRules() as $rule) { - if (!in_array($model->getType(), $usedModels)) { + if (! in_array($model->getType(), $usedModels)) { continue; } if (\is_array($rule['type'])) { foreach ($rule['type'] as $ruleType) { - if (!in_array($ruleType, ['string', 'integer', 'boolean', 'json', 'float'])) { + if (! in_array($ruleType, ['string', 'integer', 'boolean', 'json', 'float'])) { $usedModels[] = $ruleType; foreach ($this->models as $m) { if ($m->getType() === $ruleType) { $this->getNestedModels($m, $usedModels); + continue; } } } } } else { - if (!in_array($rule['type'], ['string', 'integer', 'boolean', 'json', 'float'])) { + if (! in_array($rule['type'], ['string', 'integer', 'boolean', 'json', 'float'])) { $usedModels[] = $rule['type']; foreach ($this->models as $m) { if ($m->getType() === $rule['type']) { $this->getNestedModels($m, $usedModels); + continue; } } @@ -123,7 +125,7 @@ class Swagger2 extends Format } $id = $route->getLabel('sdk.method', \uniqid()); - $desc = (!empty($route->getLabel('sdk.description', ''))) ? \realpath(__DIR__ . '/../../../../' . $route->getLabel('sdk.description', '')) : null; + $desc = (! empty($route->getLabel('sdk.description', ''))) ? \realpath(__DIR__.'/../../../../'.$route->getLabel('sdk.description', '')) : null; $produces = $route->getLabel('sdk.response.type', null); $model = $route->getLabel('sdk.response.model', 'none'); $routeSecurity = $route->getLabel('sdk.auth', []); @@ -152,7 +154,7 @@ class Swagger2 extends Format $temp = [ 'summary' => $route->getDesc(), - 'operationId' => $route->getLabel('sdk.namespace', 'default') . ucfirst($id), + 'operationId' => $route->getLabel('sdk.namespace', 'default').ucfirst($id), 'consumes' => [], 'produces' => [], 'tags' => [$route->getLabel('sdk.namespace', 'default')], @@ -163,8 +165,8 @@ class Swagger2 extends Format 'weight' => $route->getOrder(), 'cookies' => $route->getLabel('sdk.cookies', false), 'type' => $route->getLabel('sdk.methodType', ''), - 'demo' => Template::fromCamelCaseToDash($route->getLabel('sdk.namespace', 'default')) . '/' . Template::fromCamelCaseToDash($id) . '.md', - 'edit' => 'https://github.com/appwrite/appwrite/edit/master' . $route->getLabel('sdk.description', ''), + 'demo' => Template::fromCamelCaseToDash($route->getLabel('sdk.namespace', 'default')).'/'.Template::fromCamelCaseToDash($id).'.md', + 'edit' => 'https://github.com/appwrite/appwrite/edit/master'.$route->getLabel('sdk.description', ''), 'rate-limit' => $route->getLabel('abuse-limit', 0), 'rate-time' => $route->getLabel('abuse-time', 3600), 'rate-key' => $route->getLabel('abuse-key', 'url:{url},ip:{ip}'), @@ -192,8 +194,8 @@ class Swagger2 extends Format } } - if (!(\is_array($model)) && $model->isNone()) { - $temp['responses'][(string)$route->getLabel('sdk.response.code', '500')] = [ + if (! (\is_array($model)) && $model->isNone()) { + $temp['responses'][(string) $route->getLabel('sdk.response.code', '500')] = [ 'description' => in_array($produces, [ 'image/*', 'image/jpeg', @@ -205,42 +207,42 @@ class Swagger2 extends Format 'image/bmp', ]) ? 'Image' : 'File', 'schema' => [ - 'type' => 'file' + 'type' => 'file', ], ]; } else { if (\is_array($model)) { - $modelDescription = \join(', or ', \array_map(fn ($m) => $m->getName(), $model)); + $modelDescription = \implode(', or ', \array_map(fn ($m) => $m->getName(), $model)); // model has multiple possible responses, we will use oneOf foreach ($model as $m) { $usedModels[] = $m->getType(); } - $temp['responses'][(string)$route->getLabel('sdk.response.code', '500')] = [ + $temp['responses'][(string) $route->getLabel('sdk.response.code', '500')] = [ 'description' => $modelDescription, 'schema' => [ 'x-oneOf' => \array_map(function ($m) { - return ['$ref' => '#/definitions/' . $m->getType()]; - }, $model) + return ['$ref' => '#/definitions/'.$m->getType()]; + }, $model), ], ]; } else { // Response definition using one type $usedModels[] = $model->getType(); - $temp['responses'][(string)$route->getLabel('sdk.response.code', '500')] = [ + $temp['responses'][(string) $route->getLabel('sdk.response.code', '500')] = [ 'description' => $model->getName(), 'schema' => [ - '$ref' => '#/definitions/' . $model->getType(), + '$ref' => '#/definitions/'.$model->getType(), ], ]; } } if (in_array($route->getLabel('sdk.response.code', 500), [204, 301, 302, 308], true)) { - $temp['responses'][(string)$route->getLabel('sdk.response.code', '500')]['description'] = 'No content'; - unset($temp['responses'][(string)$route->getLabel('sdk.response.code', '500')]['schema']); + $temp['responses'][(string) $route->getLabel('sdk.response.code', '500')]['description'] = 'No content'; + unset($temp['responses'][(string) $route->getLabel('sdk.response.code', '500')]['schema']); } - if ((!empty($scope))) { // && 'public' != $scope + if ((! empty($scope))) { // && 'public' != $scope $securities = ['Project' => []]; foreach ($route->getLabel('sdk.auth', []) as $security) { @@ -276,7 +278,7 @@ class Swagger2 extends Format $node = [ 'name' => $name, 'description' => $param['description'], - 'required' => !$param['optional'], + 'required' => ! $param['optional'], ]; foreach ($this->services as $service) { @@ -285,10 +287,10 @@ class Swagger2 extends Format } } - switch ((!empty($validator)) ? \get_class($validator) : '') { + switch ((! empty($validator)) ? \get_class($validator) : '') { case 'Utopia\Validator\Text': $node['type'] = $validator->getType(); - $node['x-example'] = '[' . \strtoupper(Template::fromCamelCaseToSnake($node['name'])) . ']'; + $node['x-example'] = '['.\strtoupper(Template::fromCamelCaseToSnake($node['name'])).']'; break; case 'Utopia\Validator\Boolean': $node['type'] = $validator->getType(); @@ -299,11 +301,11 @@ class Swagger2 extends Format $node['x-upload-id'] = true; } $node['type'] = $validator->getType(); - $node['x-example'] = '[' . \strtoupper(Template::fromCamelCaseToSnake($node['name'])) . ']'; + $node['x-example'] = '['.\strtoupper(Template::fromCamelCaseToSnake($node['name'])).']'; break; case 'Utopia\Database\Validator\UID': $node['type'] = $validator->getType(); - $node['x-example'] = '[' . \strtoupper(Template::fromCamelCaseToSnake($node['name'])) . ']'; + $node['x-example'] = '['.\strtoupper(Template::fromCamelCaseToSnake($node['name'])).']'; break; case 'Utopia\Database\Validator\DatetimeValidator': $node['type'] = $validator->getType(); @@ -358,7 +360,7 @@ class Swagger2 extends Format $node['items'] = [ 'type' => 'string', ]; - $node['x-example'] = '["' . Permission::read(Role::any()) . '"]'; + $node['x-example'] = '["'.Permission::read(Role::any()).'"]'; break; case 'Utopia\Database\Validator\Roles': $node['type'] = $validator->getType(); @@ -366,7 +368,7 @@ class Swagger2 extends Format $node['items'] = [ 'type' => 'string', ]; - $node['x-example'] = '["' . Role::any()->toString() . '"]'; + $node['x-example'] = '["'.Role::any()->toString().'"]'; break; case 'Appwrite\Auth\Validator\Password': $node['type'] = $validator->getType(); @@ -415,11 +417,11 @@ class Swagger2 extends Format break; } - if ($param['optional'] && !\is_null($param['default'])) { // Param has default value + if ($param['optional'] && ! \is_null($param['default'])) { // Param has default value $node['default'] = $param['default']; } - if (false !== \strpos($url, ':' . $name)) { // Param is in URL path + if (false !== \strpos($url, ':'.$name)) { // Param is in URL path $node['in'] = 'path'; $temp['parameters'][] = $node; } elseif ($route->getMethod() == 'GET') { // Param is in query @@ -433,7 +435,7 @@ class Swagger2 extends Format continue; } - if (!$param['optional']) { + if (! $param['optional']) { $bodyRequired[] = $name; } @@ -453,14 +455,14 @@ class Swagger2 extends Format } } - $url = \str_replace(':' . $name, '{' . $name . '}', $url); + $url = \str_replace(':'.$name, '{'.$name.'}', $url); } - if (!empty($bodyRequired)) { + if (! empty($bodyRequired)) { $body['schema']['required'] = $bodyRequired; } - if (!empty($body['schema']['properties'])) { + if (! empty($body['schema']['properties'])) { $temp['parameters'][] = $body; } @@ -474,7 +476,7 @@ class Swagger2 extends Format } foreach ($this->models as $model) { - if (!in_array($model->getType(), $usedModels)) { + if (! in_array($model->getType(), $usedModels)) { continue; } @@ -486,7 +488,7 @@ class Swagger2 extends Format 'type' => 'object', ]; - if (!empty($rules)) { + if (! empty($rules)) { $output['definitions'][$model->getType()]['properties'] = []; } @@ -494,7 +496,7 @@ class Swagger2 extends Format $output['definitions'][$model->getType()]['additionalProperties'] = true; } - if (!empty($required)) { + if (! empty($required)) { $output['definitions'][$model->getType()]['required'] = $required; } @@ -539,17 +541,17 @@ class Swagger2 extends Format if (\is_array($rule['type'])) { if ($rule['array']) { $items = [ - 'x-anyOf' => \array_map(fn ($type) => ['$ref' => '#/definitions/' . $type], $rule['type']) + 'x-anyOf' => \array_map(fn ($type) => ['$ref' => '#/definitions/'.$type], $rule['type']), ]; } else { $items = [ - 'x-oneOf' => \array_map(fn ($type) => ['$ref' => '#/definitions/' . $type], $rule['type']) + 'x-oneOf' => \array_map(fn ($type) => ['$ref' => '#/definitions/'.$type], $rule['type']), ]; } } else { $items = [ 'type' => $type, - '$ref' => '#/definitions/' . $rule['type'], + '$ref' => '#/definitions/'.$rule['type'], ]; } break; @@ -562,6 +564,7 @@ class Swagger2 extends Format 'description' => $rule['description'] ?? '', 'x-example' => $rule['example'] ?? null, ]; + continue; } @@ -592,7 +595,7 @@ class Swagger2 extends Format if ($items) { $output['definitions'][$model->getType()]['properties'][$name]['items'] = $items; } - if (!in_array($name, $required)) { + if (! in_array($name, $required)) { $output['definitions'][$model->getType()]['properties'][$name]['x-nullable'] = true; } } diff --git a/src/Appwrite/Task/Validator/Cron.php b/src/Appwrite/Task/Validator/Cron.php index 03bd1c5220..a2709bc1c0 100644 --- a/src/Appwrite/Task/Validator/Cron.php +++ b/src/Appwrite/Task/Validator/Cron.php @@ -24,8 +24,7 @@ class Cron extends Validator * * Returns true if valid or false if not. * - * @param mixed $value - * + * @param mixed $value * @return bool */ public function isValid($value): bool @@ -34,7 +33,7 @@ class Cron extends Validator return true; } - if (!CronExpression::isValidExpression($value)) { + if (! CronExpression::isValidExpression($value)) { return false; } diff --git a/src/Appwrite/Template/Template.php b/src/Appwrite/Template/Template.php index c01d54389b..6b2bec0aef 100644 --- a/src/Appwrite/Template/Template.php +++ b/src/Appwrite/Template/Template.php @@ -17,18 +17,17 @@ class Template extends View * * Creates a new Template() from the file at $path * - * @param string $path - * + * @param string $path * @return self - * */ public static function fromFile(string $path): self { - if (!\is_readable($path)) { + if (! \is_readable($path)) { throw new Exception("$path view template is not readable."); } $template = new Template(); + return $template->setPath($path); } @@ -37,10 +36,8 @@ class Template extends View * * Creates a new Template() using a raw string * - * @param string $content - * + * @param string $content * @return self - * */ public static function fromString(string $content): self { @@ -50,6 +47,7 @@ class Template extends View $template = new Template(); $template->content = $content; + return $template; } @@ -71,10 +69,10 @@ class Template extends View if (\is_readable($this->path)) { $template = \file_get_contents($this->path); // Include template file - } elseif (!empty($this->content)) { + } elseif (! empty($this->content)) { $template = $this->print($this->content, self::FILTER_NL2P); } else { - throw new Exception('"' . $this->path . '" template is not readable or not found'); + throw new Exception('"'.$this->path.'" template is not readable or not found'); } // First replace the variables inside the params. Then replace the variables in the template @@ -90,7 +88,6 @@ class Template extends View * Parse URL string to array * * @param $url - * * @return mixed On seriously malformed URLs, parse_url() may return FALSE. */ public static function parseURL($url) @@ -104,25 +101,24 @@ class Template extends View * Convert PHP array to query string * * @param $url - * * @return string */ public static function unParseURL(array $url) { - $scheme = isset($url['scheme']) ? $url['scheme'] . '://' : ''; + $scheme = isset($url['scheme']) ? $url['scheme'].'://' : ''; $host = isset($url['host']) ? $url['host'] : ''; - $port = isset($url['port']) ? ':' . $url['port'] : ''; + $port = isset($url['port']) ? ':'.$url['port'] : ''; $user = isset($url['user']) ? $url['user'] : ''; - $pass = isset($url['pass']) ? ':' . $url['pass'] : ''; + $pass = isset($url['pass']) ? ':'.$url['pass'] : ''; $pass = ($user || $pass) ? "$pass@" : ''; $path = isset($url['path']) ? $url['path'] : ''; - $query = isset($url['query']) && !empty($url['query']) ? '?' . $url['query'] : ''; + $query = isset($url['query']) && ! empty($url['query']) ? '?'.$url['query'] : ''; - $fragment = isset($url['fragment']) ? '#' . $url['fragment'] : ''; + $fragment = isset($url['fragment']) ? '#'.$url['fragment'] : ''; - return $scheme . $user . $pass . $host . $port . $path . $query . $fragment; + return $scheme.$user.$pass.$host.$port.$path.$query.$fragment; } /** @@ -131,8 +127,7 @@ class Template extends View * Merge array of params to query string * * @param $query1 - * @param array $query2 - * + * @param array $query2 * @return string */ public static function mergeQuery($query1, array $query2) @@ -149,7 +144,7 @@ class Template extends View /** * From Camel Case * - * @var string $input + * @var string * * @return string */ @@ -167,7 +162,7 @@ class Template extends View /** * From Camel Case to Dash Case * - * @var string $input + * @var string * * @return string */ diff --git a/src/Appwrite/URL/URL.php b/src/Appwrite/URL/URL.php index 98250ab429..bfc6b8ee7d 100644 --- a/src/Appwrite/URL/URL.php +++ b/src/Appwrite/URL/URL.php @@ -9,8 +9,7 @@ class URL * * Take a URL string and split it to array parts * - * @param string $url - * + * @param string $url * @return array */ public static function parse(string $url): array @@ -34,46 +33,45 @@ class URL * * Take URL parts and combine them to a valid string * - * @param array $url - * @param array $ommit - * + * @param array $url + * @param array $ommit * @return string */ public static function unparse(array $url, array $ommit = []): string { if (isset($url['path']) && \mb_substr($url['path'], 0, 1) !== '/') { - $url['path'] = '/' . $url['path']; + $url['path'] = '/'.$url['path']; } $parts = []; - $parts['scheme'] = isset($url['scheme']) ? $url['scheme'] . '://' : ''; + $parts['scheme'] = isset($url['scheme']) ? $url['scheme'].'://' : ''; $parts['host'] = isset($url['host']) ? $url['host'] : ''; - $parts['port'] = isset($url['port']) ? ':' . $url['port'] : ''; + $parts['port'] = isset($url['port']) ? ':'.$url['port'] : ''; $parts['user'] = isset($url['user']) ? $url['user'] : ''; - $parts['pass'] = isset($url['pass']) ? ':' . $url['pass'] : ''; + $parts['pass'] = isset($url['pass']) ? ':'.$url['pass'] : ''; - $parts['pass'] = ($parts['user'] || $parts['pass']) ? $parts['pass'] . '@' : ''; + $parts['pass'] = ($parts['user'] || $parts['pass']) ? $parts['pass'].'@' : ''; $parts['path'] = isset($url['path']) ? $url['path'] : ''; - $parts['query'] = isset($url['query']) && !empty($url['query']) ? '?' . $url['query'] : ''; + $parts['query'] = isset($url['query']) && ! empty($url['query']) ? '?'.$url['query'] : ''; - $parts['fragment'] = isset($url['fragment']) ? '#' . $url['fragment'] : ''; + $parts['fragment'] = isset($url['fragment']) ? '#'.$url['fragment'] : ''; if ($ommit) { foreach ($ommit as $key) { - if (isset($parts[ $key ])) { - $parts[ $key ] = ''; + if (isset($parts[$key])) { + $parts[$key] = ''; } } } - return $parts['scheme'] . $parts['user'] . $parts['pass'] . $parts['host'] . $parts['port'] . $parts['path'] . $parts['query'] . $parts['fragment']; + return $parts['scheme'].$parts['user'].$parts['pass'].$parts['host'].$parts['port'].$parts['path'].$parts['query'].$parts['fragment']; } /** @@ -81,8 +79,7 @@ class URL * * Convert query string to array * - * @param string $query - * + * @param string $query * @return array */ public static function parseQuery(string $query): array @@ -97,8 +94,7 @@ class URL * * Convert query string array to string * - * @param array $query - * + * @param array $query * @return string */ public static function unparseQuery(array $query): string diff --git a/src/Appwrite/Usage/Calculators/TimeSeries.php b/src/Appwrite/Usage/Calculators/TimeSeries.php index 2ef3d77cac..d9911b0a5f 100644 --- a/src/Appwrite/Usage/Calculators/TimeSeries.php +++ b/src/Appwrite/Usage/Calculators/TimeSeries.php @@ -2,12 +2,11 @@ namespace Appwrite\Usage\Calculators; -use Utopia\App; use Appwrite\Usage\Calculator; +use DateTime; +use InfluxDB\Database as InfluxDatabase; use Utopia\Database\Database; use Utopia\Database\Document; -use InfluxDB\Database as InfluxDatabase; -use DateTime; class TimeSeries extends Calculator { @@ -41,17 +40,18 @@ class TimeSeries extends Calculator /** * Periods the metrics are collected for + * * @var array */ protected array $periods = [ [ 'key' => '1h', - 'startTime' => '-24 hours' + 'startTime' => '-24 hours', ], [ 'key' => '1d', - 'startTime' => '-30 days' - ] + 'startTime' => '-30 days', + ], ]; /** @@ -309,7 +309,7 @@ class TimeSeries extends Calculator ], 'files.bucketId.count.total' => [ 'table' => 'appwrite_usage_files_{scope}_count_total', - 'groupBy' => ['bucketId'] + 'groupBy' => ['bucketId'], ], 'databases.$all.count.total' => [ 'table' => 'appwrite_usage_databases_{scope}_count_total', @@ -322,15 +322,15 @@ class TimeSeries extends Calculator ], 'collections.databaseId.count.total' => [ 'table' => 'appwrite_usage_collections_{scope}_count_total', - 'groupBy' => ['databaseId'] + 'groupBy' => ['databaseId'], ], 'documents.databaseId.count.total' => [ 'table' => 'appwrite_usage_documents_{scope}_count_total', - 'groupBy' => ['databaseId'] + 'groupBy' => ['databaseId'], ], 'documents.databaseId/collectionId.count.total' => [ 'table' => 'appwrite_usage_documents_{scope}_count_total', - 'groupBy' => ['databaseId', 'collectionId'] + 'groupBy' => ['databaseId', 'collectionId'], ], 'deployments.$all.storage.size' => [ 'table' => 'appwrite_usage_deployments_{scope}_storage_size', @@ -343,7 +343,7 @@ class TimeSeries extends Calculator ], 'files.$bucketId.storage.size' => [ 'table' => 'appwrite_usage_files_{scope}_storage_size', - 'groupBy' => ['bucketId'] + 'groupBy' => ['bucketId'], ], 'builds.$all.compute.time' => [ @@ -368,18 +368,18 @@ class TimeSeries extends Calculator ], 'deployments.$all.storage.size' => [ - 'table' => 'appwrite_usage_deployments_{scope}_storage_size' + 'table' => 'appwrite_usage_deployments_{scope}_storage_size', ], 'project.$all.storage.size' => [ - 'table' => 'appwrite_usage_project_{scope}_storage_size' + 'table' => 'appwrite_usage_project_{scope}_storage_size', ], 'files.$all.storage.size' => [ - 'table' => 'appwrite_usage_files_{scope}_storage_size' + 'table' => 'appwrite_usage_files_{scope}_storage_size', ], 'files.bucketId.storage.size' => [ 'table' => 'appwrite_usage_files_{scope}_storage_size', - 'groupBy' => ['bucketId'] - ] + 'groupBy' => ['bucketId'], + ], ]; public function __construct(string $region, Database $database, InfluxDatabase $influxDB, callable $errorHandler = null) @@ -394,19 +394,18 @@ class TimeSeries extends Calculator * Create or Update Mertic * Create or update each metric in the stats collection for the given project * - * @param string $projectId - * @param int $time - * @param string $period - * @param string $metric - * @param int $value - * @param int $type - * + * @param string $projectId + * @param int $time + * @param string $period + * @param string $metric + * @param int $value + * @param int $type * @return void */ private function createOrUpdateMetric(string $projectId, string $time, string $period, string $metric, int $value, int $type): void { $id = \md5("{$time}_{$period}_{$metric}"); - $this->database->setNamespace('_' . $projectId); + $this->database->setNamespace('_'.$projectId); try { $document = $this->database->getDocument('stats', $id); @@ -440,37 +439,36 @@ class TimeSeries extends Calculator * Sync From InfluxDB * Sync stats from influxDB to stats collection in the Appwrite database * - * @param string $metric - * @param array $options - * @param array $period - * + * @param string $metric + * @param array $options + * @param array $period * @return void */ private function syncFromInfluxDB(string $metric, array $options, array $period): void { $start = DateTime::createFromFormat('U', \strtotime($period['startTime']))->format(DateTime::RFC3339); - if (!empty($this->latestTime[$metric][$period['key']])) { + if (! empty($this->latestTime[$metric][$period['key']])) { $start = $this->latestTime[$metric][$period['key']]; } $end = (new DateTime())->format(DateTime::RFC3339); $table = $options['table']; //Which influxdb table to query for this metric - $groupBy = empty($options['groupBy']) ? '' : ', ' . implode(', ', array_map(fn($groupBy) => '"' . $groupBy . '" ', $options['groupBy'])); //Some sub level metrics may be grouped by other tags like collectionId, bucketId, etc + $groupBy = empty($options['groupBy']) ? '' : ', '.implode(', ', array_map(fn ($groupBy) => '"'.$groupBy.'" ', $options['groupBy'])); //Some sub level metrics may be grouped by other tags like collectionId, bucketId, etc $filters = $options['filters'] ?? []; // Some metrics might have additional filters, like function's status - if (!empty($filters)) { - $filters = ' AND ' . implode(' AND ', array_map(fn ($filter, $value) => "\"{$filter}\"='{$value}'", array_keys($filters), array_values($filters))); + if (! empty($filters)) { + $filters = ' AND '.implode(' AND ', array_map(fn ($filter, $value) => "\"{$filter}\"='{$value}'", array_keys($filters), array_values($filters))); } else { $filters = ''; } - $query = "SELECT sum(value) AS \"value\" "; + $query = 'SELECT sum(value) AS "value" '; $query .= "FROM \"{$table}\" "; $query .= "WHERE \"time\" > '{$start}' "; $query .= "AND \"time\" < '{$end}' "; $query .= "AND \"metric_type\"='counter' {$filters} "; $query .= "GROUP BY time({$period['key']}), \"projectId\", \"projectInternalId\" {$groupBy} "; - $query .= "FILL(null)"; + $query .= 'FILL(null)'; try { $result = $this->influxDB->query($query); @@ -478,9 +476,9 @@ class TimeSeries extends Calculator foreach ($points as $point) { $projectId = $point['projectId']; - if (!empty($projectId) && $projectId !== 'console') { + if (! empty($projectId) && $projectId !== 'console') { $metricUpdated = $metric; - if (!empty($groupBy)) { + if (! empty($groupBy)) { foreach ($options['groupBy'] as $groupBy) { $groupedBy = $point[$groupBy] ?? ''; if (empty($groupedBy)) { @@ -490,7 +488,7 @@ class TimeSeries extends Calculator } } - $value = (!empty($point['value'])) ? $point['value'] : 0; + $value = (! empty($point['value'])) ? $point['value'] : 0; if (empty($point['projectInternalId'] ?? null)) { continue; } diff --git a/src/Appwrite/Usage/Stats.php b/src/Appwrite/Usage/Stats.php index e6e0056664..109fced9b1 100644 --- a/src/Appwrite/Usage/Stats.php +++ b/src/Appwrite/Usage/Stats.php @@ -24,7 +24,7 @@ class Stats /** * Event constructor. * - * @param mixed $statsd + * @param mixed $statsd */ public function __construct($statsd) { @@ -32,9 +32,8 @@ class Stats } /** - * @param string $key - * @param mixed $value - * + * @param string $key + * @param mixed $value * @return $this */ public function setParam(string $key, $value): self @@ -45,8 +44,7 @@ class Stats } /** - * @param string $key - * + * @param string $key * @return mixed|null */ public function getParam(string $key) @@ -55,8 +53,7 @@ class Stats } /** - * @param string $namespace - * + * @param string $namespace * @return $this */ public function setNamespace(string $namespace): self @@ -77,13 +74,14 @@ class Stats /** * Submit data to StatsD. * Send various metrics to StatsD based on the parameters that are set + * * @return void */ public function submit(): void { $projectId = $this->params['projectId'] ?? ''; $projectInternalId = $this->params['projectInternalId']; - $tags = ",projectInternalId={$projectInternalId},projectId={$projectId},version=" . App::getEnv('_APP_VERSION', 'UNKNOWN'); + $tags = ",projectInternalId={$projectInternalId},projectId={$projectId},version=".App::getEnv('_APP_VERSION', 'UNKNOWN'); // the global namespace is prepended to every key (optional) $this->statsd->setNamespace($this->namespace); @@ -91,14 +89,14 @@ class Stats $httpRequest = $this->params['project.{scope}.network.requests'] ?? 0; $httpMethod = $this->params['httpMethod'] ?? ''; if ($httpRequest >= 1) { - $this->statsd->increment('project.{scope}.network.requests' . $tags . ',method=' . \strtolower($httpMethod)); + $this->statsd->increment('project.{scope}.network.requests'.$tags.',method='.\strtolower($httpMethod)); } $inbound = $this->params['project.{scope}.network.inbound'] ?? 0; $outbound = $this->params['project.{scope}.network.outbound'] ?? 0; - $this->statsd->count('project.{scope}.network.inbound' . $tags, $inbound); - $this->statsd->count('project.{scope}.network.outbound' . $tags, $outbound); - $this->statsd->count('project.{scope}.network.bandwidth' . $tags, $inbound + $outbound); + $this->statsd->count('project.{scope}.network.inbound'.$tags, $inbound); + $this->statsd->count('project.{scope}.network.outbound'.$tags, $outbound); + $this->statsd->count('project.{scope}.network.bandwidth'.$tags, $inbound + $outbound); $usersMetrics = [ 'users.{scope}.requests.create', @@ -111,7 +109,7 @@ class Stats foreach ($usersMetrics as $metric) { $value = $this->params[$metric] ?? 0; if ($value === 1 || $value === -1) { - $this->statsd->count($metric . $tags, $value); + $this->statsd->count($metric.$tags, $value); } } @@ -130,14 +128,14 @@ class Stats 'documents.{scope}.requests.delete', 'databases.{scope}.count.total', 'collections.{scope}.count.total', - 'documents.{scope}.count.total' + 'documents.{scope}.count.total', ]; foreach ($dbMetrics as $metric) { $value = $this->params[$metric] ?? 0; if ($value === 1 || $value === -1) { - $dbTags = $tags . ",collectionId=" . ($this->params['collectionId'] ?? '') . ",databaseId=" . ($this->params['databaseId'] ?? ''); - $this->statsd->count($metric . $dbTags, $value); + $dbTags = $tags.',collectionId='.($this->params['collectionId'] ?? '').',databaseId='.($this->params['databaseId'] ?? ''); + $this->statsd->count($metric.$dbTags, $value); } } @@ -152,14 +150,14 @@ class Stats 'files.{scope}.requests.delete', 'buckets.{scope}.count.total', 'files.{scope}.count.total', - 'files.{scope}.storage.size' + 'files.{scope}.storage.size', ]; foreach ($storageMertics as $metric) { $value = $this->params[$metric] ?? 0; if ($value !== 0) { - $storageTags = $tags . ",bucketId=" . ($this->params['bucketId'] ?? ''); - $this->statsd->count($metric . $storageTags, $value); + $storageTags = $tags.',bucketId='.($this->params['bucketId'] ?? ''); + $this->statsd->count($metric.$storageTags, $value); } } @@ -172,8 +170,8 @@ class Stats foreach ($sessionsMetrics as $metric) { $value = $this->params[$metric] ?? 0; if ($value >= 1) { - $sessionTags = $tags . ",provider=" . ($this->params['provider'] ?? ''); - $this->statsd->count($metric . $sessionTags, $value); + $sessionTags = $tags.',provider='.($this->params['provider'] ?? ''); + $this->statsd->count($metric.$sessionTags, $value); } } @@ -186,30 +184,30 @@ class Stats $functionBuildTime = ($this->params['buildTime'] ?? 0) * 1000; // ms $functionBuildStatus = $this->params['buildStatus'] ?? ''; $functionCompute = $functionExecutionTime + $functionBuildTime; - $functionTags = $tags . ',functionId=' . $functionId; + $functionTags = $tags.',functionId='.$functionId; $deploymentSize = $this->params['deployment.{scope}.storage.size'] ?? 0; $storageSize = $this->params['files.{scope}.storage.size'] ?? 0; if ($deploymentSize + $storageSize > 0 || $deploymentSize + $storageSize <= -1) { - $this->statsd->count('project.{scope}.storage.size' . $tags, $deploymentSize + $storageSize); + $this->statsd->count('project.{scope}.storage.size'.$tags, $deploymentSize + $storageSize); } if ($deploymentSize !== 0) { - $this->statsd->count('deployments.{scope}.storage.size' . $functionTags, $deploymentSize); + $this->statsd->count('deployments.{scope}.storage.size'.$functionTags, $deploymentSize); } if ($functionExecution >= 1) { - $this->statsd->increment('executions.{scope}.compute' . $functionTags . ',functionStatus=' . $functionExecutionStatus); + $this->statsd->increment('executions.{scope}.compute'.$functionTags.',functionStatus='.$functionExecutionStatus); if ($functionExecutionTime > 0) { - $this->statsd->count('executions.{scope}.compute.time' . $functionTags, $functionExecutionTime); + $this->statsd->count('executions.{scope}.compute.time'.$functionTags, $functionExecutionTime); } } if ($functionBuild >= 1) { - $this->statsd->increment('builds.{scope}.compute' . $functionTags . ',functionBuildStatus=' . $functionBuildStatus); - $this->statsd->count('builds.{scope}.compute.time' . $functionTags, $functionBuildTime); + $this->statsd->increment('builds.{scope}.compute'.$functionTags.',functionBuildStatus='.$functionBuildStatus); + $this->statsd->count('builds.{scope}.compute.time'.$functionTags, $functionBuildTime); } if ($functionBuild + $functionExecution >= 1) { - $this->statsd->count('project.{scope}.compute.time' . $functionTags, $functionCompute); + $this->statsd->count('project.{scope}.compute.time'.$functionTags, $functionCompute); } $this->reset(); diff --git a/src/Appwrite/Utopia/Database/Validator/CustomId.php b/src/Appwrite/Utopia/Database/Validator/CustomId.php index 90d550371b..b6e913cb46 100644 --- a/src/Appwrite/Utopia/Database/Validator/CustomId.php +++ b/src/Appwrite/Utopia/Database/Validator/CustomId.php @@ -12,12 +12,10 @@ class CustomId extends Key * Returns true if valid or false if not. * * @param $value - * * @return bool */ public function isValid($value): bool { - return $value == 'unique()' || parent::isValid($value); } } diff --git a/src/Appwrite/Utopia/Database/Validator/IndexedQueries.php b/src/Appwrite/Utopia/Database/Validator/IndexedQueries.php index 1cc0429018..5945cfc762 100644 --- a/src/Appwrite/Utopia/Database/Validator/IndexedQueries.php +++ b/src/Appwrite/Utopia/Database/Validator/IndexedQueries.php @@ -24,10 +24,10 @@ class IndexedQueries extends Queries * * This Queries Validator filters indexes for only available indexes * - * @param Document[] $attributes - * @param Document[] $indexes - * @param Base ...$validators - * @param bool $strict + * @param Document[] $attributes + * @param Document[] $indexes + * @param Base ...$validators + * @param bool $strict */ public function __construct($attributes = [], $indexes = [], Base ...$validators) { @@ -35,17 +35,17 @@ class IndexedQueries extends Queries $this->indexes[] = new Document([ 'type' => Database::INDEX_UNIQUE, - 'attributes' => ['$id'] + 'attributes' => ['$id'], ]); $this->indexes[] = new Document([ 'type' => Database::INDEX_KEY, - 'attributes' => ['$createdAt'] + 'attributes' => ['$createdAt'], ]); $this->indexes[] = new Document([ 'type' => Database::INDEX_KEY, - 'attributes' => ['$updatedAt'] + 'attributes' => ['$updatedAt'], ]); foreach ($indexes ?? [] as $index) { @@ -58,9 +58,8 @@ class IndexedQueries extends Queries /** * Check if indexed array $indexes matches $queries * - * @param array $indexes - * @param array $queries - * + * @param array $indexes + * @param array $queries * @return bool */ protected function arrayMatch(array $indexes, array $queries): bool @@ -92,18 +91,18 @@ class IndexedQueries extends Queries * * Otherwise, returns true. * - * @param mixed $value + * @param mixed $value * @return bool */ public function isValid($value): bool { - if (!parent::isValid($value)) { + if (! parent::isValid($value)) { return false; } $queries = []; foreach ($value as $query) { - if (!$query instanceof Query) { + if (! $query instanceof Query) { $query = Query::parse($query); } @@ -111,8 +110,8 @@ class IndexedQueries extends Queries } $grouped = Query::groupByType($queries); - /** @var Query[] */ $filters = $grouped['filters']; - /** @var string[] */ $orderAttributes = $grouped['orderAttributes']; +/** @var Query[] */ $filters = $grouped['filters']; +/** @var string[] */ $orderAttributes = $grouped['orderAttributes']; // Check filter queries for exact index match if (count($filters) > 0) { @@ -129,22 +128,25 @@ class IndexedQueries extends Queries } } - if (!$found) { - $this->message = 'Index not found: ' . implode(",", array_keys($filtersByAttribute)); + if (! $found) { + $this->message = 'Index not found: '.implode(',', array_keys($filtersByAttribute)); + return false; } // search method requires fulltext index if (in_array(Query::TYPE_SEARCH, array_values($filtersByAttribute)) && $found['type'] !== Database::INDEX_FULLTEXT) { - $this->message = 'Search method requires fulltext index: ' . implode(",", array_keys($filtersByAttribute)); + $this->message = 'Search method requires fulltext index: '.implode(',', array_keys($filtersByAttribute)); + return false; } } // Check order attributes for exact index match $validator = new OrderAttributes($this->attributes, $this->indexes, true); - if (count($orderAttributes) > 0 && !$validator->isValid($orderAttributes)) { + if (count($orderAttributes) > 0 && ! $validator->isValid($orderAttributes)) { $this->message = $validator->getDescription(); + return false; } diff --git a/src/Appwrite/Utopia/Database/Validator/OrderAttributes.php b/src/Appwrite/Utopia/Database/Validator/OrderAttributes.php index dcf38c90f1..8a78362ce2 100644 --- a/src/Appwrite/Utopia/Database/Validator/OrderAttributes.php +++ b/src/Appwrite/Utopia/Database/Validator/OrderAttributes.php @@ -10,9 +10,9 @@ class OrderAttributes extends ValidatorOrderAttributes /** * Expression constructor * - * @param Document[] $attributes - * @param Document[] $indexes - * @param bool $strict + * @param Document[] $attributes + * @param Document[] $indexes + * @param bool $strict */ public function __construct($attributes, $indexes, $strict) { diff --git a/src/Appwrite/Utopia/Database/Validator/Queries.php b/src/Appwrite/Utopia/Database/Validator/Queries.php index 1e9fe8f208..7f923b0732 100644 --- a/src/Appwrite/Utopia/Database/Validator/Queries.php +++ b/src/Appwrite/Utopia/Database/Validator/Queries.php @@ -3,8 +3,8 @@ namespace Appwrite\Utopia\Database\Validator; use Appwrite\Utopia\Database\Validator\Query\Base; -use Utopia\Validator; use Utopia\Database\Query; +use Utopia\Validator; class Queries extends Validator { @@ -21,7 +21,7 @@ class Queries extends Validator /** * Queries constructor * - * @param Base ...$validators a list of validators + * @param Base ...$validators a list of validators */ public function __construct(Base ...$validators) { @@ -48,17 +48,18 @@ class Queries extends Validator * * Otherwise, returns true. * - * @param mixed $value + * @param mixed $value * @return bool */ public function isValid($value): bool { foreach ($value as $query) { - if (!$query instanceof Query) { + if (! $query instanceof Query) { try { $query = Query::parse($query); } catch (\Throwable $th) { $this->message = 'Invalid query: ${query}'; + return false; } } @@ -98,16 +99,18 @@ class Queries extends Validator if ($validator->getMethodType() !== $methodType) { continue; } - if (!$validator->isValid($query)) { - $this->message = 'Query not valid: ' . $validator->getDescription(); + if (! $validator->isValid($query)) { + $this->message = 'Query not valid: '.$validator->getDescription(); + return false; } $methodIsValid = true; } - if (!$methodIsValid) { - $this->message = 'Query method not valid: ' . $method; + if (! $methodIsValid) { + $this->message = 'Query method not valid: '.$method; + return false; } } diff --git a/src/Appwrite/Utopia/Database/Validator/Queries/Base.php b/src/Appwrite/Utopia/Database/Validator/Queries/Base.php index 89c82c8e82..b525f2c55e 100644 --- a/src/Appwrite/Utopia/Database/Validator/Queries/Base.php +++ b/src/Appwrite/Utopia/Database/Validator/Queries/Base.php @@ -3,10 +3,10 @@ namespace Appwrite\Utopia\Database\Validator\Queries; use Appwrite\Utopia\Database\Validator\Queries; -use Appwrite\Utopia\Database\Validator\Query\Limit; -use Appwrite\Utopia\Database\Validator\Query\Offset; use Appwrite\Utopia\Database\Validator\Query\Cursor; use Appwrite\Utopia\Database\Validator\Query\Filter; +use Appwrite\Utopia\Database\Validator\Query\Limit; +use Appwrite\Utopia\Database\Validator\Query\Offset; use Appwrite\Utopia\Database\Validator\Query\Order; use Utopia\Config\Config; use Utopia\Database\Database; @@ -17,8 +17,8 @@ class Base extends Queries /** * Expression constructor * - * @param string $collection - * @param string[] $allowedAttributes + * @param string $collection + * @param string[] $allowedAttributes */ public function __construct(string $collection, array $allowedAttributes) { @@ -32,7 +32,7 @@ class Base extends Queries $attributes = []; foreach ($collection['attributes'] as $attribute) { $key = $attribute['$id']; - if (!isset($allowedAttributesLookup[$key])) { + if (! isset($allowedAttributesLookup[$key])) { continue; } diff --git a/src/Appwrite/Utopia/Database/Validator/Queries/Buckets.php b/src/Appwrite/Utopia/Database/Validator/Queries/Buckets.php index c4d187520f..91d467b203 100644 --- a/src/Appwrite/Utopia/Database/Validator/Queries/Buckets.php +++ b/src/Appwrite/Utopia/Database/Validator/Queries/Buckets.php @@ -10,12 +10,11 @@ class Buckets extends Base 'fileSecurity', 'maximumFileSize', 'encryption', - 'antivirus' + 'antivirus', ]; /** * Expression constructor - * */ public function __construct() { diff --git a/src/Appwrite/Utopia/Database/Validator/Queries/Collections.php b/src/Appwrite/Utopia/Database/Validator/Queries/Collections.php index 6e8fcb8339..9bf2381ed2 100644 --- a/src/Appwrite/Utopia/Database/Validator/Queries/Collections.php +++ b/src/Appwrite/Utopia/Database/Validator/Queries/Collections.php @@ -7,12 +7,11 @@ class Collections extends Base public const ALLOWED_ATTRIBUTES = [ 'name', 'enabled', - 'documentSecurity' + 'documentSecurity', ]; /** * Expression constructor - * */ public function __construct() { diff --git a/src/Appwrite/Utopia/Database/Validator/Queries/Databases.php b/src/Appwrite/Utopia/Database/Validator/Queries/Databases.php index 22f7ad9b82..e47d9020d1 100644 --- a/src/Appwrite/Utopia/Database/Validator/Queries/Databases.php +++ b/src/Appwrite/Utopia/Database/Validator/Queries/Databases.php @@ -5,12 +5,11 @@ namespace Appwrite\Utopia\Database\Validator\Queries; class Databases extends Base { public const ALLOWED_ATTRIBUTES = [ - 'name' + 'name', ]; /** * Expression constructor - * */ public function __construct() { diff --git a/src/Appwrite/Utopia/Database/Validator/Queries/Deployments.php b/src/Appwrite/Utopia/Database/Validator/Queries/Deployments.php index 05b3326af1..20fe9a7123 100644 --- a/src/Appwrite/Utopia/Database/Validator/Queries/Deployments.php +++ b/src/Appwrite/Utopia/Database/Validator/Queries/Deployments.php @@ -13,7 +13,6 @@ class Deployments extends Base /** * Expression constructor - * */ public function __construct() { diff --git a/src/Appwrite/Utopia/Database/Validator/Queries/Documents.php b/src/Appwrite/Utopia/Database/Validator/Queries/Documents.php index fe1e85d699..44d9021ff4 100644 --- a/src/Appwrite/Utopia/Database/Validator/Queries/Documents.php +++ b/src/Appwrite/Utopia/Database/Validator/Queries/Documents.php @@ -3,10 +3,10 @@ namespace Appwrite\Utopia\Database\Validator\Queries; use Appwrite\Utopia\Database\Validator\IndexedQueries; -use Appwrite\Utopia\Database\Validator\Query\Limit; -use Appwrite\Utopia\Database\Validator\Query\Offset; use Appwrite\Utopia\Database\Validator\Query\Cursor; use Appwrite\Utopia\Database\Validator\Query\Filter; +use Appwrite\Utopia\Database\Validator\Query\Limit; +use Appwrite\Utopia\Database\Validator\Query\Offset; use Appwrite\Utopia\Database\Validator\Query\Order; use Utopia\Database\Database; use Utopia\Database\Document; @@ -16,8 +16,8 @@ class Documents extends IndexedQueries /** * Expression constructor * - * @param Document[] $attributes - * @param Document[] $indexes + * @param Document[] $attributes + * @param Document[] $indexes */ public function __construct(array $attributes, array $indexes) { diff --git a/src/Appwrite/Utopia/Database/Validator/Queries/Executions.php b/src/Appwrite/Utopia/Database/Validator/Queries/Executions.php index 2bfe46e28d..ca74367164 100644 --- a/src/Appwrite/Utopia/Database/Validator/Queries/Executions.php +++ b/src/Appwrite/Utopia/Database/Validator/Queries/Executions.php @@ -8,12 +8,11 @@ class Executions extends Base 'trigger', 'status', 'statusCode', - 'duration' + 'duration', ]; /** * Expression constructor - * */ public function __construct() { diff --git a/src/Appwrite/Utopia/Database/Validator/Queries/Files.php b/src/Appwrite/Utopia/Database/Validator/Queries/Files.php index 1941eabcdb..5984d32b9c 100644 --- a/src/Appwrite/Utopia/Database/Validator/Queries/Files.php +++ b/src/Appwrite/Utopia/Database/Validator/Queries/Files.php @@ -10,12 +10,11 @@ class Files extends Base 'mimeType', 'sizeOriginal', 'chunksTotal', - 'chunksUploaded' + 'chunksUploaded', ]; /** * Expression constructor - * */ public function __construct() { diff --git a/src/Appwrite/Utopia/Database/Validator/Queries/Functions.php b/src/Appwrite/Utopia/Database/Validator/Queries/Functions.php index a2ba368953..77b7e14028 100644 --- a/src/Appwrite/Utopia/Database/Validator/Queries/Functions.php +++ b/src/Appwrite/Utopia/Database/Validator/Queries/Functions.php @@ -12,12 +12,11 @@ class Functions extends Base 'schedule', 'scheduleNext', 'schedulePrevious', - 'timeout' + 'timeout', ]; /** * Expression constructor - * */ public function __construct() { diff --git a/src/Appwrite/Utopia/Database/Validator/Queries/Memberships.php b/src/Appwrite/Utopia/Database/Validator/Queries/Memberships.php index 5ff0098662..73add15ac4 100644 --- a/src/Appwrite/Utopia/Database/Validator/Queries/Memberships.php +++ b/src/Appwrite/Utopia/Database/Validator/Queries/Memberships.php @@ -9,12 +9,11 @@ class Memberships extends Base 'teamId', 'invited', 'joined', - 'confirm' + 'confirm', ]; /** * Expression constructor - * */ public function __construct() { diff --git a/src/Appwrite/Utopia/Database/Validator/Queries/Projects.php b/src/Appwrite/Utopia/Database/Validator/Queries/Projects.php index 7fff26db7f..6f36d73660 100644 --- a/src/Appwrite/Utopia/Database/Validator/Queries/Projects.php +++ b/src/Appwrite/Utopia/Database/Validator/Queries/Projects.php @@ -2,18 +2,15 @@ namespace Appwrite\Utopia\Database\Validator\Queries; -use Appwrite\Utopia\Database\Validator\Queries\Base; - class Projects extends Base { public const ALLOWED_ATTRIBUTES = [ 'name', - 'teamId' + 'teamId', ]; /** * Expression constructor - * */ public function __construct() { diff --git a/src/Appwrite/Utopia/Database/Validator/Queries/Teams.php b/src/Appwrite/Utopia/Database/Validator/Queries/Teams.php index 67aba71598..ccc5fdbf7c 100644 --- a/src/Appwrite/Utopia/Database/Validator/Queries/Teams.php +++ b/src/Appwrite/Utopia/Database/Validator/Queries/Teams.php @@ -6,12 +6,11 @@ class Teams extends Base { public const ALLOWED_ATTRIBUTES = [ 'name', - 'total' + 'total', ]; /** * Expression constructor - * */ public function __construct() { diff --git a/src/Appwrite/Utopia/Database/Validator/Queries/Users.php b/src/Appwrite/Utopia/Database/Validator/Queries/Users.php index 9b0dfe61e6..b0fe844017 100644 --- a/src/Appwrite/Utopia/Database/Validator/Queries/Users.php +++ b/src/Appwrite/Utopia/Database/Validator/Queries/Users.php @@ -12,12 +12,11 @@ class Users extends Base 'passwordUpdate', 'registration', 'emailVerification', - 'phoneVerification' + 'phoneVerification', ]; /** * Expression constructor - * */ public function __construct() { diff --git a/src/Appwrite/Utopia/Database/Validator/Queries/Variables.php b/src/Appwrite/Utopia/Database/Validator/Queries/Variables.php index eff7007c58..978c763b84 100644 --- a/src/Appwrite/Utopia/Database/Validator/Queries/Variables.php +++ b/src/Appwrite/Utopia/Database/Validator/Queries/Variables.php @@ -2,17 +2,14 @@ namespace Appwrite\Utopia\Database\Validator\Queries; -use Appwrite\Utopia\Database\Validator\Queries\Base; - class Variables extends Base { public const ALLOWED_ATTRIBUTES = [ - 'key' + 'key', ]; /** * Expression constructor - * */ public function __construct() { diff --git a/src/Appwrite/Utopia/Database/Validator/Query/Base.php b/src/Appwrite/Utopia/Database/Validator/Query/Base.php index 71a1497d29..75b02cb7a2 100644 --- a/src/Appwrite/Utopia/Database/Validator/Query/Base.php +++ b/src/Appwrite/Utopia/Database/Validator/Query/Base.php @@ -2,15 +2,19 @@ namespace Appwrite\Utopia\Database\Validator\Query; -use Utopia\Validator; use Utopia\Database\Query; +use Utopia\Validator; abstract class Base extends Validator { public const METHOD_TYPE_LIMIT = 'limit'; + public const METHOD_TYPE_OFFSET = 'offset'; + public const METHOD_TYPE_CURSOR = 'cursor'; + public const METHOD_TYPE_ORDER = 'order'; + public const METHOD_TYPE_FILTER = 'filter'; /** diff --git a/src/Appwrite/Utopia/Database/Validator/Query/Cursor.php b/src/Appwrite/Utopia/Database/Validator/Query/Cursor.php index 42bff08a1d..b99494d991 100644 --- a/src/Appwrite/Utopia/Database/Validator/Query/Cursor.php +++ b/src/Appwrite/Utopia/Database/Validator/Query/Cursor.php @@ -2,7 +2,6 @@ namespace Appwrite\Utopia\Database\Validator\Query; -use Appwrite\Utopia\Database\Validator\Query\Base; use Utopia\Database\Query; use Utopia\Database\Validator\UID; @@ -15,8 +14,7 @@ class Cursor extends Base * * Otherwise, returns false * - * @param Query $value - * + * @param Query $value * @return bool */ public function isValid($query): bool @@ -30,7 +28,8 @@ class Cursor extends Base if ($validator->isValid($cursor)) { return true; } - $this->message = 'Invalid cursor: ' . $validator->getDescription(); + $this->message = 'Invalid cursor: '.$validator->getDescription(); + return false; } diff --git a/src/Appwrite/Utopia/Database/Validator/Query/Filter.php b/src/Appwrite/Utopia/Database/Validator/Query/Filter.php index 096d036907..e11fc8a539 100644 --- a/src/Appwrite/Utopia/Database/Validator/Query/Filter.php +++ b/src/Appwrite/Utopia/Database/Validator/Query/Filter.php @@ -2,7 +2,6 @@ namespace Appwrite\Utopia\Database\Validator\Query; -use Appwrite\Utopia\Database\Validator\Query\Base; use Utopia\Database\Database; use Utopia\Database\Query; @@ -21,7 +20,7 @@ class Filter extends Base /** * Query constructor * - * @param int $maxValuesCount + * @param int $maxValuesCount */ public function __construct(array $attributes = [], int $maxValuesCount = 100) { @@ -35,8 +34,9 @@ class Filter extends Base protected function isValidAttribute($attribute): bool { // Search for attribute in schema - if (!isset($this->schema[$attribute])) { - $this->message = 'Attribute not found in schema: ' . $attribute; + if (! isset($this->schema[$attribute])) { + $this->message = 'Attribute not found in schema: '.$attribute; + return false; } @@ -45,14 +45,15 @@ class Filter extends Base protected function isValidAttributeAndValues(string $attribute, array $values): bool { - if (!$this->isValidAttribute($attribute)) { + if (! $this->isValidAttribute($attribute)) { return false; } $attributeSchema = $this->schema[$attribute]; if (count($values) > $this->maxValuesCount) { - $this->message = 'Query on attribute has greater than ' . $this->maxValuesCount . ' values: ' . $attribute; + $this->message = 'Query on attribute has greater than '.$this->maxValuesCount.' values: '.$attribute; + return false; } @@ -65,8 +66,9 @@ class Filter extends Base default => gettype($value) === $attributeType }; - if (!$condition) { - $this->message = 'Query type does not match expected: ' . $attributeType; + if (! $condition) { + $this->message = 'Query type does not match expected: '.$attributeType; + return false; } } @@ -81,8 +83,7 @@ class Filter extends Base * * Otherwise, returns false * - * @param Query $value - * + * @param Query $value * @return bool */ public function isValid($query): bool @@ -100,6 +101,7 @@ class Filter extends Base case Query::TYPE_GREATEREQUAL: case Query::TYPE_SEARCH: $values = $query->getValues(); + return $this->isValidAttributeAndValues($attribute, $values); default: diff --git a/src/Appwrite/Utopia/Database/Validator/Query/Limit.php b/src/Appwrite/Utopia/Database/Validator/Query/Limit.php index 232df93666..183b68b4c9 100644 --- a/src/Appwrite/Utopia/Database/Validator/Query/Limit.php +++ b/src/Appwrite/Utopia/Database/Validator/Query/Limit.php @@ -2,7 +2,6 @@ namespace Appwrite\Utopia\Database\Validator\Query; -use Appwrite\Utopia\Database\Validator\Query\Base; use Utopia\Database\Query; use Utopia\Validator\Range; @@ -13,7 +12,7 @@ class Limit extends Base /** * Query constructor * - * @param int $maxLimit + * @param int $maxLimit */ public function __construct(int $maxLimit = 100) { @@ -27,7 +26,8 @@ class Limit extends Base return true; } - $this->message = 'Invalid limit: ' . $validator->getDescription(); + $this->message = 'Invalid limit: '.$validator->getDescription(); + return false; } @@ -36,8 +36,7 @@ class Limit extends Base * * Returns true if method is limit values are within range. * - * @param Query $value - * + * @param Query $value * @return bool */ public function isValid($query): bool @@ -46,11 +45,13 @@ class Limit extends Base $method = $query->getMethod(); if ($method !== Query::TYPE_LIMIT) { - $this->message = 'Query method invalid: ' . $method; + $this->message = 'Query method invalid: '.$method; + return false; } $limit = $query->getValue(); + return $this->isValidLimit($limit); } diff --git a/src/Appwrite/Utopia/Database/Validator/Query/Offset.php b/src/Appwrite/Utopia/Database/Validator/Query/Offset.php index 9f832a7c62..4cab85512e 100644 --- a/src/Appwrite/Utopia/Database/Validator/Query/Offset.php +++ b/src/Appwrite/Utopia/Database/Validator/Query/Offset.php @@ -2,7 +2,6 @@ namespace Appwrite\Utopia\Database\Validator\Query; -use Appwrite\Utopia\Database\Validator\Query\Base; use Utopia\Database\Query; use Utopia\Validator\Range; @@ -13,7 +12,7 @@ class Offset extends Base /** * Query constructor * - * @param int $maxOffset + * @param int $maxOffset */ public function __construct(int $maxOffset = 5000) { @@ -27,7 +26,8 @@ class Offset extends Base return true; } - $this->message = 'Invalid offset: ' . $validator->getDescription(); + $this->message = 'Invalid offset: '.$validator->getDescription(); + return false; } @@ -36,8 +36,7 @@ class Offset extends Base * * Returns true if method is offset and values are within range. * - * @param Query $value - * + * @param Query $value * @return bool */ public function isValid($query): bool @@ -46,11 +45,13 @@ class Offset extends Base $method = $query->getMethod(); if ($method !== Query::TYPE_OFFSET) { - $this->message = 'Query method invalid: ' . $method; + $this->message = 'Query method invalid: '.$method; + return false; } $offset = $query->getValue(); + return $this->isValidOffset($offset); } diff --git a/src/Appwrite/Utopia/Database/Validator/Query/Order.php b/src/Appwrite/Utopia/Database/Validator/Query/Order.php index 0c12d7ac44..36d20b5bb2 100644 --- a/src/Appwrite/Utopia/Database/Validator/Query/Order.php +++ b/src/Appwrite/Utopia/Database/Validator/Query/Order.php @@ -2,9 +2,7 @@ namespace Appwrite\Utopia\Database\Validator\Query; -use Appwrite\Utopia\Database\Validator\Query\Base; use Utopia\Database\Query; -use Utopia\Validator; class Order extends Base { @@ -15,7 +13,6 @@ class Order extends Base /** * Query constructor - * */ public function __construct(array $attributes = []) { @@ -27,8 +24,9 @@ class Order extends Base protected function isValidAttribute($attribute): bool { // Search for attribute in schema - if (!isset($this->schema[$attribute])) { - $this->message = 'Attribute not found in schema: ' . $attribute; + if (! isset($this->schema[$attribute])) { + $this->message = 'Attribute not found in schema: '.$attribute; + return false; } @@ -42,8 +40,7 @@ class Order extends Base * * Otherwise, returns false * - * @param Query $value - * + * @param Query $value * @return bool */ public function isValid($query): bool @@ -55,6 +52,7 @@ class Order extends Base if ($attribute === '') { return true; } + return $this->isValidAttribute($attribute); } diff --git a/src/Appwrite/Utopia/Request.php b/src/Appwrite/Utopia/Request.php index 229c9dd53d..3f4d368e78 100644 --- a/src/Appwrite/Utopia/Request.php +++ b/src/Appwrite/Utopia/Request.php @@ -10,6 +10,7 @@ use Utopia\Swoole\Request as UtopiaRequest; class Request extends UtopiaRequest { private static ?Filter $filter = null; + private static ?Route $route = null; public function __construct(SwooleRequest $request) @@ -18,14 +19,14 @@ class Request extends UtopiaRequest } /** - * @inheritdoc + * {@inheritdoc} */ public function getParams(): array { $parameters = parent::getParams(); if (self::hasFilter() && self::hasRoute()) { - $endpointIdentifier = self::getRoute()->getLabel('sdk.namespace', 'unknown') . '.' . self::getRoute()->getLabel('sdk.method', 'unknown'); + $endpointIdentifier = self::getRoute()->getLabel('sdk.namespace', 'unknown').'.'.self::getRoute()->getLabel('sdk.method', 'unknown'); $parameters = self::getFilter()->parse($parameters, $endpointIdentifier); } @@ -35,8 +36,7 @@ class Request extends UtopiaRequest /** * Function to set a response filter * - * @param Filter|null $filter Filter the response filter to set - * + * @param Filter|null $filter Filter the response filter to set * @return void */ public static function setFilter(?Filter $filter): void @@ -67,8 +67,7 @@ class Request extends UtopiaRequest /** * Function to set a request route * - * @param Route|null $route the request route to set - * + * @param Route|null $route the request route to set * @return void */ public static function setRoute(?Route $route): void diff --git a/src/Appwrite/Utopia/Request/Filter.php b/src/Appwrite/Utopia/Request/Filter.php index 59346c7e17..4c1ea1bfd1 100644 --- a/src/Appwrite/Utopia/Request/Filter.php +++ b/src/Appwrite/Utopia/Request/Filter.php @@ -7,9 +7,8 @@ abstract class Filter /** * Parse params to another format. * - * @param array $content - * @param string $model - * + * @param array $content + * @param string $model * @return array */ abstract public function parse(array $content, string $model): array; diff --git a/src/Appwrite/Utopia/Request/Filters/V12.php b/src/Appwrite/Utopia/Request/Filters/V12.php index f2a65307ae..96fbf62885 100644 --- a/src/Appwrite/Utopia/Request/Filters/V12.php +++ b/src/Appwrite/Utopia/Request/Filters/V12.php @@ -11,44 +11,44 @@ class V12 extends Filter { switch ($model) { // No IDs -> Custom IDs - case "account.create": - case "account.createMagicURLSession": - case "users.create": + case 'account.create': + case 'account.createMagicURLSession': + case 'users.create': $content = $this->addId($content, 'userId'); break; - case "functions.create": + case 'functions.create': $content = $this->addId($content, 'functionId'); break; - case "teams.create": + case 'teams.create': $content = $this->addId($content, 'teamId'); break; - // Status integer -> boolean - case "users.updateStatus": + // Status integer -> boolean + case 'users.updateStatus': $content = $this->convertStatus($content); break; - // Deprecating order type - case "functions.listExecutions": + // Deprecating order type + case 'functions.listExecutions': $content = $this->removeOrderType($content); break; - // The rest (more complex) formats - case "database.createDocument": + // The rest (more complex) formats + case 'database.createDocument': $content = $this->addId($content, 'documentId'); $content = $this->removeParentProperties($content); break; - case "database.listDocuments": + case 'database.listDocuments': $content = $this->removeOrderCast($content); $content = $this->convertOrder($content); $content = $this->convertQueries($content); break; - case "database.createCollection": + case 'database.createCollection': $content = $this->addId($content, 'collectionId'); $content = $this->removeRules($content); $content = $this->addCollectionPermissionLevel($content); break; - case "database.updateCollection": + case 'database.updateCollection': $content = $this->removeRules($content); $content = $this->addCollectionPermissionLevel($content); break; @@ -62,12 +62,14 @@ class V12 extends Filter protected function addId(array $content, string $key): array { $content[$key] = 'unique()'; + return $content; } protected function addCollectionPermissionLevel(array $content): array { $content['permission'] = 'document'; + return $content; } @@ -76,18 +78,21 @@ class V12 extends Filter protected function removeRules(array $content): array { unset($content['rules']); + return $content; } protected function removeOrderType(array $content): array { unset($content['orderType']); + return $content; } protected function removeOrderCast(array $content): array { unset($content['orderCast']); + return $content; } @@ -102,6 +107,7 @@ class V12 extends Filter if (isset($content['parentPropertyType'])) { unset($content['parentPropertyType']); } + return $content; } @@ -112,18 +118,19 @@ class V12 extends Filter if (isset($content['status'])) { $content['status'] = $content['status'] === 2 ? false : true; } + return $content; } protected function convertOrder(array $content): array { if (isset($content['orderField'])) { - $content['orderAttributes'] = [ $content['orderField'] ]; + $content['orderAttributes'] = [$content['orderField']]; unset($content['orderField']); } if (isset($content['orderType'])) { - $content['orderTypes'] = [ $content['orderType'] ]; + $content['orderTypes'] = [$content['orderType']]; unset($content['orderType']); } @@ -134,7 +141,7 @@ class V12 extends Filter { $queries = []; - if (!empty($content['filters'])) { + if (! empty($content['filters'])) { foreach ($content['filters'] as $filter) { $operators = ['=' => 'equal', '!=' => 'notEqual', '>' => 'greater', '<' => 'lesser', '<=' => 'lesserEqual', '>=' => 'greaterEqual']; foreach ($operators as $operator => $operatorVerbose) { @@ -151,10 +158,10 @@ class V12 extends Filter // Let's keep it at true and false string, but without "" around // No action needed } else { - $filterValue = \is_numeric($filterValue) ? $filterValue : '"' . $filterValue . '"'; + $filterValue = \is_numeric($filterValue) ? $filterValue : '"'.$filterValue.'"'; } - $query = $attributeKey . '.' . $operators[$usedOperator] . '(' . $filterValue . ')'; + $query = $attributeKey.'.'.$operators[$usedOperator].'('.$filterValue.')'; \array_push($queries, $query); } } diff --git a/src/Appwrite/Utopia/Request/Filters/V13.php b/src/Appwrite/Utopia/Request/Filters/V13.php index e1122fdd71..3f297b5943 100644 --- a/src/Appwrite/Utopia/Request/Filters/V13.php +++ b/src/Appwrite/Utopia/Request/Filters/V13.php @@ -11,13 +11,13 @@ class V13 extends Filter { switch ($model) { // Replaced Types - case "database.createIntegerAttribute": - case "database.createFloatAttribute": - $content = $this->convertStringToNum($content, "min"); - $content = $this->convertStringToNum($content, "max"); - $content = $this->convertStringToNum($content, "default"); + case 'database.createIntegerAttribute': + case 'database.createFloatAttribute': + $content = $this->convertStringToNum($content, 'min'); + $content = $this->convertStringToNum($content, 'max'); + $content = $this->convertStringToNum($content, 'default'); break; - case "functions.createExecution": + case 'functions.createExecution': $content = $this->convertExecution($content); } @@ -26,13 +26,15 @@ class V13 extends Filter private function convertStringToNum($content, $value) { - $content[$value] = is_null($content[$value]) ? null : (int)$content[$value]; + $content[$value] = is_null($content[$value]) ? null : (int) $content[$value]; + return $content; } private function convertExecution($content) { $content['async'] = true; + return $content; } } diff --git a/src/Appwrite/Utopia/Request/Filters/V14.php b/src/Appwrite/Utopia/Request/Filters/V14.php index 7130307f0d..1b50404f82 100644 --- a/src/Appwrite/Utopia/Request/Filters/V14.php +++ b/src/Appwrite/Utopia/Request/Filters/V14.php @@ -2,8 +2,8 @@ namespace Appwrite\Utopia\Request\Filters; -use Appwrite\Utopia\Request\Filter; use Appwrite\Migration\Version\V13 as MigrationV13; +use Appwrite\Utopia\Request\Filter; class V14 extends Filter { @@ -11,10 +11,10 @@ class V14 extends Filter public function parse(array $content, string $model): array { switch ($model) { - case "functions.create": - case "functions.update": - case "projects.createWebhook": - case "projects.updateWebhook": + case 'functions.create': + case 'functions.update': + case 'projects.createWebhook': + case 'projects.updateWebhook': $content = $this->convertEvents($content); break; } @@ -27,7 +27,7 @@ class V14 extends Filter $migration = new MigrationV13(); $events = $content['events'] ?? []; - $content['events'] = $migration->migrateEvents($events); + $content['events'] = $migration->migrateEvents($events); return $content; } diff --git a/src/Appwrite/Utopia/Request/Filters/V15.php b/src/Appwrite/Utopia/Request/Filters/V15.php index 50e5ec0db7..fc8f7bc495 100644 --- a/src/Appwrite/Utopia/Request/Filters/V15.php +++ b/src/Appwrite/Utopia/Request/Filters/V15.php @@ -5,8 +5,8 @@ namespace Appwrite\Utopia\Request\Filters; use Appwrite\Utopia\Request\Filter; use Utopia\Database\Database; use Utopia\Database\Helpers\Permission; -use Utopia\Database\Query; use Utopia\Database\Helpers\Role; +use Utopia\Database\Query; class V15 extends Filter { @@ -81,11 +81,11 @@ class V15 extends Filter protected function convertLimitAndOffset($content) { if (isset($content['limit'])) { - $content['queries'][] = 'limit(' . $content['limit'] . ')'; + $content['queries'][] = 'limit('.$content['limit'].')'; } if (isset($content['offset'])) { - $content['queries'][] = 'offset(' . $content['offset'] . ')'; + $content['queries'][] = 'offset('.$content['offset'].')'; } unset($content['limit']); @@ -100,9 +100,9 @@ class V15 extends Filter $cursorDirection = $content['cursorDirection'] ?? Database::CURSOR_AFTER; if ($cursorDirection === Database::CURSOR_BEFORE) { - $content['queries'][] = 'cursorBefore("' . $content["cursor"] . '")'; + $content['queries'][] = 'cursorBefore("'.$content['cursor'].'")'; } else { - $content['queries'][] = 'cursorAfter("' . $content["cursor"] . '")'; + $content['queries'][] = 'cursorAfter("'.$content['cursor'].'")'; } } @@ -133,9 +133,9 @@ class V15 extends Filter $attribute = $content['orderAttributes'][$i] ?? ''; if ($type === Database::ORDER_DESC) { - $content['queries'][] = 'orderDesc("' . $attribute . '")'; + $content['queries'][] = 'orderDesc("'.$attribute.'")'; } else { - $content['queries'][] = 'orderAsc("' . $attribute . '")'; + $content['queries'][] = 'orderAsc("'.$attribute.'")'; } } } @@ -194,7 +194,7 @@ class V15 extends Filter protected function convertFilters($content) { - if (!isset($content['queries'])) { + if (! isset($content['queries'])) { return $content; } @@ -214,18 +214,19 @@ class V15 extends Filter $parts = explode($middle, $query); if (count($parts) > 1) { $attribute = $parts[0]; - $value = rtrim($parts[1], ")"); - $content['queries'][$i] = $newOperation . '("' . $attribute . '", [' . $value . '])'; + $value = rtrim($parts[1], ')'); + $content['queries'][$i] = $newOperation.'("'.$attribute.'", ['.$value.'])'; } } } } + return $content; } protected function convertExecute($content) { - if (!isset($content['execute'])) { + if (! isset($content['execute'])) { return $content; } @@ -247,7 +248,7 @@ class V15 extends Filter protected function convertExpire($content) { - if (!isset($content['expire'])) { + if (! isset($content['expire'])) { return $content; } diff --git a/src/Appwrite/Utopia/Response.php b/src/Appwrite/Utopia/Response.php index 2ab514f91c..af62b43144 100644 --- a/src/Appwrite/Utopia/Response.php +++ b/src/Appwrite/Utopia/Response.php @@ -2,11 +2,6 @@ namespace Appwrite\Utopia; -use Exception; -use Swoole\Http\Request as SwooleRequest; -use Utopia\Swoole\Response as SwooleResponse; -use Swoole\Http\Response as SwooleHTTPResponse; -use Utopia\Database\Document; use Appwrite\Utopia\Response\Filter; use Appwrite\Utopia\Response\Model; use Appwrite\Utopia\Response\Model\Account; @@ -17,72 +12,74 @@ use Appwrite\Utopia\Response\Model\AlgoPhpass; use Appwrite\Utopia\Response\Model\AlgoScrypt; use Appwrite\Utopia\Response\Model\AlgoScryptModified; use Appwrite\Utopia\Response\Model\AlgoSha; -use Appwrite\Utopia\Response\Model\None; use Appwrite\Utopia\Response\Model\Any; use Appwrite\Utopia\Response\Model\Attribute; -use Appwrite\Utopia\Response\Model\AttributeList; -use Appwrite\Utopia\Response\Model\AttributeString; -use Appwrite\Utopia\Response\Model\AttributeInteger; -use Appwrite\Utopia\Response\Model\AttributeFloat; use Appwrite\Utopia\Response\Model\AttributeBoolean; +use Appwrite\Utopia\Response\Model\AttributeDatetime; use Appwrite\Utopia\Response\Model\AttributeEmail; use Appwrite\Utopia\Response\Model\AttributeEnum; +use Appwrite\Utopia\Response\Model\AttributeFloat; +use Appwrite\Utopia\Response\Model\AttributeInteger; use Appwrite\Utopia\Response\Model\AttributeIP; +use Appwrite\Utopia\Response\Model\AttributeList; +use Appwrite\Utopia\Response\Model\AttributeString; use Appwrite\Utopia\Response\Model\AttributeURL; -use Appwrite\Utopia\Response\Model\AttributeDatetime; use Appwrite\Utopia\Response\Model\BaseList; +use Appwrite\Utopia\Response\Model\Bucket; +use Appwrite\Utopia\Response\Model\Build; use Appwrite\Utopia\Response\Model\Collection; -use Appwrite\Utopia\Response\Model\Database; use Appwrite\Utopia\Response\Model\Continent; use Appwrite\Utopia\Response\Model\Country; use Appwrite\Utopia\Response\Model\Currency; +use Appwrite\Utopia\Response\Model\Database; +use Appwrite\Utopia\Response\Model\Deployment; use Appwrite\Utopia\Response\Model\Document as ModelDocument; use Appwrite\Utopia\Response\Model\Domain; use Appwrite\Utopia\Response\Model\Error; use Appwrite\Utopia\Response\Model\ErrorDev; use Appwrite\Utopia\Response\Model\Execution; -use Appwrite\Utopia\Response\Model\Build; use Appwrite\Utopia\Response\Model\File; -use Appwrite\Utopia\Response\Model\Bucket; use Appwrite\Utopia\Response\Model\Func; -use Appwrite\Utopia\Response\Model\Index; -use Appwrite\Utopia\Response\Model\JWT; -use Appwrite\Utopia\Response\Model\Key; -use Appwrite\Utopia\Response\Model\Language; -use Appwrite\Utopia\Response\Model\User; -use Appwrite\Utopia\Response\Model\Session; -use Appwrite\Utopia\Response\Model\Team; -use Appwrite\Utopia\Response\Model\Locale; -use Appwrite\Utopia\Response\Model\Log; -use Appwrite\Utopia\Response\Model\Membership; -use Appwrite\Utopia\Response\Model\Metric; -use Appwrite\Utopia\Response\Model\Permissions; -use Appwrite\Utopia\Response\Model\Phone; -use Appwrite\Utopia\Response\Model\Platform; -use Appwrite\Utopia\Response\Model\Project; -use Appwrite\Utopia\Response\Model\Rule; -use Appwrite\Utopia\Response\Model\Deployment; -use Appwrite\Utopia\Response\Model\Token; -use Appwrite\Utopia\Response\Model\Webhook; -use Appwrite\Utopia\Response\Model\Preferences; use Appwrite\Utopia\Response\Model\HealthAntivirus; use Appwrite\Utopia\Response\Model\HealthQueue; use Appwrite\Utopia\Response\Model\HealthStatus; use Appwrite\Utopia\Response\Model\HealthTime; use Appwrite\Utopia\Response\Model\HealthVersion; -use Appwrite\Utopia\Response\Model\Mock; // Keep last +use Appwrite\Utopia\Response\Model\Index; +use Appwrite\Utopia\Response\Model\JWT; +use Appwrite\Utopia\Response\Model\Key; +use Appwrite\Utopia\Response\Model\Language; +use Appwrite\Utopia\Response\Model\Locale; +use Appwrite\Utopia\Response\Model\Log; +use Appwrite\Utopia\Response\Model\Membership; +use Appwrite\Utopia\Response\Model\Metric; +use Appwrite\Utopia\Response\Model\Mock; +use Appwrite\Utopia\Response\Model\None; +use Appwrite\Utopia\Response\Model\Phone; +use Appwrite\Utopia\Response\Model\Platform; +use Appwrite\Utopia\Response\Model\Preferences; +use Appwrite\Utopia\Response\Model\Project; use Appwrite\Utopia\Response\Model\Provider; use Appwrite\Utopia\Response\Model\Runtime; +use Appwrite\Utopia\Response\Model\Session; +use Appwrite\Utopia\Response\Model\Team; +use Appwrite\Utopia\Response\Model\Token; use Appwrite\Utopia\Response\Model\UsageBuckets; use Appwrite\Utopia\Response\Model\UsageCollection; use Appwrite\Utopia\Response\Model\UsageDatabase; -use Appwrite\Utopia\Response\Model\UsageDatabases; +use Appwrite\Utopia\Response\Model\UsageDatabases; // Keep last use Appwrite\Utopia\Response\Model\UsageFunction; use Appwrite\Utopia\Response\Model\UsageFunctions; use Appwrite\Utopia\Response\Model\UsageProject; use Appwrite\Utopia\Response\Model\UsageStorage; use Appwrite\Utopia\Response\Model\UsageUsers; +use Appwrite\Utopia\Response\Model\User; use Appwrite\Utopia\Response\Model\Variable; +use Appwrite\Utopia\Response\Model\Webhook; +use Exception; +use Swoole\Http\Response as SwooleHTTPResponse; +use Utopia\Database\Document; +use Utopia\Swoole\Response as SwooleResponse; /** * @method int getStatusCode() @@ -92,130 +89,222 @@ class Response extends SwooleResponse { // General public const MODEL_NONE = 'none'; + public const MODEL_ANY = 'any'; + public const MODEL_LOG = 'log'; + public const MODEL_LOG_LIST = 'logList'; + public const MODEL_ERROR = 'error'; + public const MODEL_METRIC = 'metric'; + public const MODEL_METRIC_LIST = 'metricList'; + public const MODEL_ERROR_DEV = 'errorDev'; + public const MODEL_BASE_LIST = 'baseList'; + public const MODEL_USAGE_DATABASES = 'usageDatabases'; + public const MODEL_USAGE_DATABASE = 'usageDatabase'; + public const MODEL_USAGE_COLLECTION = 'usageCollection'; + public const MODEL_USAGE_USERS = 'usageUsers'; + public const MODEL_USAGE_BUCKETS = 'usageBuckets'; + public const MODEL_USAGE_STORAGE = 'usageStorage'; + public const MODEL_USAGE_FUNCTIONS = 'usageFunctions'; + public const MODEL_USAGE_FUNCTION = 'usageFunction'; + public const MODEL_USAGE_PROJECT = 'usageProject'; // Database public const MODEL_DATABASE = 'database'; + public const MODEL_DATABASE_LIST = 'databaseList'; + public const MODEL_COLLECTION = 'collection'; + public const MODEL_COLLECTION_LIST = 'collectionList'; + public const MODEL_INDEX = 'index'; + public const MODEL_INDEX_LIST = 'indexList'; + public const MODEL_DOCUMENT = 'document'; + public const MODEL_DOCUMENT_LIST = 'documentList'; // Database Attributes public const MODEL_ATTRIBUTE = 'attribute'; + public const MODEL_ATTRIBUTE_LIST = 'attributeList'; + public const MODEL_ATTRIBUTE_STRING = 'attributeString'; + public const MODEL_ATTRIBUTE_INTEGER = 'attributeInteger'; + public const MODEL_ATTRIBUTE_FLOAT = 'attributeFloat'; + public const MODEL_ATTRIBUTE_BOOLEAN = 'attributeBoolean'; + public const MODEL_ATTRIBUTE_EMAIL = 'attributeEmail'; + public const MODEL_ATTRIBUTE_ENUM = 'attributeEnum'; + public const MODEL_ATTRIBUTE_IP = 'attributeIp'; + public const MODEL_ATTRIBUTE_URL = 'attributeUrl'; + public const MODEL_ATTRIBUTE_DATETIME = 'attributeDatetime'; // Users public const MODEL_ACCOUNT = 'account'; + public const MODEL_USER = 'user'; + public const MODEL_USER_LIST = 'userList'; + public const MODEL_SESSION = 'session'; + public const MODEL_SESSION_LIST = 'sessionList'; + public const MODEL_TOKEN = 'token'; + public const MODEL_JWT = 'jwt'; + public const MODEL_PREFERENCES = 'preferences'; // Users password algos public const MODEL_ALGO_MD5 = 'algoMd5'; + public const MODEL_ALGO_SHA = 'algoSha'; + public const MODEL_ALGO_SCRYPT = 'algoScrypt'; + public const MODEL_ALGO_SCRYPT_MODIFIED = 'algoScryptModified'; + public const MODEL_ALGO_BCRYPT = 'algoBcrypt'; + public const MODEL_ALGO_ARGON2 = 'algoArgon2'; + public const MODEL_ALGO_PHPASS = 'algoPhpass'; // Storage public const MODEL_FILE = 'file'; + public const MODEL_FILE_LIST = 'fileList'; + public const MODEL_BUCKET = 'bucket'; + public const MODEL_BUCKET_LIST = 'bucketList'; // Locale public const MODEL_LOCALE = 'locale'; + public const MODEL_COUNTRY = 'country'; + public const MODEL_COUNTRY_LIST = 'countryList'; + public const MODEL_CONTINENT = 'continent'; + public const MODEL_CONTINENT_LIST = 'continentList'; + public const MODEL_CURRENCY = 'currency'; + public const MODEL_CURRENCY_LIST = 'currencyList'; + public const MODEL_LANGUAGE = 'language'; + public const MODEL_LANGUAGE_LIST = 'languageList'; + public const MODEL_PHONE = 'phone'; + public const MODEL_PHONE_LIST = 'phoneList'; // Teams public const MODEL_TEAM = 'team'; + public const MODEL_TEAM_LIST = 'teamList'; + public const MODEL_MEMBERSHIP = 'membership'; + public const MODEL_MEMBERSHIP_LIST = 'membershipList'; // Functions public const MODEL_FUNCTION = 'function'; + public const MODEL_FUNCTION_LIST = 'functionList'; + public const MODEL_RUNTIME = 'runtime'; + public const MODEL_RUNTIME_LIST = 'runtimeList'; + public const MODEL_DEPLOYMENT = 'deployment'; + public const MODEL_DEPLOYMENT_LIST = 'deploymentList'; + public const MODEL_EXECUTION = 'execution'; + public const MODEL_EXECUTION_LIST = 'executionList'; + public const MODEL_BUILD = 'build'; + public const MODEL_BUILD_LIST = 'buildList'; // Not used anywhere yet + public const MODEL_FUNC_PERMISSIONS = 'funcPermissions'; // Project public const MODEL_PROJECT = 'project'; + public const MODEL_PROJECT_LIST = 'projectList'; + public const MODEL_WEBHOOK = 'webhook'; + public const MODEL_WEBHOOK_LIST = 'webhookList'; + public const MODEL_KEY = 'key'; + public const MODEL_KEY_LIST = 'keyList'; + public const MODEL_PROVIDER = 'provider'; + public const MODEL_PROVIDER_LIST = 'providerList'; + public const MODEL_PLATFORM = 'platform'; + public const MODEL_PLATFORM_LIST = 'platformList'; + public const MODEL_DOMAIN = 'domain'; + public const MODEL_DOMAIN_LIST = 'domainList'; + public const MODEL_VARIABLE = 'variable'; + public const MODEL_VARIABLE_LIST = 'variableList'; // Health public const MODEL_HEALTH_STATUS = 'healthStatus'; + public const MODEL_HEALTH_VERSION = 'healthVersion'; + public const MODEL_HEALTH_QUEUE = 'healthQueue'; + public const MODEL_HEALTH_TIME = 'healthTime'; + public const MODEL_HEALTH_ANTIVIRUS = 'healthAntivirus'; // Deprecated public const MODEL_PERMISSIONS = 'permissions'; + public const MODEL_RULE = 'rule'; + public const MODEL_TASK = 'task'; // Tests (keep last) @@ -234,7 +323,7 @@ class Response extends SwooleResponse /** * Response constructor. * - * @param float $time + * @param float $time */ public function __construct(SwooleHTTPResponse $response) { @@ -353,6 +442,7 @@ class Response extends SwooleResponse * HTTP content types */ public const CONTENT_TYPE_YAML = 'application/x-yaml'; + public const CONTENT_TYPE_NULL = 'null'; /** @@ -375,14 +465,15 @@ class Response extends SwooleResponse /** * Get Model Object * - * @param string $key + * @param string $key * @return Model + * * @throws Exception */ public function getModel(string $key): Model { - if (!isset($this->models[$key])) { - throw new Exception('Undefined model: ' . $key); + if (! isset($this->models[$key])) { + throw new Exception('Undefined model: '.$key); } return $this->models[$key]; @@ -402,10 +493,11 @@ class Response extends SwooleResponse * Validate response objects and outputs * the response according to given format type * - * @param Document $document - * @param string $model + * @param Document $document + * @param string $model * * return void + * * @throws Exception */ public function dynamic(Document $document, string $model): void @@ -419,11 +511,11 @@ class Response extends SwooleResponse switch ($this->getContentType()) { case self::CONTENT_TYPE_JSON: - $this->json(!empty($output) ? $output : new \stdClass()); + $this->json(! empty($output) ? $output : new \stdClass()); break; case self::CONTENT_TYPE_YAML: - $this->yaml(!empty($output) ? $output : new \stdClass()); + $this->yaml(! empty($output) ? $output : new \stdClass()); break; case self::CONTENT_TYPE_NULL: @@ -433,7 +525,7 @@ class Response extends SwooleResponse if ($model === self::MODEL_NONE) { $this->noContent(); } else { - $this->json(!empty($output) ? $output : new \stdClass()); + $this->json(! empty($output) ? $output : new \stdClass()); } break; } @@ -442,18 +534,19 @@ class Response extends SwooleResponse /** * Generate valid response object from document data * - * @param Document $document - * @param string $model + * @param Document $document + * @param string $model * * return array * @return array + * * @throws Exception */ public function output(Document $document, string $model): array { - $data = $document; - $model = $this->getModel($model); - $output = []; + $data = $document; + $model = $this->getModel($model); + $output = []; $document = $model->filter($document); @@ -464,17 +557,17 @@ class Response extends SwooleResponse } foreach ($model->getRules() as $key => $rule) { - if (!$document->isSet($key) && $rule['required']) { // do not set attribute in response if not required + if (! $document->isSet($key) && $rule['required']) { // do not set attribute in response if not required if (\array_key_exists('default', $rule)) { $document->setAttribute($key, $rule['default']); } else { - throw new Exception('Model ' . $model->getName() . ' is missing response key: ' . $key); + throw new Exception('Model '.$model->getName().' is missing response key: '.$key); } } if ($rule['array']) { - if (!is_array($data[$key])) { - throw new Exception($key . ' must be an array of type ' . $rule['type']); + if (! is_array($data[$key])) { + throw new Exception($key.' must be an array of type '.$rule['type']); } foreach ($data[$key] as $index => $item) { @@ -484,7 +577,7 @@ class Response extends SwooleResponse $condition = false; foreach ($this->getModel($type)->conditions as $attribute => $val) { $condition = $item->getAttribute($attribute) === $val; - if (!$condition) { + if (! $condition) { break; } } @@ -497,8 +590,8 @@ class Response extends SwooleResponse $ruleType = $rule['type']; } - if (!array_key_exists($ruleType, $this->models)) { - throw new Exception('Missing model for rule: ' . $ruleType); + if (! array_key_exists($ruleType, $this->models)) { + throw new Exception('Missing model for rule: '.$ruleType); } $data[$key][$index] = $this->output($item, $ruleType); @@ -523,14 +616,13 @@ class Response extends SwooleResponse * * Generate HTTP response output including the response header (+cookies) and body and prints them. * - * @param string $body - * + * @param string $body * @return void */ public function file(string $body = ''): void { $this->payload = [ - 'payload' => $body + 'payload' => $body, ]; $this->send($body); @@ -544,14 +636,14 @@ class Response extends SwooleResponse * * @see https://en.wikipedia.org/wiki/YAML * - * @param array $data - * + * @param array $data * @return void + * * @throws Exception */ public function yaml(array $data): void { - if (!extension_loaded('yaml')) { + if (! extension_loaded('yaml')) { throw new Exception('Missing yaml extension. Learn more at: https://www.php.net/manual/en/book.yaml.php'); } @@ -572,7 +664,6 @@ class Response extends SwooleResponse * Function to set a response filter * * @param $filter the response filter to set - * * @return void */ public static function setFilter(?Filter $filter) diff --git a/src/Appwrite/Utopia/Response/Filter.php b/src/Appwrite/Utopia/Response/Filter.php index 9110abd07a..47cca955fe 100644 --- a/src/Appwrite/Utopia/Response/Filter.php +++ b/src/Appwrite/Utopia/Response/Filter.php @@ -7,9 +7,8 @@ abstract class Filter /** * Parse the content to another format. * - * @param array $content - * @param string $model - * + * @param array $content + * @param string $model * @return array */ abstract public function parse(array $content, string $model): array; diff --git a/src/Appwrite/Utopia/Response/Filters/V11.php b/src/Appwrite/Utopia/Response/Filters/V11.php index 8fa22f42b2..09f9fbfc06 100644 --- a/src/Appwrite/Utopia/Response/Filters/V11.php +++ b/src/Appwrite/Utopia/Response/Filters/V11.php @@ -42,7 +42,7 @@ class V11 extends Filter $parsedResponse = $this->parseFunctionsList($content); break; - // Convert status from boolean to int + // Convert status from boolean to int case Response::MODEL_USER: $parsedResponse = $this->parseStatus($content); break; @@ -50,7 +50,7 @@ class V11 extends Filter $parsedResponse = $this->parseUserList($content); break; - // Convert all Health responses back to original + // Convert all Health responses back to original case Response::MODEL_HEALTH_STATUS: $parsedResponse = $this->parseHealthStatus($content); break; @@ -67,7 +67,7 @@ class V11 extends Filter $parsedResponse = $this->parseHealthAntivirus($content); break; - // Complex filters + // Complex filters case Response::MODEL_COLLECTION: $parsedResponse = $this->parseCollection($content); break; @@ -101,6 +101,7 @@ class V11 extends Filter $parsedResponse[] = $this->parsePermissions($document); } $content['documents'] = $parsedResponse; + return $content; } @@ -112,6 +113,7 @@ class V11 extends Filter $parsedResponse[] = $this->parsePermissions($file); } $content['files'] = $parsedResponse; + return $content; } @@ -123,6 +125,7 @@ class V11 extends Filter $parsedResponse[] = $this->parseExecutionPermissions($execution); } $content['executions'] = $parsedResponse; + return $content; } @@ -134,6 +137,7 @@ class V11 extends Filter $parsedResponse[] = $this->parseFunctionPermissions($function); } $content['functions'] = $parsedResponse; + return $content; } @@ -145,6 +149,7 @@ class V11 extends Filter $parsedResponse[] = $this->parseStatus($user); } $content['users'] = $parsedResponse; + return $content; } @@ -159,6 +164,7 @@ class V11 extends Filter $parsedResponse = $this->addDate($content, 'dateCreated'); $parsedResponse = $this->addDate($content, 'dateUpdated'); $parsedResponse = $this->parseAttributes($content); + return $parsedResponse; } @@ -170,6 +176,7 @@ class V11 extends Filter $parsedResponse[] = $this->parseCollection($collection); } $content['collections'] = $parsedResponse; + return $content; } @@ -181,6 +188,7 @@ class V11 extends Filter $parsedResponse = $this->removeRule($content, 'userName'); $parsedResponse = $this->removeRule($content, 'mode'); $parsedResponse = $this->removeRule($content, 'sum'); + return $parsedResponse; } @@ -192,6 +200,7 @@ class V11 extends Filter $parsedResponse[] = $this->parseLog($log); } $content['logs'] = $parsedResponse; + return $content; } @@ -203,6 +212,7 @@ class V11 extends Filter $parsedResponse = $this->parseOAuths($content); $parsedResponse = $this->parseAuthsStatus($content); $parsedResponse = $this->removeServicesStatus($content); + return $parsedResponse; } @@ -214,6 +224,7 @@ class V11 extends Filter $parsedResponse[] = $this->parseProject($project); } $content['projects'] = $parsedResponse; + return $content; } @@ -248,7 +259,6 @@ class V11 extends Filter return $content; } - protected function parseHealthQueue(array $content) { // Did not change @@ -303,15 +313,15 @@ class V11 extends Filter protected function parseOAuths(array $content) { - $regexPattern = "/provider([a-zA-Z0-9]+)(Appid|Secret)/"; + $regexPattern = '/provider([a-zA-Z0-9]+)(Appid|Secret)/'; foreach ($content as $key => $value) { \preg_match_all($regexPattern, $key, $regexGroups); if (\count($regexGroups[1]) > 0 && \count($regexGroups[2]) > 0) { $providerName = $regexGroups[1][0]; $valueKey = $regexGroups[2][0]; - $content['usersOauth2' . $providerName . $valueKey] = $value; - unset($content['provider' . $providerName . $valueKey]); + $content['usersOauth2'.$providerName.$valueKey] = $value; + unset($content['provider'.$providerName.$valueKey]); } } @@ -320,7 +330,7 @@ class V11 extends Filter protected function parseAuthsStatus(array $content) { - $regexPattern = "/auth([a-zA-Z0-9]+)/"; + $regexPattern = '/auth([a-zA-Z0-9]+)/'; foreach ($content as $key => $value) { \preg_match_all($regexPattern, $key, $regexGroups); @@ -328,7 +338,7 @@ class V11 extends Filter $providerName = $regexGroups[1][0]; $content[$providerName] = $value; - unset($content['auth' . $providerName]); + unset($content['auth'.$providerName]); } } @@ -377,15 +387,16 @@ class V11 extends Filter protected function parsePermissions(array $content) { - $content['$permissions'] = [ 'read' => $content['$read'], 'write' => $content['$write'] ]; + $content['$permissions'] = ['read' => $content['$read'], 'write' => $content['$write']]; unset($content['$read']); unset($content['$write']); + return $content; } protected function parseFunctionPermissions(array $content) { - $content['$permissions'] = [ 'execute' => $content['execute'] ]; + $content['$permissions'] = ['execute' => $content['execute']]; unset($content['execute']); return $content; @@ -393,7 +404,7 @@ class V11 extends Filter protected function parseExecutionPermissions(array $content) { - $content['$permissions'] = [ 'read' => $content['$read'] ]; + $content['$permissions'] = ['read' => $content['$read']]; unset($content['$read']); return $content; diff --git a/src/Appwrite/Utopia/Response/Filters/V12.php b/src/Appwrite/Utopia/Response/Filters/V12.php index 79d22ad044..795135bf43 100644 --- a/src/Appwrite/Utopia/Response/Filters/V12.php +++ b/src/Appwrite/Utopia/Response/Filters/V12.php @@ -99,6 +99,7 @@ class V12 extends Filter protected function parseError(array $content) { unset($content['type']); + return $content; } @@ -124,6 +125,7 @@ class V12 extends Filter $content['sessions'] = $parsedResponse; $content['sum'] = $content['total']; unset($content['total']); + return $content; } @@ -146,6 +148,7 @@ class V12 extends Filter $content['files'] = $parsedResponse; $content['sum'] = $content['total']; unset($content['total']); + return $content; } @@ -153,6 +156,7 @@ class V12 extends Filter { $content['tag'] = $content['deployment']; unset($content['deployment']); + return $content; } @@ -166,6 +170,7 @@ class V12 extends Filter $content['functions'] = $parsedResponse; $content['sum'] = $content['total']; unset($content['total']); + return $content; } @@ -173,6 +178,7 @@ class V12 extends Filter { $content['functionId'] = $content['resourceId']; $content['command'] = $content['entrypoint']; + return $content; } @@ -186,12 +192,14 @@ class V12 extends Filter $content['deployments'] = $parsedResponse; $content['sum'] = $content['total']; unset($content['total']); + return $content; } protected function parseUsageBuckets(array $content) { unset($content['filesStorage']); + return $content; } @@ -237,6 +245,7 @@ class V12 extends Filter $content['executions'] = $parsedResponse; $content['sum'] = $content['total']; unset($content['total']); + return $content; } @@ -244,6 +253,7 @@ class V12 extends Filter { $content['sum'] = $content['total']; unset($content['total']); + return $content; } @@ -257,6 +267,7 @@ class V12 extends Filter $content['teams'] = $parsedResponse; $content['sum'] = $content['total']; unset($content['total']); + return $content; } @@ -264,6 +275,7 @@ class V12 extends Filter { $content['sum'] = $content['total']; unset($content['total']); + return $content; } } diff --git a/src/Appwrite/Utopia/Response/Filters/V13.php b/src/Appwrite/Utopia/Response/Filters/V13.php index d48473593e..2c613280ac 100644 --- a/src/Appwrite/Utopia/Response/Filters/V13.php +++ b/src/Appwrite/Utopia/Response/Filters/V13.php @@ -55,6 +55,7 @@ class V13 extends Filter $parsedResponse[] = $this->parseExecution($document); } $content['executions'] = $parsedResponse; + return $content; } @@ -74,6 +75,7 @@ class V13 extends Filter $parsedResponse[] = $this->parseProject($document); } $content['projects'] = $parsedResponse; + return $content; } @@ -98,6 +100,7 @@ class V13 extends Filter $parsedResponse[] = $this->parseMembership($document); } $content['memberships'] = $parsedResponse; + return $content; } } diff --git a/src/Appwrite/Utopia/Response/Filters/V15.php b/src/Appwrite/Utopia/Response/Filters/V15.php index 232feec201..fadf426f1d 100644 --- a/src/Appwrite/Utopia/Response/Filters/V15.php +++ b/src/Appwrite/Utopia/Response/Filters/V15.php @@ -210,11 +210,13 @@ class V15 extends Filter if (array_key_exists($attribute, $content)) { if (empty($content[$attribute])) { $content[$attribute] = 0; + continue; } $content[$attribute] = strtotime($content[$attribute]); } } + return $content; } @@ -225,18 +227,20 @@ class V15 extends Filter unset($content['hashOptions']); $content = $this->parseDatetimeAttributes($content, ['registration', 'passwordUpdate', '$createdAt', '$updatedAt']); + return $content; } protected function parseMetric(array $content) { $content = $this->parseDatetimeAttributes($content, ['date']); + return $content; } protected function parsePermissions(array $content) { - if (!isset($content['$permissions'])) { + if (! isset($content['$permissions'])) { return $content; } @@ -248,10 +252,10 @@ class V15 extends Filter $permission = Permission::parse($permission); $permission_value = $permission->getRole(); if ($permission->getIdentifier()) { - $permission_value .= ':' . $permission->getIdentifier(); + $permission_value .= ':'.$permission->getIdentifier(); } if ($permission->getDimension()) { - $permission_value .= '/' . $permission->getDimension(); + $permission_value .= '/'.$permission->getDimension(); } // Old type permissions meant that 'write' is equivalent to 'create', 'update' and 'delete' @@ -305,6 +309,7 @@ class V15 extends Filter unset($content['documentSecurity']); $content = $this->parsePermissions($content); $content = $this->parseDatetimeAttributes($content, ['$createdAt', '$updatedAt']); + return $content; } @@ -312,6 +317,7 @@ class V15 extends Filter { $content = $this->parsePermissions($content); $content = $this->parseDatetimeAttributes($content, ['$createdAt', '$updatedAt']); + return $content; } @@ -325,6 +331,7 @@ class V15 extends Filter unset($content['$databaseId']); $content = $this->parsePermissionsCreatedAtUpdatedAt($content); + return $content; } @@ -354,6 +361,7 @@ class V15 extends Filter private function parseCreatedAtUpdatedAt($content) { $content = $this->parseDatetimeAttributes($content, ['$createdAt', '$updatedAt']); + return $content; } @@ -386,24 +394,28 @@ class V15 extends Filter private function parseKey($content) { $content = $this->parseDatetimeAttributes($content, ['$createdAt', '$updatedAt', 'expire']); + return $content; } private function parseLog($content) { $content = $this->parseDatetimeAttributes($content, ['time']); + return $content; } private function parseMembership($content) { $content = $this->parseDatetimeAttributes($content, ['$createdAt', '$updatedAt', 'invited', 'joined']); + return $content; } private function parseSession($content) { $content = $this->parseDatetimeAttributes($content, ['$createdAt', 'expire', 'providerAccessTokenExpiry']); + return $content; } diff --git a/src/Appwrite/Utopia/Response/Model.php b/src/Appwrite/Utopia/Response/Model.php index 292d1b07e7..773e35141c 100644 --- a/src/Appwrite/Utopia/Response/Model.php +++ b/src/Appwrite/Utopia/Response/Model.php @@ -7,11 +7,17 @@ use Utopia\Database\Document; abstract class Model { public const TYPE_STRING = 'string'; + public const TYPE_INTEGER = 'integer'; + public const TYPE_FLOAT = 'double'; + public const TYPE_BOOLEAN = 'boolean'; + public const TYPE_JSON = 'json'; + public const TYPE_DATETIME = 'datetime'; + public const TYPE_DATETIME_EXAMPLE = '2020-10-15T06:38:00.000+00:00'; /** @@ -39,7 +45,6 @@ abstract class Model */ public array $conditions = []; - /** * Filter Document Structure * @@ -78,8 +83,8 @@ abstract class Model * Add a New Rule * If rule is an array of documents with varying models * - * @param string $key - * @param array $options + * @param string $key + * @param array $options */ protected function addRule(string $key, array $options): self { @@ -87,7 +92,7 @@ abstract class Model 'required' => true, 'array' => false, 'description' => '', - 'example' => '' + 'example' => '', ], $options); return $this; @@ -97,8 +102,8 @@ abstract class Model * Delete an existing Rule * If rule exists, it will be removed * - * @param string $key - * @param array $options + * @param string $key + * @param array $options */ protected function removeRule(string $key): self { diff --git a/src/Appwrite/Utopia/Response/Model/AlgoArgon2.php b/src/Appwrite/Utopia/Response/Model/AlgoArgon2.php index 3e162bb905..ff2b0f94e0 100644 --- a/src/Appwrite/Utopia/Response/Model/AlgoArgon2.php +++ b/src/Appwrite/Utopia/Response/Model/AlgoArgon2.php @@ -34,8 +34,7 @@ class AlgoArgon2 extends Model 'description' => 'Number of threads used to compute hash.', 'default' => '', 'example' => 3, - ]) - ; + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/AlgoScrypt.php b/src/Appwrite/Utopia/Response/Model/AlgoScrypt.php index 4dda297d71..066f976433 100644 --- a/src/Appwrite/Utopia/Response/Model/AlgoScrypt.php +++ b/src/Appwrite/Utopia/Response/Model/AlgoScrypt.php @@ -39,8 +39,7 @@ class AlgoScrypt extends Model 'description' => 'Length used to compute hash.', 'default' => 64, 'example' => 64, - ]) - ; + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/AlgoScryptModified.php b/src/Appwrite/Utopia/Response/Model/AlgoScryptModified.php index 40b9df1dad..73104eba7a 100644 --- a/src/Appwrite/Utopia/Response/Model/AlgoScryptModified.php +++ b/src/Appwrite/Utopia/Response/Model/AlgoScryptModified.php @@ -33,8 +33,7 @@ class AlgoScryptModified extends Model 'description' => 'Key used to compute hash.', 'default' => '', 'example' => 'XyEKE9RcTDeLEsL/RjwPDBv/RqDl8fb3gpYEOQaPihbxf1ZAtSOHCjuAAa7Q3oHpCYhXSN9tizHgVOwn6krflQ==', - ]) - ; + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/Attribute.php b/src/Appwrite/Utopia/Response/Model/Attribute.php index a05a40766e..d985ea7471 100644 --- a/src/Appwrite/Utopia/Response/Model/Attribute.php +++ b/src/Appwrite/Utopia/Response/Model/Attribute.php @@ -40,8 +40,7 @@ class Attribute extends Model 'default' => false, 'required' => false, 'example' => false, - ]) - ; + ]); } public array $conditions = []; diff --git a/src/Appwrite/Utopia/Response/Model/AttributeBoolean.php b/src/Appwrite/Utopia/Response/Model/AttributeBoolean.php index 94902aa9eb..e96140d0b3 100644 --- a/src/Appwrite/Utopia/Response/Model/AttributeBoolean.php +++ b/src/Appwrite/Utopia/Response/Model/AttributeBoolean.php @@ -3,7 +3,6 @@ namespace Appwrite\Utopia\Response\Model; use Appwrite\Utopia\Response; -use Appwrite\Utopia\Response\Model\Attribute; class AttributeBoolean extends Attribute { @@ -29,13 +28,12 @@ class AttributeBoolean extends Attribute 'description' => 'Default value for attribute when not provided. Cannot be set when attribute is required.', 'default' => null, 'required' => false, - 'example' => false - ]) - ; + 'example' => false, + ]); } public array $conditions = [ - 'type' => self::TYPE_BOOLEAN + 'type' => self::TYPE_BOOLEAN, ]; /** diff --git a/src/Appwrite/Utopia/Response/Model/AttributeDatetime.php b/src/Appwrite/Utopia/Response/Model/AttributeDatetime.php index 16692d215b..187f113f8d 100644 --- a/src/Appwrite/Utopia/Response/Model/AttributeDatetime.php +++ b/src/Appwrite/Utopia/Response/Model/AttributeDatetime.php @@ -37,12 +37,11 @@ class AttributeDatetime extends Attribute 'example' => self::TYPE_DATETIME_EXAMPLE, 'array' => false, 'required' => false, - ]) - ; + ]); } public array $conditions = [ - 'type' => self::TYPE_DATETIME + 'type' => self::TYPE_DATETIME, ]; /** diff --git a/src/Appwrite/Utopia/Response/Model/AttributeEmail.php b/src/Appwrite/Utopia/Response/Model/AttributeEmail.php index cdbd1056ba..ffcdbc6eb1 100644 --- a/src/Appwrite/Utopia/Response/Model/AttributeEmail.php +++ b/src/Appwrite/Utopia/Response/Model/AttributeEmail.php @@ -3,7 +3,6 @@ namespace Appwrite\Utopia\Response\Model; use Appwrite\Utopia\Response; -use Appwrite\Utopia\Response\Model\Attribute; class AttributeEmail extends Attribute { @@ -36,13 +35,12 @@ class AttributeEmail extends Attribute 'default' => null, 'required' => false, 'example' => 'default@example.com', - ]) - ; + ]); } public array $conditions = [ 'type' => self::TYPE_STRING, - 'format' => \APP_DATABASE_ATTRIBUTE_EMAIL + 'format' => \APP_DATABASE_ATTRIBUTE_EMAIL, ]; /** diff --git a/src/Appwrite/Utopia/Response/Model/AttributeEnum.php b/src/Appwrite/Utopia/Response/Model/AttributeEnum.php index 3eab7dfdff..0549c3cbe6 100644 --- a/src/Appwrite/Utopia/Response/Model/AttributeEnum.php +++ b/src/Appwrite/Utopia/Response/Model/AttributeEnum.php @@ -3,7 +3,6 @@ namespace Appwrite\Utopia\Response\Model; use Appwrite\Utopia\Response; -use Appwrite\Utopia\Response\Model\Attribute; class AttributeEnum extends Attribute { @@ -43,13 +42,12 @@ class AttributeEnum extends Attribute 'default' => null, 'required' => false, 'example' => 'element', - ]) - ; + ]); } public array $conditions = [ 'type' => self::TYPE_STRING, - 'format' => \APP_DATABASE_ATTRIBUTE_ENUM + 'format' => \APP_DATABASE_ATTRIBUTE_ENUM, ]; /** diff --git a/src/Appwrite/Utopia/Response/Model/AttributeFloat.php b/src/Appwrite/Utopia/Response/Model/AttributeFloat.php index 1318b8c7b2..28bd88e749 100644 --- a/src/Appwrite/Utopia/Response/Model/AttributeFloat.php +++ b/src/Appwrite/Utopia/Response/Model/AttributeFloat.php @@ -3,7 +3,6 @@ namespace Appwrite\Utopia\Response\Model; use Appwrite\Utopia\Response; -use Appwrite\Utopia\Response\Model\Attribute; class AttributeFloat extends Attribute { @@ -44,8 +43,7 @@ class AttributeFloat extends Attribute 'default' => null, 'required' => false, 'example' => 2.5, - ]) - ; + ]); } public array $conditions = [ diff --git a/src/Appwrite/Utopia/Response/Model/AttributeIP.php b/src/Appwrite/Utopia/Response/Model/AttributeIP.php index a692664c34..2e746d735a 100644 --- a/src/Appwrite/Utopia/Response/Model/AttributeIP.php +++ b/src/Appwrite/Utopia/Response/Model/AttributeIP.php @@ -3,7 +3,6 @@ namespace Appwrite\Utopia\Response\Model; use Appwrite\Utopia\Response; -use Appwrite\Utopia\Response\Model\Attribute; class AttributeIP extends Attribute { @@ -36,13 +35,12 @@ class AttributeIP extends Attribute 'default' => null, 'required' => false, 'example' => '192.0.2.0', - ]) - ; + ]); } public array $conditions = [ 'type' => self::TYPE_STRING, - 'format' => \APP_DATABASE_ATTRIBUTE_IP + 'format' => \APP_DATABASE_ATTRIBUTE_IP, ]; /** diff --git a/src/Appwrite/Utopia/Response/Model/AttributeInteger.php b/src/Appwrite/Utopia/Response/Model/AttributeInteger.php index 50c3641445..f672592553 100644 --- a/src/Appwrite/Utopia/Response/Model/AttributeInteger.php +++ b/src/Appwrite/Utopia/Response/Model/AttributeInteger.php @@ -3,7 +3,6 @@ namespace Appwrite\Utopia\Response\Model; use Appwrite\Utopia\Response; -use Appwrite\Utopia\Response\Model\Attribute; class AttributeInteger extends Attribute { @@ -44,8 +43,7 @@ class AttributeInteger extends Attribute 'default' => null, 'required' => false, 'example' => 10, - ]) - ; + ]); } public array $conditions = [ @@ -54,6 +52,7 @@ class AttributeInteger extends Attribute /** * Get Name * + * * @return string */ public function getName(): string diff --git a/src/Appwrite/Utopia/Response/Model/AttributeList.php b/src/Appwrite/Utopia/Response/Model/AttributeList.php index 92ce9cd6cd..fa1f43282b 100644 --- a/src/Appwrite/Utopia/Response/Model/AttributeList.php +++ b/src/Appwrite/Utopia/Response/Model/AttributeList.php @@ -4,7 +4,6 @@ namespace Appwrite\Utopia\Response\Model; use Appwrite\Utopia\Response; use Appwrite\Utopia\Response\Model; -use Utopia\Database\Document; class AttributeList extends Model { @@ -27,13 +26,12 @@ class AttributeList extends Model Response::MODEL_ATTRIBUTE_URL, Response::MODEL_ATTRIBUTE_IP, Response::MODEL_ATTRIBUTE_DATETIME, - Response::MODEL_ATTRIBUTE_STRING // needs to be last, since its condition would dominate any other string attribute + Response::MODEL_ATTRIBUTE_STRING, // needs to be last, since its condition would dominate any other string attribute ], 'description' => 'List of attributes.', 'default' => [], - 'array' => true - ]) - ; + 'array' => true, + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/AttributeString.php b/src/Appwrite/Utopia/Response/Model/AttributeString.php index fa36836050..eb72d705e6 100644 --- a/src/Appwrite/Utopia/Response/Model/AttributeString.php +++ b/src/Appwrite/Utopia/Response/Model/AttributeString.php @@ -3,7 +3,6 @@ namespace Appwrite\Utopia\Response\Model; use Appwrite\Utopia\Response; -use Appwrite\Utopia\Response\Model\Attribute; class AttributeString extends Attribute { @@ -24,8 +23,7 @@ class AttributeString extends Attribute 'default' => null, 'required' => false, 'example' => 'default', - ]) - ; + ]); } public array $conditions = [ diff --git a/src/Appwrite/Utopia/Response/Model/AttributeURL.php b/src/Appwrite/Utopia/Response/Model/AttributeURL.php index 332654f342..78bd9c24d2 100644 --- a/src/Appwrite/Utopia/Response/Model/AttributeURL.php +++ b/src/Appwrite/Utopia/Response/Model/AttributeURL.php @@ -3,7 +3,6 @@ namespace Appwrite\Utopia\Response\Model; use Appwrite\Utopia\Response; -use Appwrite\Utopia\Response\Model\Attribute; class AttributeURL extends Attribute { @@ -36,13 +35,12 @@ class AttributeURL extends Attribute 'default' => null, 'required' => false, 'example' => 'http://example.com', - ]) - ; + ]); } public array $conditions = [ 'type' => self::TYPE_STRING, - 'format' => \APP_DATABASE_ATTRIBUTE_URL + 'format' => \APP_DATABASE_ATTRIBUTE_URL, ]; /** diff --git a/src/Appwrite/Utopia/Response/Model/BaseList.php b/src/Appwrite/Utopia/Response/Model/BaseList.php index 06a5249388..af02d735cb 100644 --- a/src/Appwrite/Utopia/Response/Model/BaseList.php +++ b/src/Appwrite/Utopia/Response/Model/BaseList.php @@ -17,12 +17,12 @@ class BaseList extends Model protected string $type = ''; /** - * @param string $name - * @param string $type - * @param string $key - * @param string $model - * @param bool $paging - * @param bool $public + * @param string $name + * @param string $type + * @param string $key + * @param string $model + * @param bool $paging + * @param bool $public */ public function __construct(string $name, string $type, string $key, string $model, bool $paging = true, bool $public = true) { @@ -34,13 +34,13 @@ class BaseList extends Model $namesWithCap = [ 'documents', 'collections', 'users', 'files', 'buckets', 'functions', 'deployments', 'executions', 'projects', 'webhooks', 'keys', - 'platforms', 'domains', 'memberships', 'teams' + 'platforms', 'domains', 'memberships', 'teams', ]; if (\in_array($name, $namesWithCap)) { - $description = 'Total number of ' . $key . ' documents that matched your query used as reference for offset pagination. When the `total` number of ' . $key . ' documents available is greater than 5000, total returned will be capped at 5000, and cursor pagination should be used. Read more about [pagination](https://appwrite.io/docs/pagination).'; + $description = 'Total number of '.$key.' documents that matched your query used as reference for offset pagination. When the `total` number of '.$key.' documents available is greater than 5000, total returned will be capped at 5000, and cursor pagination should be used. Read more about [pagination](https://appwrite.io/docs/pagination).'; } else { - $description = 'Total number of ' . $key . ' documents that matched your query.'; + $description = 'Total number of '.$key.' documents that matched your query.'; } $this->addRule('total', [ @@ -52,7 +52,7 @@ class BaseList extends Model } $this->addRule($key, [ 'type' => $model, - 'description' => 'List of ' . $key . '.', + 'description' => 'List of '.$key.'.', 'default' => [], 'array' => true, ]); diff --git a/src/Appwrite/Utopia/Response/Model/Bucket.php b/src/Appwrite/Utopia/Response/Model/Bucket.php index 0276c1d1f9..16f1b02f24 100644 --- a/src/Appwrite/Utopia/Response/Model/Bucket.php +++ b/src/Appwrite/Utopia/Response/Model/Bucket.php @@ -64,14 +64,14 @@ class Bucket extends Model 'description' => 'Allowed file extensions.', 'default' => [], 'example' => ['jpg', 'png'], - 'array' => true + 'array' => true, ]) ->addRule('compression', [ 'type' => self::TYPE_STRING, - 'description' => 'Compression algorithm choosen for compression. Will be one of ' . COMPRESSION_TYPE_NONE . ', [' . COMPRESSION_TYPE_GZIP . '](https://en.wikipedia.org/wiki/Gzip), or [' . COMPRESSION_TYPE_ZSTD . '](https://en.wikipedia.org/wiki/Zstd).', + 'description' => 'Compression algorithm choosen for compression. Will be one of '.COMPRESSION_TYPE_NONE.', ['.COMPRESSION_TYPE_GZIP.'](https://en.wikipedia.org/wiki/Gzip), or ['.COMPRESSION_TYPE_ZSTD.'](https://en.wikipedia.org/wiki/Zstd).', 'default' => '', 'example' => 'gzip', - 'array' => false + 'array' => false, ]) ->addRule('encryption', [ 'type' => self::TYPE_BOOLEAN, @@ -84,8 +84,7 @@ class Bucket extends Model 'description' => 'Virus scanning is enabled.', 'default' => true, 'example' => false, - ]) - ; + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/Build.php b/src/Appwrite/Utopia/Response/Model/Build.php index b76f0ee083..f8709bd027 100644 --- a/src/Appwrite/Utopia/Response/Model/Build.php +++ b/src/Appwrite/Utopia/Response/Model/Build.php @@ -62,8 +62,7 @@ class Build extends Model 'description' => 'The build duration in seconds.', 'default' => 0, 'example' => 0, - ]) - ; + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/Collection.php b/src/Appwrite/Utopia/Response/Model/Collection.php index 64e3a9129a..4310ea81a7 100644 --- a/src/Appwrite/Utopia/Response/Model/Collection.php +++ b/src/Appwrite/Utopia/Response/Model/Collection.php @@ -33,7 +33,7 @@ class Collection extends Model 'description' => 'Collection permissions. [Learn more about permissions](/docs/permissions).', 'default' => '', 'example' => ['read("any")'], - 'array' => true + 'array' => true, ]) ->addRule('databaseId', [ 'type' => self::TYPE_STRING, @@ -81,9 +81,8 @@ class Collection extends Model 'description' => 'Collection indexes.', 'default' => [], 'example' => new \stdClass(), - 'array' => true - ]) - ; + 'array' => true, + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/Continent.php b/src/Appwrite/Utopia/Response/Model/Continent.php index 5291424a4a..4fd5c9e095 100644 --- a/src/Appwrite/Utopia/Response/Model/Continent.php +++ b/src/Appwrite/Utopia/Response/Model/Continent.php @@ -21,8 +21,7 @@ class Continent extends Model 'description' => 'Continent two letter code.', 'default' => '', 'example' => 'EU', - ]) - ; + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/Country.php b/src/Appwrite/Utopia/Response/Model/Country.php index 64590a54d4..866460f929 100644 --- a/src/Appwrite/Utopia/Response/Model/Country.php +++ b/src/Appwrite/Utopia/Response/Model/Country.php @@ -21,8 +21,7 @@ class Country extends Model 'description' => 'Country two-character ISO 3166-1 alpha code.', 'default' => '', 'example' => 'US', - ]) - ; + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/Currency.php b/src/Appwrite/Utopia/Response/Model/Currency.php index 883ef486d8..e938f8a454 100644 --- a/src/Appwrite/Utopia/Response/Model/Currency.php +++ b/src/Appwrite/Utopia/Response/Model/Currency.php @@ -51,8 +51,7 @@ class Currency extends Model 'description' => 'Currency plural name', 'default' => '', 'example' => 'US dollars', - ]) - ; + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/Database.php b/src/Appwrite/Utopia/Response/Model/Database.php index 9d9a4b2762..5d7435388b 100644 --- a/src/Appwrite/Utopia/Response/Model/Database.php +++ b/src/Appwrite/Utopia/Response/Model/Database.php @@ -33,8 +33,7 @@ class Database extends Model 'description' => 'Database update date in ISO 8601 format.', 'default' => '', 'example' => self::TYPE_DATETIME_EXAMPLE, - ]) - ; + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/Deployment.php b/src/Appwrite/Utopia/Response/Model/Deployment.php index 8862d6a14e..be571810b8 100644 --- a/src/Appwrite/Utopia/Response/Model/Deployment.php +++ b/src/Appwrite/Utopia/Response/Model/Deployment.php @@ -87,8 +87,7 @@ class Deployment extends Model 'description' => 'The current build time in seconds.', 'default' => 0, 'example' => 128, - ]) - ; + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/Domain.php b/src/Appwrite/Utopia/Response/Model/Domain.php index 28b8f593ba..86dff5c804 100644 --- a/src/Appwrite/Utopia/Response/Model/Domain.php +++ b/src/Appwrite/Utopia/Response/Model/Domain.php @@ -68,8 +68,7 @@ class Domain extends Model 'description' => 'Registered with Appwrite', 'default' => false, 'example' => true, - ]) - ; + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/Error.php b/src/Appwrite/Utopia/Response/Model/Error.php index 99cf3cbce2..6fc182214d 100644 --- a/src/Appwrite/Utopia/Response/Model/Error.php +++ b/src/Appwrite/Utopia/Response/Model/Error.php @@ -33,8 +33,7 @@ class Error extends Model 'description' => 'Server version number.', 'default' => '', 'example' => '1.0', - ]) - ; + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/ErrorDev.php b/src/Appwrite/Utopia/Response/Model/ErrorDev.php index 9319397c77..4911da6bc7 100644 --- a/src/Appwrite/Utopia/Response/Model/ErrorDev.php +++ b/src/Appwrite/Utopia/Response/Model/ErrorDev.php @@ -34,8 +34,7 @@ class ErrorDev extends Error 'default' => [], 'example' => '', 'array' => true, - ]) - ; + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/Execution.php b/src/Appwrite/Utopia/Response/Model/Execution.php index 8672a91598..d4bd212e93 100644 --- a/src/Appwrite/Utopia/Response/Model/Execution.php +++ b/src/Appwrite/Utopia/Response/Model/Execution.php @@ -83,8 +83,7 @@ class Execution extends Model 'description' => 'The script execution duration in seconds.', 'default' => 0, 'example' => 0.400, - ]) - ; + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/File.php b/src/Appwrite/Utopia/Response/Model/File.php index 53469f46b3..a9a89d2a41 100644 --- a/src/Appwrite/Utopia/Response/Model/File.php +++ b/src/Appwrite/Utopia/Response/Model/File.php @@ -76,8 +76,7 @@ class File extends Model 'description' => 'Total number of chunks uploaded', 'default' => 0, 'example' => 17890, - ]) - ; + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/Func.php b/src/Appwrite/Utopia/Response/Model/Func.php index 74cfb1e844..a76b070fd7 100644 --- a/src/Appwrite/Utopia/Response/Model/Func.php +++ b/src/Appwrite/Utopia/Response/Model/Func.php @@ -4,8 +4,6 @@ namespace Appwrite\Utopia\Response\Model; use Appwrite\Utopia\Response; use Appwrite\Utopia\Response\Model; -use stdClass; -use Utopia\Database\Document; class Func extends Model { @@ -66,7 +64,7 @@ class Func extends Model 'description' => 'Function variables.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('events', [ 'type' => self::TYPE_STRING, @@ -98,8 +96,7 @@ class Func extends Model 'description' => 'Function execution timeout in seconds.', 'default' => 15, 'example' => 15, - ]) - ; + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/HealthAntivirus.php b/src/Appwrite/Utopia/Response/Model/HealthAntivirus.php index 7a74195371..97d608ff09 100644 --- a/src/Appwrite/Utopia/Response/Model/HealthAntivirus.php +++ b/src/Appwrite/Utopia/Response/Model/HealthAntivirus.php @@ -21,8 +21,7 @@ class HealthAntivirus extends Model 'description' => 'Antivirus status. Possible values can are: `disabled`, `offline`, `online`', 'default' => '', 'example' => 'online', - ]) - ; + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/HealthQueue.php b/src/Appwrite/Utopia/Response/Model/HealthQueue.php index da7c49a43f..5990a4c5d3 100644 --- a/src/Appwrite/Utopia/Response/Model/HealthQueue.php +++ b/src/Appwrite/Utopia/Response/Model/HealthQueue.php @@ -15,8 +15,7 @@ class HealthQueue extends Model 'description' => 'Amount of actions in the queue.', 'default' => 0, 'example' => 8, - ]) - ; + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/HealthStatus.php b/src/Appwrite/Utopia/Response/Model/HealthStatus.php index 23756de131..dcd8750c51 100644 --- a/src/Appwrite/Utopia/Response/Model/HealthStatus.php +++ b/src/Appwrite/Utopia/Response/Model/HealthStatus.php @@ -21,8 +21,7 @@ class HealthStatus extends Model 'description' => 'Service status. Possible values can are: `pass`, `fail`', 'default' => '', 'example' => 'pass', - ]) - ; + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/HealthTime.php b/src/Appwrite/Utopia/Response/Model/HealthTime.php index 042d073ce5..0484b8ec33 100644 --- a/src/Appwrite/Utopia/Response/Model/HealthTime.php +++ b/src/Appwrite/Utopia/Response/Model/HealthTime.php @@ -27,8 +27,7 @@ class HealthTime extends Model 'description' => 'Difference of unix remote and local timestamps in milliseconds.', 'default' => 0, 'example' => 93, - ]) - ; + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/HealthVersion.php b/src/Appwrite/Utopia/Response/Model/HealthVersion.php index 15a73c0e75..6fab34576d 100644 --- a/src/Appwrite/Utopia/Response/Model/HealthVersion.php +++ b/src/Appwrite/Utopia/Response/Model/HealthVersion.php @@ -15,8 +15,7 @@ class HealthVersion extends Model 'description' => 'Version of the Appwrite instance.', 'default' => '', 'example' => '0.11.0', - ]) - ; + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/Index.php b/src/Appwrite/Utopia/Response/Model/Index.php index b7ac626be9..fe13da2ee0 100644 --- a/src/Appwrite/Utopia/Response/Model/Index.php +++ b/src/Appwrite/Utopia/Response/Model/Index.php @@ -42,8 +42,7 @@ class Index extends Model 'example' => [], 'array' => true, 'required' => false, - ]) - ; + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/JWT.php b/src/Appwrite/Utopia/Response/Model/JWT.php index a2563a2ad8..debb81b28e 100644 --- a/src/Appwrite/Utopia/Response/Model/JWT.php +++ b/src/Appwrite/Utopia/Response/Model/JWT.php @@ -14,8 +14,7 @@ class JWT extends Model 'type' => self::TYPE_STRING, 'description' => 'JWT encoded string.', 'example' => 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c', - ]) - ; + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/Key.php b/src/Appwrite/Utopia/Response/Model/Key.php index c9b84be13e..c0c94e24a4 100644 --- a/src/Appwrite/Utopia/Response/Model/Key.php +++ b/src/Appwrite/Utopia/Response/Model/Key.php @@ -62,16 +62,15 @@ class Key extends Model 'type' => self::TYPE_DATETIME, 'description' => 'Most recent access date in ISO 8601 format.', 'default' => '', - 'example' => self::TYPE_DATETIME_EXAMPLE + 'example' => self::TYPE_DATETIME_EXAMPLE, ]) ->addRule('sdks', [ 'type' => self::TYPE_STRING, 'description' => 'List of SDK user agents that used this key.', 'default' => null, 'example' => 'appwrite:flutter', - 'array' => true - ]) - ; + 'array' => true, + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/Language.php b/src/Appwrite/Utopia/Response/Model/Language.php index 64f99a006f..c3f1072c82 100644 --- a/src/Appwrite/Utopia/Response/Model/Language.php +++ b/src/Appwrite/Utopia/Response/Model/Language.php @@ -27,8 +27,7 @@ class Language extends Model 'description' => 'Language native name.', 'default' => '', 'example' => 'Italiano', - ]) - ; + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/Locale.php b/src/Appwrite/Utopia/Response/Model/Locale.php index fdfa363acd..61f371e7ac 100644 --- a/src/Appwrite/Utopia/Response/Model/Locale.php +++ b/src/Appwrite/Utopia/Response/Model/Locale.php @@ -51,8 +51,7 @@ class Locale extends Model 'description' => 'Currency code in [ISO 4217-1](http://en.wikipedia.org/wiki/ISO_4217) three-character format', 'default' => '', 'example' => 'USD', - ]) - ; + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/Log.php b/src/Appwrite/Utopia/Response/Model/Log.php index bc2c923494..7177cad078 100644 --- a/src/Appwrite/Utopia/Response/Model/Log.php +++ b/src/Appwrite/Utopia/Response/Model/Log.php @@ -135,8 +135,7 @@ class Log extends Model 'description' => 'Country name.', 'default' => '', 'example' => 'United States', - ]) - ; + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/Membership.php b/src/Appwrite/Utopia/Response/Model/Membership.php index 118864e804..21d7ec94f8 100644 --- a/src/Appwrite/Utopia/Response/Model/Membership.php +++ b/src/Appwrite/Utopia/Response/Model/Membership.php @@ -82,8 +82,7 @@ class Membership extends Model 'default' => [], 'example' => 'admin', 'array' => true, - ]) - ; + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/Metric.php b/src/Appwrite/Utopia/Response/Model/Metric.php index 16cf7f7df2..6b52f97e21 100644 --- a/src/Appwrite/Utopia/Response/Model/Metric.php +++ b/src/Appwrite/Utopia/Response/Model/Metric.php @@ -20,7 +20,7 @@ class Metric extends Model 'type' => self::TYPE_DATETIME, 'description' => 'The date at which this metric was aggregated in ISO 8601 format.', 'default' => '', - 'example' => self::TYPE_DATETIME_EXAMPLE + 'example' => self::TYPE_DATETIME_EXAMPLE, ]); } diff --git a/src/Appwrite/Utopia/Response/Model/Mock.php b/src/Appwrite/Utopia/Response/Model/Mock.php index afdae66084..7332e589f1 100644 --- a/src/Appwrite/Utopia/Response/Model/Mock.php +++ b/src/Appwrite/Utopia/Response/Model/Mock.php @@ -15,8 +15,7 @@ class Mock extends Model 'description' => 'Result message.', 'default' => '', 'example' => 'Success', - ]) - ; + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/Phone.php b/src/Appwrite/Utopia/Response/Model/Phone.php index 226955919b..d732d0dc2e 100644 --- a/src/Appwrite/Utopia/Response/Model/Phone.php +++ b/src/Appwrite/Utopia/Response/Model/Phone.php @@ -27,8 +27,7 @@ class Phone extends Model 'description' => 'Country name.', 'default' => '', 'example' => 'United States', - ]) - ; + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/Platform.php b/src/Appwrite/Utopia/Response/Model/Platform.php index 4b8ffb1486..a25d819947 100644 --- a/src/Appwrite/Utopia/Response/Model/Platform.php +++ b/src/Appwrite/Utopia/Response/Model/Platform.php @@ -73,8 +73,7 @@ class Platform extends Model 'description' => 'HTTP basic authentication password.', 'default' => '', 'example' => 'password', - ]) - ; + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/Project.php b/src/Appwrite/Utopia/Response/Model/Project.php index ff89b09008..c09ab45afc 100644 --- a/src/Appwrite/Utopia/Response/Model/Project.php +++ b/src/Appwrite/Utopia/Response/Model/Project.php @@ -154,8 +154,7 @@ class Project extends Model 'default' => [], 'example' => new \stdClass(), 'array' => true, - ]) - ; + ]); $services = Config::getParam('services', []); $auth = Config::getParam('auth', []); @@ -165,17 +164,16 @@ class Project extends Model $key = $method['key'] ?? ''; $this - ->addRule('auth' . ucfirst($key), [ + ->addRule('auth'.ucfirst($key), [ 'type' => self::TYPE_BOOLEAN, - 'description' => $name . ' auth method status', + 'description' => $name.' auth method status', 'example' => true, 'default' => true, - ]) - ; + ]); } foreach ($services as $service) { - if (!$service['optional']) { + if (! $service['optional']) { continue; } @@ -183,13 +181,12 @@ class Project extends Model $key = $service['key'] ?? ''; $this - ->addRule('serviceStatusFor' . ucfirst($key), [ + ->addRule('serviceStatusFor'.ucfirst($key), [ 'type' => self::TYPE_BOOLEAN, - 'description' => $name . ' service status', + 'description' => $name.' service status', 'example' => true, 'default' => true, - ]) - ; + ]); } } @@ -225,12 +222,12 @@ class Project extends Model $services = Config::getParam('services', []); foreach ($services as $service) { - if (!$service['optional']) { + if (! $service['optional']) { continue; } $key = $service['key'] ?? ''; $value = $values[$key] ?? true; - $document->setAttribute('serviceStatusFor' . ucfirst($key), $value); + $document->setAttribute('serviceStatusFor'.ucfirst($key), $value); } // Auth @@ -244,7 +241,7 @@ class Project extends Model foreach ($auth as $index => $method) { $key = $method['key']; $value = $authValues[$key] ?? true; - $document->setAttribute('auth' . ucfirst($key), $value); + $document->setAttribute('auth'.ucfirst($key), $value); } // Providers @@ -253,20 +250,20 @@ class Project extends Model $projectProviders = []; foreach ($providers as $key => $provider) { - if (!$provider['enabled']) { + if (! $provider['enabled']) { // Disabled by Appwrite configuration, exclude from response continue; } $projectProviders[] = new Document([ 'name' => ucfirst($key), - 'appId' => $providerValues[$key . 'Appid'] ?? '', - 'secret' => $providerValues[$key . 'Secret'] ?? '', - 'enabled' => $providerValues[$key . 'Enabled'] ?? false, + 'appId' => $providerValues[$key.'Appid'] ?? '', + 'secret' => $providerValues[$key.'Secret'] ?? '', + 'enabled' => $providerValues[$key.'Enabled'] ?? false, ]); } - $document->setAttribute("providers", $projectProviders); + $document->setAttribute('providers', $projectProviders); return $document; } diff --git a/src/Appwrite/Utopia/Response/Model/Provider.php b/src/Appwrite/Utopia/Response/Model/Provider.php index 0f14993508..4fa7e26f47 100644 --- a/src/Appwrite/Utopia/Response/Model/Provider.php +++ b/src/Appwrite/Utopia/Response/Model/Provider.php @@ -37,8 +37,7 @@ class Provider extends Model 'type' => self::TYPE_BOOLEAN, 'description' => 'Provider is active and can be used to create session.', 'example' => '', - ]) - ; + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/Runtime.php b/src/Appwrite/Utopia/Response/Model/Runtime.php index 8bc42cb418..43cf711994 100644 --- a/src/Appwrite/Utopia/Response/Model/Runtime.php +++ b/src/Appwrite/Utopia/Response/Model/Runtime.php @@ -20,7 +20,7 @@ class Runtime extends Model 'type' => self::TYPE_STRING, 'description' => 'Runtime Name.', 'default' => '', - 'example' => 'Python' + 'example' => 'Python', ]) ->addRule('version', [ 'type' => self::TYPE_STRING, @@ -52,8 +52,7 @@ class Runtime extends Model 'default' => '', 'example' => 'amd64', 'array' => true, - ]) - ; + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/Session.php b/src/Appwrite/Utopia/Response/Model/Session.php index d961966b24..7b71780c4e 100644 --- a/src/Appwrite/Utopia/Response/Model/Session.php +++ b/src/Appwrite/Utopia/Response/Model/Session.php @@ -159,8 +159,7 @@ class Session extends Model 'description' => 'Returns true if this the current user session.', 'default' => false, 'example' => true, - ]) - ; + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/Team.php b/src/Appwrite/Utopia/Response/Model/Team.php index f4580729c7..599aabd686 100644 --- a/src/Appwrite/Utopia/Response/Model/Team.php +++ b/src/Appwrite/Utopia/Response/Model/Team.php @@ -39,8 +39,7 @@ class Team extends Model 'description' => 'Total number of team members.', 'default' => 0, 'example' => 7, - ]) - ; + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/Token.php b/src/Appwrite/Utopia/Response/Model/Token.php index c409e37f03..05bbe10302 100644 --- a/src/Appwrite/Utopia/Response/Model/Token.php +++ b/src/Appwrite/Utopia/Response/Model/Token.php @@ -39,8 +39,7 @@ class Token extends Model 'description' => 'Token expiration date in ISO 8601 format.', 'default' => '', 'example' => self::TYPE_DATETIME_EXAMPLE, - ]) - ; + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/UsageBuckets.php b/src/Appwrite/Utopia/Response/Model/UsageBuckets.php index 8c6c81f234..b29e4db78f 100644 --- a/src/Appwrite/Utopia/Response/Model/UsageBuckets.php +++ b/src/Appwrite/Utopia/Response/Model/UsageBuckets.php @@ -21,44 +21,43 @@ class UsageBuckets extends Model 'description' => 'Aggregated stats for total number of files in this bucket.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('filesStorage', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for total storage of files in this bucket.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('filesCreate', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for files created.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('filesRead', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for files read.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('filesUpdate', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for files updated.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('filesDelete', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for files deleted.', 'default' => [], 'example' => [], - 'array' => true - ]) - ; + 'array' => true, + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/UsageCollection.php b/src/Appwrite/Utopia/Response/Model/UsageCollection.php index 8b6966fcd2..ea6351d943 100644 --- a/src/Appwrite/Utopia/Response/Model/UsageCollection.php +++ b/src/Appwrite/Utopia/Response/Model/UsageCollection.php @@ -21,37 +21,36 @@ class UsageCollection extends Model 'description' => 'Aggregated stats for total number of documents.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('documentsCreate', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for documents created.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('documentsRead', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for documents read.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('documentsUpdate', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for documents updated.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('documentsDelete', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for documents deleted.', 'default' => [], 'example' => [], - 'array' => true - ]) - ; + 'array' => true, + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/UsageDatabase.php b/src/Appwrite/Utopia/Response/Model/UsageDatabase.php index 0c84d796ba..f95661ff13 100644 --- a/src/Appwrite/Utopia/Response/Model/UsageDatabase.php +++ b/src/Appwrite/Utopia/Response/Model/UsageDatabase.php @@ -21,72 +21,71 @@ class UsageDatabase extends Model 'description' => 'Aggregated stats for total number of documents.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('collectionsCount', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for total number of collections.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('documentsCreate', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for documents created.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('documentsRead', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for documents read.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('documentsUpdate', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for documents updated.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('documentsDelete', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for documents deleted.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('collectionsCreate', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for collections created.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('collectionsRead', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for collections read.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('collectionsUpdate', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for collections updated.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('collectionsDelete', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for collections delete.', 'default' => [], 'example' => [], - 'array' => true - ]) - ; + 'array' => true, + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/UsageDatabases.php b/src/Appwrite/Utopia/Response/Model/UsageDatabases.php index 93488a47db..bc02187091 100644 --- a/src/Appwrite/Utopia/Response/Model/UsageDatabases.php +++ b/src/Appwrite/Utopia/Response/Model/UsageDatabases.php @@ -21,107 +21,106 @@ class UsageDatabases extends Model 'description' => 'Aggregated stats for total number of documents.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('documentsCount', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for total number of documents.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('collectionsCount', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for total number of collections.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('databasesCreate', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for documents created.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('databasesRead', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for documents read.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('databasesUpdate', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for documents updated.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('databasesDelete', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for total number of collections.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('documentsCreate', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for documents created.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('documentsRead', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for documents read.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('documentsUpdate', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for documents updated.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('documentsDelete', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for documents deleted.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('collectionsCreate', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for collections created.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('collectionsRead', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for collections read.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('collectionsUpdate', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for collections updated.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('collectionsDelete', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for collections delete.', 'default' => [], 'example' => [], - 'array' => true - ]) - ; + 'array' => true, + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/UsageFunction.php b/src/Appwrite/Utopia/Response/Model/UsageFunction.php index 58d76bbf41..fc433d1928 100644 --- a/src/Appwrite/Utopia/Response/Model/UsageFunction.php +++ b/src/Appwrite/Utopia/Response/Model/UsageFunction.php @@ -21,58 +21,57 @@ class UsageFunction extends Model 'description' => 'Aggregated stats for number of function executions.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('executionsFailure', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for function execution failures.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('executionsSuccess', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for function execution successes.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('executionsTime', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for function execution duration.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('buildsTotal', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for number of function builds.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('buildsFailure', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for function build failures.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('buildsSuccess', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for function build successes.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('buildsTime', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for function build duration.', 'default' => [], 'example' => [], - 'array' => true - ]) - ; + 'array' => true, + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/UsageFunctions.php b/src/Appwrite/Utopia/Response/Model/UsageFunctions.php index 7adb0d4aa3..66cebf58b5 100644 --- a/src/Appwrite/Utopia/Response/Model/UsageFunctions.php +++ b/src/Appwrite/Utopia/Response/Model/UsageFunctions.php @@ -21,58 +21,57 @@ class UsageFunctions extends Model 'description' => 'Aggregated stats for number of function executions.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('executionsFailure', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for function execution failures.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('executionsSuccess', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for function execution successes.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('executionsTime', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for function execution duration.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('buildsTotal', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for number of function builds.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('buildsFailure', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for function build failures.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('buildsSuccess', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for function build successes.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('buildsTime', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for function build duration.', 'default' => [], 'example' => [], - 'array' => true - ]) - ; + 'array' => true, + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/UsageProject.php b/src/Appwrite/Utopia/Response/Model/UsageProject.php index e37bc5928d..81b4b752b6 100644 --- a/src/Appwrite/Utopia/Response/Model/UsageProject.php +++ b/src/Appwrite/Utopia/Response/Model/UsageProject.php @@ -21,58 +21,57 @@ class UsageProject extends Model 'description' => 'Aggregated stats for number of requests.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('network', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for consumed bandwidth.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('executions', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for function executions.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('documents', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for number of documents.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('databases', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for number of databases.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('users', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for number of users.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('storage', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for the occupied storage size (in bytes).', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('buckets', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for number of buckets.', 'default' => [], 'example' => [], - 'array' => true - ]) - ; + 'array' => true, + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/UsageStorage.php b/src/Appwrite/Utopia/Response/Model/UsageStorage.php index 7e3c08e12a..6c11f7fa4f 100644 --- a/src/Appwrite/Utopia/Response/Model/UsageStorage.php +++ b/src/Appwrite/Utopia/Response/Model/UsageStorage.php @@ -21,79 +21,78 @@ class UsageStorage extends Model 'description' => 'Aggregated stats for the occupied storage size (in bytes).', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('filesCount', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for total number of files.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('bucketsCount', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for total number of buckets.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('bucketsCreate', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for buckets created.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('bucketsRead', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for buckets read.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('bucketsUpdate', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for buckets updated.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('bucketsDelete', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for buckets deleted.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('filesCreate', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for files created.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('filesRead', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for files read.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('filesUpdate', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for files updated.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('filesDelete', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for files deleted.', 'default' => [], 'example' => [], - 'array' => true - ]) - ; + 'array' => true, + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/UsageUsers.php b/src/Appwrite/Utopia/Response/Model/UsageUsers.php index 4c7b37d50f..797ca7b5ec 100644 --- a/src/Appwrite/Utopia/Response/Model/UsageUsers.php +++ b/src/Appwrite/Utopia/Response/Model/UsageUsers.php @@ -21,58 +21,57 @@ class UsageUsers extends Model 'description' => 'Aggregated stats for total number of users.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('usersCreate', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for users created.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('usersRead', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for users read.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('usersUpdate', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for users updated.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('usersDelete', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for users deleted.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('sessionsCreate', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for sessions created.', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('sessionsProviderCreate', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for sessions created for a provider ( email, anonymous or oauth2 ).', 'default' => [], 'example' => [], - 'array' => true + 'array' => true, ]) ->addRule('sessionsDelete', [ 'type' => Response::MODEL_METRIC, 'description' => 'Aggregated stats for sessions deleted.', 'default' => [], 'example' => [], - 'array' => true - ]) - ; + 'array' => true, + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/User.php b/src/Appwrite/Utopia/Response/Model/User.php index 11a9bbf3a5..d42768fa1b 100644 --- a/src/Appwrite/Utopia/Response/Model/User.php +++ b/src/Appwrite/Utopia/Response/Model/User.php @@ -109,8 +109,7 @@ class User extends Model 'description' => 'User preferences as a key-value object', 'default' => new \stdClass(), 'example' => ['theme' => 'pink', 'timezone' => 'UTC'], - ]) - ; + ]); } /** @@ -128,6 +127,7 @@ class User extends Model if (is_array($prefs) && empty($prefs)) { $document->setAttribute('prefs', new \stdClass()); } + return $document; } diff --git a/src/Appwrite/Utopia/Response/Model/Variable.php b/src/Appwrite/Utopia/Response/Model/Variable.php index f4b3bcf2bb..7d84e8803f 100644 --- a/src/Appwrite/Utopia/Response/Model/Variable.php +++ b/src/Appwrite/Utopia/Response/Model/Variable.php @@ -46,8 +46,7 @@ class Variable extends Model 'description' => 'Function ID.', 'default' => '', 'example' => '5e5ea5c16897e', - ]) - ; + ]); } /** diff --git a/src/Appwrite/Utopia/Response/Model/Webhook.php b/src/Appwrite/Utopia/Response/Model/Webhook.php index 781bb9186d..d9e0f4be3c 100644 --- a/src/Appwrite/Utopia/Response/Model/Webhook.php +++ b/src/Appwrite/Utopia/Response/Model/Webhook.php @@ -75,8 +75,7 @@ class Webhook extends Model 'description' => 'Signature key which can be used to validated incoming', 'default' => '', 'example' => 'ad3d581ca230e2b7059c545e5a', - ]) - ; + ]); } /** diff --git a/src/Appwrite/Utopia/View.php b/src/Appwrite/Utopia/View.php index e4ed8164c9..ba0a1f0fc6 100644 --- a/src/Appwrite/Utopia/View.php +++ b/src/Appwrite/Utopia/View.php @@ -11,8 +11,9 @@ class View extends OldView * * Convert all applicable characters to HTML entities * - * @param string $str + * @param string $str * @return string + * * @deprecated Use print method with escape filter */ public function escape($str) diff --git a/src/Executor/Executor.php b/src/Executor/Executor.php index 416d47ab82..0782271c1c 100644 --- a/src/Executor/Executor.php +++ b/src/Executor/Executor.php @@ -4,18 +4,25 @@ namespace Executor; use Exception; use Utopia\App; -use Utopia\CLI\Console; class Executor { public const METHOD_GET = 'GET'; + public const METHOD_POST = 'POST'; + public const METHOD_PUT = 'PUT'; + public const METHOD_PATCH = 'PATCH'; + public const METHOD_DELETE = 'DELETE'; + public const METHOD_HEAD = 'HEAD'; + public const METHOD_OPTIONS = 'OPTIONS'; + public const METHOD_CONNECT = 'CONNECT'; + public const METHOD_TRACE = 'TRACE'; private $endpoint; @@ -28,7 +35,7 @@ class Executor public function __construct(string $endpoint) { - if (!filter_var($endpoint, FILTER_VALIDATE_URL)) { + if (! filter_var($endpoint, FILTER_VALIDATE_URL)) { throw new Exception('Unsupported endpoint'); } $this->endpoint = $endpoint; @@ -39,18 +46,18 @@ class Executor * * Launches a runtime container for a deployment ready for execution * - * @param string $deploymentId - * @param string $projectId - * @param string $source - * @param string $runtime - * @param string $baseImage - * @param bool $remove - * @param string $entrypoint - * @param string $workdir - * @param string $destinaction - * @param string $network - * @param array $vars - * @param array $commands + * @param string $deploymentId + * @param string $projectId + * @param string $source + * @param string $runtime + * @param string $baseImage + * @param bool $remove + * @param string $entrypoint + * @param string $workdir + * @param string $destinaction + * @param string $network + * @param array $vars + * @param array $commands */ public function createRuntime( string $deploymentId, @@ -65,10 +72,10 @@ class Executor array $vars = [], array $commands = [] ) { - $route = "/runtimes"; + $route = '/runtimes'; $headers = [ 'content-type' => 'application/json', - 'x-appwrite-executor-key' => App::getEnv('_APP_EXECUTOR_SECRET', '') + 'x-appwrite-executor-key' => App::getEnv('_APP_EXECUTOR_SECRET', ''), ]; $params = [ 'runtimeId' => "$projectId-$deploymentId", @@ -80,10 +87,10 @@ class Executor 'workdir' => $workdir, 'vars' => $vars, 'remove' => $remove, - 'commands' => $commands + 'commands' => $commands, ]; - $timeout = (int) App::getEnv('_APP_FUNCTIONS_BUILD_TIMEOUT', 900); + $timeout = (int) App::getEnv('_APP_FUNCTIONS_BUILD_TIMEOUT', 900); $response = $this->call(self::METHOD_POST, $route, $headers, $params, true, $timeout); @@ -100,16 +107,16 @@ class Executor * * Deletes a runtime and cleans up any containers remaining. * - * @param string $projectId - * @param string $deploymentId + * @param string $projectId + * @param string $deploymentId */ public function deleteRuntime(string $projectId, string $deploymentId) { $runtimeId = "$projectId-$deploymentId"; $route = "/runtimes/$runtimeId"; $headers = [ - 'content-type' => 'application/json', - 'x-appwrite-executor-key' => App::getEnv('_APP_EXECUTOR_SECRET', '') + 'content-type' => 'application/json', + 'x-appwrite-executor-key' => App::getEnv('_APP_EXECUTOR_SECRET', ''), ]; $params = []; @@ -127,16 +134,15 @@ class Executor /** * Create an execution * - * @param string $projectId - * @param string $deploymentId - * @param string $path - * @param array $vars - * @param string $entrypoint - * @param string $data + * @param string $projectId + * @param string $deploymentId + * @param string $path + * @param array $vars + * @param string $entrypoint + * @param string $data * @param string runtime - * @param string $baseImage - * @param int $timeout - * + * @param string $baseImage + * @param int $timeout * @return array */ public function createExecution( @@ -150,10 +156,10 @@ class Executor string $baseImage, $timeout ) { - $route = "/execution"; + $route = '/execution'; $headers = [ - 'content-type' => 'application/json', - 'x-appwrite-executor-key' => App::getEnv('_APP_EXECUTOR_SECRET', '') + 'content-type' => 'application/json', + 'x-appwrite-executor-key' => App::getEnv('_APP_EXECUTOR_SECRET', ''), ]; $params = [ 'runtimeId' => "$projectId-$deploymentId", @@ -163,7 +169,7 @@ class Executor ]; /* Add 2 seconds as a buffer to the actual timeout value since there can be a slight variance*/ - $requestTimeout = $timeout + 2; + $requestTimeout = $timeout + 2; $response = $this->call(self::METHOD_POST, $route, $headers, $params, true, $requestTimeout); $status = $response['headers']['status-code']; @@ -216,22 +222,23 @@ class Executor * * Make an API call * - * @param string $method - * @param string $path - * @param array $params - * @param array $headers - * @param bool $decode + * @param string $method + * @param string $path + * @param array $params + * @param array $headers + * @param bool $decode * @return array|string + * * @throws Exception */ public function call(string $method, string $path = '', array $headers = [], array $params = [], bool $decode = true, int $timeout = 15) { - $headers = array_merge($this->headers, $headers); - $ch = curl_init($this->endpoint . $path . (($method == self::METHOD_GET && !empty($params)) ? '?' . http_build_query($params) : '')); - $responseHeaders = []; - $responseStatus = -1; - $responseType = ''; - $responseBody = ''; + $headers = array_merge($this->headers, $headers); + $ch = curl_init($this->endpoint.$path.(($method == self::METHOD_GET && ! empty($params)) ? '?'.http_build_query($params) : '')); + $responseHeaders = []; + $responseStatus = -1; + $responseType = ''; + $responseBody = ''; switch ($headers['content-type']) { case 'application/json': @@ -248,7 +255,7 @@ class Executor } foreach ($headers as $i => $header) { - $headers[] = $i . ':' . $header; + $headers[] = $i.':'.$header; unset($headers[$i]); } @@ -281,8 +288,8 @@ class Executor curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); } - $responseBody = curl_exec($ch); - $responseType = $responseHeaders['content-type'] ?? ''; + $responseBody = curl_exec($ch); + $responseType = $responseHeaders['content-type'] ?? ''; $responseStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE); if ($decode) { @@ -291,7 +298,7 @@ class Executor $json = json_decode($responseBody, true); if ($json === null) { - throw new Exception('Failed to parse response: ' . $responseBody); + throw new Exception('Failed to parse response: '.$responseBody); } $responseBody = $json; @@ -301,7 +308,7 @@ class Executor } if ((curl_errno($ch)/* || 200 != $responseStatus*/)) { - throw new Exception(curl_error($ch) . ' with status code ' . $responseStatus, $responseStatus); + throw new Exception(curl_error($ch).' with status code '.$responseStatus, $responseStatus); } curl_close($ch); @@ -310,21 +317,21 @@ class Executor return [ 'headers' => $responseHeaders, - 'body' => $responseBody + 'body' => $responseBody, ]; } /** * Parse Cookie String * - * @param string $cookie + * @param string $cookie * @return array */ public function parseCookie(string $cookie): array { $cookies = []; - parse_str(strtr($cookie, array('&' => '%26', '+' => '%2B', ';' => '&')), $cookies); + parse_str(strtr($cookie, ['&' => '%26', '+' => '%2B', ';' => '&']), $cookies); return $cookies; } @@ -332,8 +339,8 @@ class Executor /** * Flatten params array to PHP multiple format * - * @param array $data - * @param string $prefix + * @param array $data + * @param string $prefix * @return array */ protected function flatten(array $data, string $prefix = ''): array diff --git a/tests/e2e/Client.php b/tests/e2e/Client.php index e98472b2b8..f107e2d2c2 100644 --- a/tests/e2e/Client.php +++ b/tests/e2e/Client.php @@ -7,13 +7,21 @@ use Exception; class Client { public const METHOD_GET = 'GET'; + public const METHOD_POST = 'POST'; + public const METHOD_PUT = 'PUT'; + public const METHOD_PATCH = 'PATCH'; + public const METHOD_DELETE = 'DELETE'; + public const METHOD_HEAD = 'HEAD'; + public const METHOD_OPTIONS = 'OPTIONS'; + public const METHOD_CONNECT = 'CONNECT'; + public const METHOD_TRACE = 'TRACE'; /** @@ -52,8 +60,7 @@ class Client * * Your Appwrite project ID. You can find your project ID in your Appwrite console project settings. * - * @param string $value - * + * @param string $value * @return self $this */ public function setProject(string $value): self @@ -68,8 +75,7 @@ class Client * * Your Appwrite project secret key. You can can create a new API key from your Appwrite console API keys dashboard. * - * @param string $value - * + * @param string $value * @return self $this */ public function setKey(string $value): self @@ -82,8 +88,7 @@ class Client /** * Set Locale * - * @param string $value - * + * @param string $value * @return self $this */ public function setLocale(string $value): self @@ -96,8 +101,7 @@ class Client /** * Set Mode * - * @param string $value - * + * @param string $value * @return self $this */ public function setMode(string $value): self @@ -108,7 +112,7 @@ class Client } /** - * @param bool $status true + * @param bool $status true * @return self $this */ public function setSelfSigned(bool $status = true): self @@ -119,7 +123,7 @@ class Client } /** - * @param string $endpoint + * @param string $endpoint * @return self $this */ public function setEndpoint(string $endpoint): self @@ -138,9 +142,8 @@ class Client } /** - * @param string $key - * @param string $value - * + * @param string $key + * @param string $value * @return self $this */ public function addHeader(string $key, string $value): self @@ -155,22 +158,23 @@ class Client * * Make an API call * - * @param string $method - * @param string $path - * @param array $params - * @param array $headers - * @param bool $decode + * @param string $method + * @param string $path + * @param array $params + * @param array $headers + * @param bool $decode * @return array|string + * * @throws Exception */ public function call(string $method, string $path = '', array $headers = [], array $params = [], bool $decode = true) { - $headers = array_merge($this->headers, $headers); - $ch = curl_init($this->endpoint . $path . (($method == self::METHOD_GET && !empty($params)) ? '?' . http_build_query($params) : '')); - $responseHeaders = []; - $responseStatus = -1; - $responseType = ''; - $responseBody = ''; + $headers = array_merge($this->headers, $headers); + $ch = curl_init($this->endpoint.$path.(($method == self::METHOD_GET && ! empty($params)) ? '?'.http_build_query($params) : '')); + $responseHeaders = []; + $responseStatus = -1; + $responseType = ''; + $responseBody = ''; switch ($headers['content-type']) { case 'application/json': @@ -191,7 +195,7 @@ class Client } foreach ($headers as $i => $header) { - $headers[] = $i . ':' . $header; + $headers[] = $i.':'.$header; unset($headers[$i]); } @@ -226,8 +230,8 @@ class Client curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); } - $responseBody = curl_exec($ch); - $responseType = $responseHeaders['content-type'] ?? ''; + $responseBody = curl_exec($ch); + $responseType = $responseHeaders['content-type'] ?? ''; $responseStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE); if ($decode) { @@ -236,7 +240,7 @@ class Client $json = json_decode($responseBody, true); if ($json === null) { - throw new Exception('Failed to parse response: ' . $responseBody); + throw new Exception('Failed to parse response: '.$responseBody); } $responseBody = $json; @@ -246,7 +250,7 @@ class Client } if ((curl_errno($ch)/* || 200 != $responseStatus*/)) { - throw new Exception(curl_error($ch) . ' with status code ' . $responseStatus, $responseStatus); + throw new Exception(curl_error($ch).' with status code '.$responseStatus, $responseStatus); } curl_close($ch); @@ -254,26 +258,26 @@ class Client $responseHeaders['status-code'] = $responseStatus; if ($responseStatus === 500) { - echo 'Server error(' . $method . ': ' . $path . '. Params: ' . json_encode($params) . '): ' . json_encode($responseBody) . "\n"; + echo 'Server error('.$method.': '.$path.'. Params: '.json_encode($params).'): '.json_encode($responseBody)."\n"; } return [ 'headers' => $responseHeaders, - 'body' => $responseBody + 'body' => $responseBody, ]; } /** * Parse Cookie String * - * @param string $cookie + * @param string $cookie * @return array */ public function parseCookie(string $cookie): array { $cookies = []; - parse_str(strtr($cookie, array('&' => '%26', '+' => '%2B', ';' => '&')), $cookies); + parse_str(strtr($cookie, ['&' => '%26', '+' => '%2B', ';' => '&']), $cookies); return $cookies; } @@ -281,8 +285,8 @@ class Client /** * Flatten params array to PHP multiple format * - * @param array $data - * @param string $prefix + * @param array $data + * @param string $prefix * @return array */ protected function flatten(array $data, string $prefix = ''): array diff --git a/tests/e2e/General/AbuseTest.php b/tests/e2e/General/AbuseTest.php index f5a2829974..ded164af21 100644 --- a/tests/e2e/General/AbuseTest.php +++ b/tests/e2e/General/AbuseTest.php @@ -34,13 +34,13 @@ class AbuseTest extends Scope $max = 120; for ($i = 0; $i <= $max + 1; $i++) { - $response = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents', [ + $response = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents', [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], [ 'documentId' => ID::unique(), 'data' => [ - 'title' => 'The Hulk ' . $i, + 'title' => 'The Hulk '.$i, ], ]); @@ -59,7 +59,7 @@ class AbuseTest extends Scope $collectionId = $data['collectionId']; $max = 120; - $document = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents', [ + $document = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents', [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], 'x-appwrite-key' => $this->getProject()['apiKey'], @@ -73,12 +73,12 @@ class AbuseTest extends Scope $documentId = $document['body']['$id']; for ($i = 0; $i <= $max + 1; $i++) { - $response = $this->client->call(Client::METHOD_PATCH, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents/' . $documentId, [ + $response = $this->client->call(Client::METHOD_PATCH, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents/'.$documentId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], [ 'data' => [ - 'title' => 'The Hulk ' . $i, + 'title' => 'The Hulk '.$i, ], ]); @@ -98,7 +98,7 @@ class AbuseTest extends Scope $max = 60; for ($i = 0; $i <= $max + 1; $i++) { - $document = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents', [ + $document = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents', [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], 'x-appwrite-key' => $this->getProject()['apiKey'], @@ -111,7 +111,7 @@ class AbuseTest extends Scope $documentId = $document['body']['$id']; - $response = $this->client->call(Client::METHOD_DELETE, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents/' . $documentId, [ + $response = $this->client->call(Client::METHOD_DELETE, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents/'.$documentId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ]); @@ -131,12 +131,12 @@ class AbuseTest extends Scope $max = 60; for ($i = 0; $i <= $max + 1; $i++) { - $response = $this->client->call(Client::METHOD_POST, '/storage/buckets/' . $bucketId . '/files', [ + $response = $this->client->call(Client::METHOD_POST, '/storage/buckets/'.$bucketId.'/files', [ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], ], [ 'fileId' => ID::unique(), - 'file' => new CURLFile(realpath(__DIR__ . '/../../resources/logo.png'), 'image/png', 'permissions.png'), + 'file' => new CURLFile(realpath(__DIR__.'/../../resources/logo.png'), 'image/png', 'permissions.png'), ]); if ($i < $max) { @@ -153,23 +153,23 @@ class AbuseTest extends Scope $bucketId = $data['bucketId']; $max = 60; - $response = $this->client->call(Client::METHOD_POST, '/storage/buckets/' . $bucketId . '/files', [ + $response = $this->client->call(Client::METHOD_POST, '/storage/buckets/'.$bucketId.'/files', [ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], 'x-appwrite-key' => $this->getProject()['apiKey'], ], [ 'fileId' => ID::unique(), - 'file' => new CURLFile(realpath(__DIR__ . '/../../resources/logo.png'), 'image/png', 'permissions.png'), + 'file' => new CURLFile(realpath(__DIR__.'/../../resources/logo.png'), 'image/png', 'permissions.png'), ]); $fileId = $response['body']['$id']; for ($i = 0; $i <= $max + 1; $i++) { - $response = $this->client->call(Client::METHOD_PUT, '/storage/buckets/' . $bucketId . '/files/' . $fileId, [ + $response = $this->client->call(Client::METHOD_PUT, '/storage/buckets/'.$bucketId.'/files/'.$fileId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], [ - 'name' => 'permissions' . $i . '.png', + 'name' => 'permissions'.$i.'.png', ]); if ($i < $max) { @@ -187,18 +187,18 @@ class AbuseTest extends Scope $max = 60; for ($i = 0; $i <= $max + 1; $i++) { - $response = $this->client->call(Client::METHOD_POST, '/storage/buckets/' . $bucketId . '/files', [ + $response = $this->client->call(Client::METHOD_POST, '/storage/buckets/'.$bucketId.'/files', [ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], 'x-appwrite-key' => $this->getProject()['apiKey'], ], [ 'fileId' => ID::unique(), - 'file' => new CURLFile(realpath(__DIR__ . '/../../resources/logo.png'), 'image/png', 'permissions.png'), + 'file' => new CURLFile(realpath(__DIR__.'/../../resources/logo.png'), 'image/png', 'permissions.png'), ]); $fileId = $response['body']['$id']; - $response = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/' . $bucketId . '/files/' . $fileId, [ + $response = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/'.$bucketId.'/files/'.$fileId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ]); @@ -216,7 +216,7 @@ class AbuseTest extends Scope $database = $this->client->call(Client::METHOD_POST, '/databases', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'databaseId' => ID::unique(), 'name' => 'AbuseDatabase', @@ -227,10 +227,10 @@ class AbuseTest extends Scope $databaseId = $database['body']['$id']; - $movies = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections', [ + $movies = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections', [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ], [ 'collectionId' => ID::unique(), 'name' => 'Movies', @@ -244,10 +244,10 @@ class AbuseTest extends Scope $collectionId = $movies['body']['$id']; - $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/attributes/string', [ + $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/attributes/string', [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ], [ 'key' => 'title', 'size' => 256, diff --git a/tests/e2e/General/HTTPTest.php b/tests/e2e/General/HTTPTest.php index 09f744f271..420c20b6c8 100644 --- a/tests/e2e/General/HTTPTest.php +++ b/tests/e2e/General/HTTPTest.php @@ -80,7 +80,7 @@ class HTTPTest extends Scope { // Preparation $previousEndpoint = $this->client->getEndpoint(); - $this->client->setEndpoint("http://localhost"); + $this->client->setEndpoint('http://localhost'); /** * Test for SUCCESS @@ -107,7 +107,7 @@ class HTTPTest extends Scope public function testSpecs() { - $directory = __DIR__ . '/../../../app/config/specs/'; + $directory = __DIR__.'/../../../app/config/specs/'; $files = scandir($directory); $client = new Client(); @@ -131,7 +131,7 @@ class HTTPTest extends Scope break; } } - if (!$allowed) { + if (! $allowed) { continue; } @@ -140,7 +140,7 @@ class HTTPTest extends Scope */ $response = $client->call(Client::METHOD_POST, '/validator/debug', [ 'content-type' => 'application/json', - ], json_decode(file_get_contents($directory . $file), true)); + ], json_decode(file_get_contents($directory.$file), true)); $response['body'] = json_decode($response['body'], true); $this->assertEquals(200, $response['headers']['status-code']); diff --git a/tests/e2e/General/UsageTest.php b/tests/e2e/General/UsageTest.php index afa8433cbb..0f08298ba7 100644 --- a/tests/e2e/General/UsageTest.php +++ b/tests/e2e/General/UsageTest.php @@ -3,11 +3,11 @@ namespace Tests\E2E\General; use Appwrite\Tests\Retry; +use CURLFile; use Tests\E2E\Client; use Tests\E2E\Scopes\ProjectCustom; use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\SideServer; -use CURLFile; use Tests\E2E\Services\Functions\FunctionsBase; use Utopia\Database\Helpers\Permission; use Utopia\Database\Helpers\Role; @@ -46,9 +46,9 @@ class UsageTest extends Scope $usersCount = 0; $requestsCount = 0; for ($i = 0; $i < 10; $i++) { - $email = uniqid() . 'user@usage.test'; + $email = uniqid().'user@usage.test'; $password = 'password'; - $name = uniqid() . 'User'; + $name = uniqid().'User'; $res = $this->client->call(Client::METHOD_POST, '/users', $headers, [ 'userId' => 'unique()', 'email' => $email, @@ -62,9 +62,9 @@ class UsageTest extends Scope if ($i < 5) { $userId = $res['body']['$id']; - $res = $this->client->call(Client::METHOD_GET, '/users/' . $userId, $headers); + $res = $this->client->call(Client::METHOD_GET, '/users/'.$userId, $headers); $this->assertEquals($userId, $res['body']['$id']); - $res = $this->client->call(Client::METHOD_DELETE, '/users/' . $userId, $headers); + $res = $this->client->call(Client::METHOD_DELETE, '/users/'.$userId, $headers); $this->assertEmpty($res['body']); $requestsCount += 2; $usersCount--; @@ -75,7 +75,7 @@ class UsageTest extends Scope 'projectId' => $projectId, 'headers' => $headers, 'usersCount' => $usersCount, - 'requestsCount' => $requestsCount + 'requestsCount' => $requestsCount, ]; } @@ -96,10 +96,10 @@ class UsageTest extends Scope $cheaders = [ 'origin' => 'http://localhost', 'x-appwrite-project' => 'console', - 'cookie' => 'a_session_console=' . $this->getRoot()['session'], + 'cookie' => 'a_session_console='.$this->getRoot()['session'], ]; - $res = $this->client->call(Client::METHOD_GET, '/projects/' . $projectId . '/usage?range=30d', $cheaders); + $res = $this->client->call(Client::METHOD_GET, '/projects/'.$projectId.'/usage?range=30d', $cheaders); $res = $res['body']; $this->assertEquals(9, count($res)); @@ -112,7 +112,7 @@ class UsageTest extends Scope $res = $this->client->call(Client::METHOD_GET, '/users/usage?range=30d', array_merge($cheaders, [ 'x-appwrite-project' => $projectId, - 'x-appwrite-mode' => 'admin' + 'x-appwrite-mode' => 'admin', ])); $requestsCount++; $res = $res['body']; @@ -145,11 +145,11 @@ class UsageTest extends Scope $filesDelete = 0; for ($i = 0; $i < 10; $i++) { - $name = uniqid() . ' bucket'; + $name = uniqid().' bucket'; $res = $this->client->call(Client::METHOD_POST, '/storage/buckets', $headers, [ 'bucketId' => 'unique()', 'name' => $name, - 'permission' => 'bucket' + 'permission' => 'bucket', ]); $this->assertEquals($name, $res['body']['name']); $this->assertNotEmpty($res['body']['$id']); @@ -160,11 +160,11 @@ class UsageTest extends Scope $requestsCount++; if ($i < 5) { - $res = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId, $headers); + $res = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId, $headers); $this->assertEquals($bucketId, $res['body']['$id']); $bucketsRead++; - $res = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/' . $bucketId, $headers); + $res = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/'.$bucketId, $headers); $this->assertEmpty($res['body']); $bucketsDelete++; @@ -176,26 +176,26 @@ class UsageTest extends Scope // upload some files $files = [ [ - 'path' => realpath(__DIR__ . '/../../resources/logo.png'), + 'path' => realpath(__DIR__.'/../../resources/logo.png'), 'name' => 'logo.png', ], [ - 'path' => realpath(__DIR__ . '/../../resources/file.png'), + 'path' => realpath(__DIR__.'/../../resources/file.png'), 'name' => 'file.png', ], [ - 'path' => realpath(__DIR__ . '/../../resources/disk-a/kitten-3.gif'), + 'path' => realpath(__DIR__.'/../../resources/disk-a/kitten-3.gif'), 'name' => 'kitten-3.gif', ], [ - 'path' => realpath(__DIR__ . '/../../resources/disk-a/kitten-1.jpg'), + 'path' => realpath(__DIR__.'/../../resources/disk-a/kitten-1.jpg'), 'name' => 'kitten-1.jpg', ], ]; for ($i = 0; $i < 10; $i++) { $file = $files[$i % count($files)]; - $res = $this->client->call(Client::METHOD_POST, '/storage/buckets/' . $bucketId . '/files', array_merge($headers, ['content-type' => 'multipart/form-data']), [ + $res = $this->client->call(Client::METHOD_POST, '/storage/buckets/'.$bucketId.'/files', array_merge($headers, ['content-type' => 'multipart/form-data']), [ 'fileId' => 'unique()', 'file' => new CURLFile($file['path'], '', $file['name']), ]); @@ -209,16 +209,16 @@ class UsageTest extends Scope $fileId = $res['body']['$id']; if ($i < 5) { - $res = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId, $headers); + $res = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId, $headers); $this->assertEquals($fileId, $res['body']['$id']); $filesRead++; - $res = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/' . $bucketId . '/files/' . $fileId, $headers); + $res = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/'.$bucketId.'/files/'.$fileId, $headers); $this->assertEmpty($res['body']); $filesDelete++; $requestsCount += 2; $filesCount--; - $storageTotal -= $fileSize; + $storageTotal -= $fileSize; } } @@ -262,10 +262,10 @@ class UsageTest extends Scope $headers = [ 'origin' => 'http://localhost', 'x-appwrite-project' => 'console', - 'cookie' => 'a_session_console=' . $this->getRoot()['session'], + 'cookie' => 'a_session_console='.$this->getRoot()['session'], ]; - $res = $this->client->call(Client::METHOD_GET, '/projects/' . $projectId . '/usage?range=30d', $headers); + $res = $this->client->call(Client::METHOD_GET, '/projects/'.$projectId.'/usage?range=30d', $headers); $res = $res['body']; $this->assertEquals(9, count($res)); @@ -278,7 +278,7 @@ class UsageTest extends Scope $res = $this->client->call(Client::METHOD_GET, '/storage/usage?range=30d', array_merge($headers, [ 'x-appwrite-project' => $projectId, - 'x-appwrite-mode' => 'admin' + 'x-appwrite-mode' => 'admin', ])); $requestsCount++; $res = $res['body']; @@ -301,9 +301,9 @@ class UsageTest extends Scope $this->assertEquals($filesDelete, $res['filesDelete'][array_key_last($res['filesDelete'])]['value']); $this->validateDates($res['filesDelete']); - $res = $this->client->call(Client::METHOD_GET, '/storage/' . $bucketId . '/usage?range=30d', array_merge($headers, [ + $res = $this->client->call(Client::METHOD_GET, '/storage/'.$bucketId.'/usage?range=30d', array_merge($headers, [ 'x-appwrite-project' => $projectId, - 'x-appwrite-mode' => 'admin' + 'x-appwrite-mode' => 'admin', ])); $requestsCount++; $res = $res['body']; @@ -314,6 +314,7 @@ class UsageTest extends Scope $this->assertEquals($filesDelete, $res['filesDelete'][array_key_last($res['filesDelete'])]['value']); $data['requestsCount'] = $requestsCount; + return $data; } @@ -344,7 +345,7 @@ class UsageTest extends Scope $documentsDelete = 0; for ($i = 0; $i < 10; $i++) { - $name = uniqid() . ' database'; + $name = uniqid().' database'; $res = $this->client->call(Client::METHOD_POST, '/databases', $headers, [ 'databaseId' => 'unique()', 'name' => $name, @@ -358,11 +359,11 @@ class UsageTest extends Scope $databasesCreate++; if ($i < 5) { - $res = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId, $headers); + $res = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId, $headers); $this->assertEquals($databaseId, $res['body']['$id']); $databasesRead++; - $res = $this->client->call(Client::METHOD_DELETE, '/databases/' . $databaseId, $headers); + $res = $this->client->call(Client::METHOD_DELETE, '/databases/'.$databaseId, $headers); $this->assertEmpty($res['body']); $databasesDelete++; @@ -372,8 +373,8 @@ class UsageTest extends Scope } for ($i = 0; $i < 10; $i++) { - $name = uniqid() . ' collection'; - $res = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections', $headers, [ + $name = uniqid().' collection'; + $res = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections', $headers, [ 'collectionId' => 'unique()', 'name' => $name, 'documentSecurity' => false, @@ -393,11 +394,11 @@ class UsageTest extends Scope $collectionsCreate++; if ($i < 5) { - $res = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $collectionId, $headers); + $res = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$collectionId, $headers); $this->assertEquals($collectionId, $res['body']['$id']); $collectionsRead++; - $res = $this->client->call(Client::METHOD_DELETE, '/databases/' . $databaseId . '/collections/' . $collectionId, $headers); + $res = $this->client->call(Client::METHOD_DELETE, '/databases/'.$databaseId.'/collections/'.$collectionId, $headers); $this->assertEmpty($res['body']); $collectionsDelete++; @@ -406,7 +407,7 @@ class UsageTest extends Scope } } - $res = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/attributes' . '/string', $headers, [ + $res = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/attributes'.'/string', $headers, [ 'key' => 'name', 'size' => 255, 'required' => true, @@ -417,10 +418,10 @@ class UsageTest extends Scope sleep(20); for ($i = 0; $i < 10; $i++) { - $name = uniqid() . ' collection'; - $res = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents', $headers, [ + $name = uniqid().' collection'; + $res = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents', $headers, [ 'documentId' => 'unique()', - 'data' => ['name' => $name] + 'data' => ['name' => $name], ]); $this->assertEquals($name, $res['body']['name']); $this->assertNotEmpty($res['body']['$id']); @@ -431,11 +432,11 @@ class UsageTest extends Scope $documentsCreate++; if ($i < 5) { - $res = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents/' . $documentId, $headers); + $res = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents/'.$documentId, $headers); $this->assertEquals($documentId, $res['body']['$id']); $documentsRead++; - $res = $this->client->call(Client::METHOD_DELETE, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents/' . $documentId, $headers); + $res = $this->client->call(Client::METHOD_DELETE, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents/'.$documentId, $headers); $this->assertEmpty($res['body']); $documentsDelete++; @@ -502,9 +503,9 @@ class UsageTest extends Scope $headers = [ 'origin' => 'http://localhost', 'x-appwrite-project' => 'console', - 'cookie' => 'a_session_console=' . $this->getRoot()['session'], + 'cookie' => 'a_session_console='.$this->getRoot()['session'], ]; - $res = $this->client->call(Client::METHOD_GET, '/projects/' . $projectId . '/usage?range=30d', $headers); + $res = $this->client->call(Client::METHOD_GET, '/projects/'.$projectId.'/usage?range=30d', $headers); $res = $res['body']; $this->assertEquals(9, count($res)); @@ -519,7 +520,7 @@ class UsageTest extends Scope $res = $this->client->call(Client::METHOD_GET, '/databases/usage?range=30d', array_merge($headers, [ 'x-appwrite-project' => $projectId, - 'x-appwrite-mode' => 'admin' + 'x-appwrite-mode' => 'admin', ])); $res = $res['body']; $this->assertEquals($databasesCount, $res['databasesCount'][array_key_last($res['databasesCount'])]['value']); @@ -552,9 +553,9 @@ class UsageTest extends Scope $this->assertEquals($documentsDelete, $res['documentsDelete'][array_key_last($res['documentsDelete'])]['value']); $this->validateDates($res['documentsDelete']); - $res = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/usage?range=30d', array_merge($headers, [ + $res = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/usage?range=30d', array_merge($headers, [ 'x-appwrite-project' => $projectId, - 'x-appwrite-mode' => 'admin' + 'x-appwrite-mode' => 'admin', ])); $res = $res['body']; $this->assertEquals($collectionsCount, $res['collectionsCount'][array_key_last($res['collectionsCount'])]['value']); @@ -578,9 +579,9 @@ class UsageTest extends Scope $this->assertEquals($documentsDelete, $res['documentsDelete'][array_key_last($res['documentsDelete'])]['value']); $this->validateDates($res['documentsDelete']); - $res = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $collectionId . '/usage?range=30d', array_merge($headers, [ + $res = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$collectionId.'/usage?range=30d', array_merge($headers, [ 'x-appwrite-project' => $projectId, - 'x-appwrite-mode' => 'admin' + 'x-appwrite-mode' => 'admin', ])); $res = $res['body']; $this->assertEquals($documentsCount, $res['documentsCount'][array_key_last($res['documentsCount'])]['value']); @@ -594,10 +595,10 @@ class UsageTest extends Scope $this->validateDates($res['documentsDelete']); $data['requestsCount'] = $requestsCount; + return $data; } - /** @depends testDatabaseStats */ public function testPrepareFunctionsStats(array $data): array { @@ -630,13 +631,13 @@ class UsageTest extends Scope $this->assertEquals(201, $response1['headers']['status-code']); $this->assertNotEmpty($response1['body']['$id']); - $code = realpath(__DIR__ . '/../../resources/functions') . "/php/code.tar.gz"; + $code = realpath(__DIR__.'/../../resources/functions').'/php/code.tar.gz'; $this->packageCode('php'); - $deployment = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/deployments', array_merge($headers, ['content-type' => 'multipart/form-data',]), [ + $deployment = $this->client->call(Client::METHOD_POST, '/functions/'.$functionId.'/deployments', array_merge($headers, ['content-type' => 'multipart/form-data']), [ 'entrypoint' => 'index.php', 'code' => new CURLFile($code, 'application/x-gzip', \basename($code)), - 'activate' => true + 'activate' => true, ]); $deploymentId = $deployment['body']['$id'] ?? ''; @@ -649,7 +650,7 @@ class UsageTest extends Scope // Wait for deployment to build. sleep(30); - $response = $this->client->call(Client::METHOD_PATCH, '/functions/' . $functionId . '/deployments/' . $deploymentId, $headers, []); + $response = $this->client->call(Client::METHOD_PATCH, '/functions/'.$functionId.'/deployments/'.$deploymentId, $headers, []); $this->assertEquals(200, $response['headers']['status-code']); $this->assertNotEmpty($response['body']['$id']); @@ -657,7 +658,7 @@ class UsageTest extends Scope $this->assertEquals(true, $dateValidator->isValid($response['body']['$updatedAt'])); $this->assertEquals($deploymentId, $response['body']['deployment']); - $execution = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/executions', $headers, [ + $execution = $this->client->call(Client::METHOD_POST, '/functions/'.$functionId.'/executions', $headers, [ 'async' => false, ]); @@ -671,7 +672,7 @@ class UsageTest extends Scope $executions++; } - $execution = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/executions', $headers, [ + $execution = $this->client->call(Client::METHOD_POST, '/functions/'.$functionId.'/executions', $headers, [ 'async' => false, ]); @@ -685,7 +686,7 @@ class UsageTest extends Scope } $executionTime += (int) ($execution['body']['duration'] * 1000); - $execution = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/executions', $headers, [ + $execution = $this->client->call(Client::METHOD_POST, '/functions/'.$functionId.'/executions', $headers, [ 'async' => true, ]); @@ -695,7 +696,7 @@ class UsageTest extends Scope sleep(10); - $execution = $this->client->call(Client::METHOD_GET, '/functions/' . $functionId . '/executions/' . $execution['body']['$id'], $headers); + $execution = $this->client->call(Client::METHOD_GET, '/functions/'.$functionId.'/executions/'.$execution['body']['$id'], $headers); if ($execution['body']['status'] == 'failed') { $failures++; @@ -726,8 +727,8 @@ class UsageTest extends Scope sleep(20); - $response = $this->client->call(Client::METHOD_GET, '/functions/' . $functionId . '/usage', $headers, [ - 'range' => '30d' + $response = $this->client->call(Client::METHOD_GET, '/functions/'.$functionId.'/usage', $headers, [ + 'range' => '30d', ]); $this->assertEquals(200, $response['headers']['status-code']); @@ -751,7 +752,7 @@ class UsageTest extends Scope $this->validateDates($response['executionsFailure']); $response = $this->client->call(Client::METHOD_GET, '/functions/usage', $headers, [ - 'range' => '30d' + 'range' => '30d', ]); $this->assertEquals(200, $response['headers']['status-code']); diff --git a/tests/e2e/Scopes/ProjectCustom.php b/tests/e2e/Scopes/ProjectCustom.php index 4d780d04c6..151af89ff4 100644 --- a/tests/e2e/Scopes/ProjectCustom.php +++ b/tests/e2e/Scopes/ProjectCustom.php @@ -13,19 +13,19 @@ trait ProjectCustom protected static $project = []; /** - * @param bool $fresh + * @param bool $fresh * @return array */ public function getProject(bool $fresh = false): array { - if (!empty(self::$project) && !$fresh) { + if (! empty(self::$project) && ! $fresh) { return self::$project; } $team = $this->client->call(Client::METHOD_POST, '/teams', [ 'origin' => 'http://localhost', 'content-type' => 'application/json', - 'cookie' => 'a_session_console=' . $this->getRoot()['session'], + 'cookie' => 'a_session_console='.$this->getRoot()['session'], 'x-appwrite-project' => 'console', ], [ 'teamId' => ID::unique(), @@ -38,7 +38,7 @@ trait ProjectCustom $project = $this->client->call(Client::METHOD_POST, '/projects', [ 'origin' => 'http://localhost', 'content-type' => 'application/json', - 'cookie' => 'a_session_console=' . $this->getRoot()['session'], + 'cookie' => 'a_session_console='.$this->getRoot()['session'], 'x-appwrite-project' => 'console', ], [ 'projectId' => ID::unique(), @@ -59,10 +59,10 @@ trait ProjectCustom $this->assertEquals(201, $project['headers']['status-code']); $this->assertNotEmpty($project['body']); - $key = $this->client->call(Client::METHOD_POST, '/projects/' . $project['body']['$id'] . '/keys', [ + $key = $this->client->call(Client::METHOD_POST, '/projects/'.$project['body']['$id'].'/keys', [ 'origin' => 'http://localhost', 'content-type' => 'application/json', - 'cookie' => 'a_session_console=' . $this->getRoot()['session'], + 'cookie' => 'a_session_console='.$this->getRoot()['session'], 'x-appwrite-project' => 'console', ], [ 'name' => 'Demo Project Key', @@ -95,10 +95,10 @@ trait ProjectCustom $this->assertNotEmpty($key['body']); $this->assertNotEmpty($key['body']['secret']); - $webhook = $this->client->call(Client::METHOD_POST, '/projects/' . $project['body']['$id'] . '/webhooks', [ + $webhook = $this->client->call(Client::METHOD_POST, '/projects/'.$project['body']['$id'].'/webhooks', [ 'origin' => 'http://localhost', 'content-type' => 'application/json', - 'cookie' => 'a_session_console=' . $this->getRoot()['session'], + 'cookie' => 'a_session_console='.$this->getRoot()['session'], 'x-appwrite-project' => 'console', ], [ 'name' => 'Webhook Test', @@ -107,7 +107,7 @@ trait ProjectCustom 'functions.*', 'buckets.*', 'teams.*', - 'users.*' + 'users.*', ], 'url' => 'http://request-catcher:5000/webhook', 'security' => false, @@ -135,13 +135,12 @@ trait ProjectCustom public function getNewKey(array $scopes) { - $projectId = self::$project['$id']; - $key = $this->client->call(Client::METHOD_POST, '/projects/' . $projectId . '/keys', [ + $key = $this->client->call(Client::METHOD_POST, '/projects/'.$projectId.'/keys', [ 'origin' => 'http://localhost', 'content-type' => 'application/json', - 'cookie' => 'a_session_console=' . $this->getRoot()['session'], + 'cookie' => 'a_session_console='.$this->getRoot()['session'], 'x-appwrite-project' => 'console', ], [ 'name' => 'Demo Project Key', diff --git a/tests/e2e/Scopes/Scope.php b/tests/e2e/Scopes/Scope.php index 42057e8e94..5c94c77cad 100644 --- a/tests/e2e/Scopes/Scope.php +++ b/tests/e2e/Scopes/Scope.php @@ -3,8 +3,8 @@ namespace Tests\E2E\Scopes; use Appwrite\Tests\Retryable; -use Tests\E2E\Client; use PHPUnit\Framework\TestCase; +use Tests\E2E\Client; use Utopia\Database\Helpers\ID; abstract class Scope extends TestCase @@ -12,6 +12,7 @@ abstract class Scope extends TestCase use Retryable; protected ?Client $client = null; + protected string $endpoint = 'http://localhost/v1'; protected function setUp(): void @@ -19,8 +20,7 @@ abstract class Scope extends TestCase $this->client = new Client(); $this->client - ->setEndpoint($this->endpoint) - ; + ->setEndpoint($this->endpoint); } protected function tearDown(): void @@ -75,7 +75,7 @@ abstract class Scope extends TestCase return self::$root; } - $email = uniqid() . 'user@localhost.test'; + $email = uniqid().'user@localhost.test'; $password = 'password'; $name = 'User Name'; @@ -101,7 +101,7 @@ abstract class Scope extends TestCase 'password' => $password, ]); - $session = $this->client->parseCookie((string)$session['headers']['set-cookie'])['a_session_console']; + $session = $this->client->parseCookie((string) $session['headers']['set-cookie'])['a_session_console']; self::$root = [ '$id' => ID::custom($root['body']['$id']), @@ -127,7 +127,7 @@ abstract class Scope extends TestCase return self::$user[$this->getProject()['$id']]; } - $email = uniqid() . 'user@localhost.test'; + $email = uniqid().'user@localhost.test'; $password = 'password'; $name = 'User Name'; @@ -153,7 +153,7 @@ abstract class Scope extends TestCase 'password' => $password, ]); - $token = $this->client->parseCookie((string)$session['headers']['set-cookie'])['a_session_' . $this->getProject()['$id']]; + $token = $this->client->parseCookie((string) $session['headers']['set-cookie'])['a_session_'.$this->getProject()['$id']]; self::$user[$this->getProject()['$id']] = [ '$id' => ID::custom($user['body']['$id']), diff --git a/tests/e2e/Scopes/SideClient.php b/tests/e2e/Scopes/SideClient.php index 54f77a9747..2348da8e6b 100644 --- a/tests/e2e/Scopes/SideClient.php +++ b/tests/e2e/Scopes/SideClient.php @@ -8,7 +8,7 @@ trait SideClient { return [ 'origin' => 'http://localhost', - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $this->getUser()['session'], + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$this->getUser()['session'], ]; } diff --git a/tests/e2e/Scopes/SideConsole.php b/tests/e2e/Scopes/SideConsole.php index 74a0dd0c60..f067977c14 100644 --- a/tests/e2e/Scopes/SideConsole.php +++ b/tests/e2e/Scopes/SideConsole.php @@ -8,8 +8,8 @@ trait SideConsole { return [ 'origin' => 'http://localhost', - 'cookie' => 'a_session_console=' . $this->getRoot()['session'], - 'x-appwrite-mode' => 'admin' + 'cookie' => 'a_session_console='.$this->getRoot()['session'], + 'x-appwrite-mode' => 'admin', ]; } diff --git a/tests/e2e/Scopes/SideServer.php b/tests/e2e/Scopes/SideServer.php index b5e15150e9..f72ac1f2e2 100644 --- a/tests/e2e/Scopes/SideServer.php +++ b/tests/e2e/Scopes/SideServer.php @@ -12,7 +12,7 @@ trait SideServer public function getHeaders(): array { return [ - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]; } diff --git a/tests/e2e/Services/Account/AccountBase.php b/tests/e2e/Services/Account/AccountBase.php index 785b2af097..2adf69f267 100644 --- a/tests/e2e/Services/Account/AccountBase.php +++ b/tests/e2e/Services/Account/AccountBase.php @@ -4,15 +4,15 @@ namespace Tests\E2E\Services\Account; use Appwrite\Tests\Retry; use Tests\E2E\Client; -use Utopia\Database\Helpers\ID; use Utopia\Database\DateTime; +use Utopia\Database\Helpers\ID; use Utopia\Database\Validator\DatetimeValidator; trait AccountBase { public function testCreateAccount(): array { - $email = uniqid() . 'user@localhost.test'; + $email = uniqid().'user@localhost.test'; $password = 'password'; $name = 'User Name'; @@ -124,7 +124,7 @@ trait AccountBase $this->assertNotFalse(\DateTime::createFromFormat('Y-m-d\TH:i:s.uP', $response['body']['expire'])); $sessionId = $response['body']['$id']; - $session = $this->client->parseCookie((string)$response['headers']['set-cookie'])['a_session_' . $this->getProject()['$id']]; + $session = $this->client->parseCookie((string) $response['headers']['set-cookie'])['a_session_'.$this->getProject()['$id']]; $response = $this->client->call(Client::METHOD_POST, '/account/sessions', array_merge([ 'origin' => 'http://localhost', @@ -146,7 +146,7 @@ trait AccountBase 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ]), [ - 'email' => $email . 'x', + 'email' => $email.'x', 'password' => $password, ]); @@ -158,7 +158,7 @@ trait AccountBase 'x-appwrite-project' => $this->getProject()['$id'], ]), [ 'email' => $email, - 'password' => $password . 'x', + 'password' => $password.'x', ]); $this->assertEquals($response['headers']['status-code'], 401); @@ -196,7 +196,7 @@ trait AccountBase 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ])); $this->assertEquals($response['headers']['status-code'], 200); @@ -219,7 +219,7 @@ trait AccountBase $response = $this->client->call(Client::METHOD_GET, '/account', [ 'content-type' => 'application/json', - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session . 'xx', + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session.'xx', 'x-appwrite-project' => $this->getProject()['$id'], ]); @@ -242,7 +242,7 @@ trait AccountBase 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ])); $this->assertEquals($response['headers']['status-code'], 200); @@ -279,7 +279,7 @@ trait AccountBase 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ])); $this->assertEquals($response['headers']['status-code'], 200); @@ -338,7 +338,7 @@ trait AccountBase 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ])); $this->assertEquals($response['headers']['status-code'], 200); @@ -346,7 +346,7 @@ trait AccountBase $this->assertNotEmpty($response['body']['logs']); $this->assertCount(3, $response['body']['logs']); $this->assertIsNumeric($response['body']['total']); - $this->assertContains($response['body']['logs'][1]['event'], ["session.create"]); + $this->assertContains($response['body']['logs'][1]['event'], ['session.create']); $this->assertEquals($response['body']['logs'][1]['ip'], filter_var($response['body']['logs'][1]['ip'], FILTER_VALIDATE_IP)); $dateValidator = new DatetimeValidator(); $this->assertEquals(true, $dateValidator->isValid($response['body']['logs'][1]['time'])); @@ -369,7 +369,7 @@ trait AccountBase $this->assertEquals('--', $response['body']['logs'][1]['countryCode']); $this->assertEquals('Unknown', $response['body']['logs'][1]['countryName']); - $this->assertContains($response['body']['logs'][2]['event'], ["user.create"]); + $this->assertContains($response['body']['logs'][2]['event'], ['user.create']); $this->assertEquals($response['body']['logs'][2]['ip'], filter_var($response['body']['logs'][2]['ip'], FILTER_VALIDATE_IP)); $this->assertEquals(true, $dateValidator->isValid($response['body']['logs'][2]['time'])); @@ -395,9 +395,9 @@ trait AccountBase 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), [ - 'queries' => [ 'limit(1)' ], + 'queries' => ['limit(1)'], ]); $this->assertEquals($responseLimit['headers']['status-code'], 200); @@ -412,9 +412,9 @@ trait AccountBase 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), [ - 'queries' => [ 'offset(1)' ], + 'queries' => ['offset(1)'], ]); $this->assertEquals($responseOffset['headers']['status-code'], 200); @@ -429,9 +429,9 @@ trait AccountBase 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), [ - 'queries' => [ 'limit(1)', 'offset(1)' ], + 'queries' => ['limit(1)', 'offset(1)'], ]); $this->assertEquals($responseLimitOffset['headers']['status-code'], 200); @@ -473,9 +473,9 @@ trait AccountBase 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), [ - 'name' => $newName + 'name' => $newName, ]); $this->assertEquals($response['headers']['status-code'], 200); @@ -502,7 +502,7 @@ trait AccountBase 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), []); $this->assertEquals($response['headers']['status-code'], 400); @@ -511,9 +511,9 @@ trait AccountBase 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), [ - 'name' => 'ocSRq1d3QphHivJyUmYY7WMnrxyjdk5YvVwcDqx2zS0coxESN8RmsQwLWw5Whnf0WbVohuFWTRAaoKgCOO0Y0M7LwgFnZmi8881Y72222222222222222222222222222' + 'name' => 'ocSRq1d3QphHivJyUmYY7WMnrxyjdk5YvVwcDqx2zS0coxESN8RmsQwLWw5Whnf0WbVohuFWTRAaoKgCOO0Y0M7LwgFnZmi8881Y72222222222222222222222222222', ]); $this->assertEquals($response['headers']['status-code'], 400); @@ -540,7 +540,7 @@ trait AccountBase 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), [ 'password' => 'new-password', 'oldPassword' => $password, @@ -579,7 +579,7 @@ trait AccountBase 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), []); $this->assertEquals($response['headers']['status-code'], 400); @@ -591,7 +591,7 @@ trait AccountBase 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), [ 'password' => 'new-password', 'oldPassword' => $password, @@ -605,9 +605,9 @@ trait AccountBase 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), [ - 'password' => 'new-password' + 'password' => 'new-password', ]); $this->assertEquals($response['headers']['status-code'], 401); @@ -621,7 +621,7 @@ trait AccountBase */ public function testUpdateAccountEmail($data): array { - $newEmail = uniqid() . 'new@localhost.test'; + $newEmail = uniqid().'new@localhost.test'; $session = $data['session'] ?? ''; /** @@ -631,7 +631,7 @@ trait AccountBase 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), [ 'email' => $newEmail, 'password' => 'new-password', @@ -660,7 +660,7 @@ trait AccountBase 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), []); $this->assertEquals($response['headers']['status-code'], 400); @@ -676,9 +676,9 @@ trait AccountBase 'x-appwrite-project' => $this->getProject()['$id'], ]), [ 'userId' => ID::unique(), - 'email' => $data['email'], - 'password' => $data['password'], - 'name' => $data['name'], + 'email' => $data['email'], + 'password' => $data['password'], + 'name' => $data['name'], ]); $this->assertEquals($response['headers']['status-code'], 201); @@ -688,7 +688,6 @@ trait AccountBase $this->assertEquals($response['body']['email'], $data['email']); $this->assertEquals($response['body']['name'], $data['name']); - $data['email'] = $newEmail; return $data; @@ -699,7 +698,7 @@ trait AccountBase */ public function testUpdateAccountPrefs($data): array { - $newEmail = uniqid() . 'new@localhost.test'; + $newEmail = uniqid().'new@localhost.test'; $session = $data['session'] ?? ''; /** @@ -709,12 +708,12 @@ trait AccountBase 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), [ 'prefs' => [ 'prefKey1' => 'prefValue1', 'prefKey2' => 'prefValue2', - ] + ], ]); $this->assertEquals($response['headers']['status-code'], 200); @@ -738,21 +737,9 @@ trait AccountBase 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), [ - 'prefs' => '{}' - ]); - - $this->assertEquals($response['headers']['status-code'], 400); - - - $response = $this->client->call(Client::METHOD_PATCH, '/account/prefs', array_merge([ - 'origin' => 'http://localhost', - 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, - ]), [ - 'prefs' => '[]' + 'prefs' => '{}', ]); $this->assertEquals($response['headers']['status-code'], 400); @@ -761,9 +748,20 @@ trait AccountBase 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), [ - 'prefs' => '{"test": "value"}' + 'prefs' => '[]', + ]); + + $this->assertEquals($response['headers']['status-code'], 400); + + $response = $this->client->call(Client::METHOD_PATCH, '/account/prefs', array_merge([ + 'origin' => 'http://localhost', + 'content-type' => 'application/json', + 'x-appwrite-project' => $this->getProject()['$id'], + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, + ]), [ + 'prefs' => '{"test": "value"}', ]); $this->assertEquals($response['headers']['status-code'], 400); @@ -771,29 +769,29 @@ trait AccountBase /** * Prefs size exceeded */ - $prefsObject = ["longValue" => str_repeat("🍰", 100000)]; + $prefsObject = ['longValue' => str_repeat('🍰', 100000)]; $response = $this->client->call(Client::METHOD_PATCH, '/account/prefs', array_merge([ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), [ - 'prefs' => $prefsObject + 'prefs' => $prefsObject, ]); $this->assertEquals(400, $response['headers']['status-code']); // Now let's test the same thing, but with normal symbol instead of multi-byte cake emoji - $prefsObject = ["longValue" => str_repeat("-", 100000)]; + $prefsObject = ['longValue' => str_repeat('-', 100000)]; $response = $this->client->call(Client::METHOD_PATCH, '/account/prefs', array_merge([ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), [ - 'prefs' => $prefsObject + 'prefs' => $prefsObject, ]); $this->assertEquals(400, $response['headers']['status-code']); @@ -817,7 +815,7 @@ trait AccountBase 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), [ 'url' => 'http://localhost/verification', @@ -836,14 +834,14 @@ trait AccountBase $this->assertEquals('Account Verification', $lastEmail['subject']); $verification = substr($lastEmail['text'], strpos($lastEmail['text'], '&secret=', 0) + 8, 256); - $expireTime = strpos($lastEmail['text'], 'expire=' . urlencode(DateTime::format(new \DateTime($response['body']['expire']))), 0); + $expireTime = strpos($lastEmail['text'], 'expire='.urlencode(DateTime::format(new \DateTime($response['body']['expire']))), 0); $this->assertNotFalse($expireTime); - $secretTest = strpos($lastEmail['text'], 'secret=' . $response['body']['secret'], 0); + $secretTest = strpos($lastEmail['text'], 'secret='.$response['body']['secret'], 0); $this->assertNotFalse($secretTest); - $userIDTest = strpos($lastEmail['text'], 'userId=' . $response['body']['userId'], 0); + $userIDTest = strpos($lastEmail['text'], 'userId='.$response['body']['userId'], 0); $this->assertNotFalse($userIDTest); @@ -854,7 +852,7 @@ trait AccountBase 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), [ 'url' => 'localhost/verification', ]); @@ -865,7 +863,7 @@ trait AccountBase 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), [ 'url' => 'http://remotehost/verification', ]); @@ -893,7 +891,7 @@ trait AccountBase 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), [ 'userId' => $id, 'secret' => $verification, @@ -908,7 +906,7 @@ trait AccountBase 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), [ 'userId' => ID::custom('ewewe'), 'secret' => $verification, @@ -920,7 +918,7 @@ trait AccountBase 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), [ 'userId' => $id, 'secret' => 'sdasdasdasd', @@ -953,7 +951,7 @@ trait AccountBase ]); $sessionNewId = $response['body']['$id']; - $sessionNew = $this->client->parseCookie((string)$response['headers']['set-cookie'])['a_session_' . $this->getProject()['$id']]; + $sessionNew = $this->client->parseCookie((string) $response['headers']['set-cookie'])['a_session_'.$this->getProject()['$id']]; $this->assertEquals($response['headers']['status-code'], 201); @@ -961,16 +959,16 @@ trait AccountBase 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $sessionNew, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$sessionNew, ]); $this->assertEquals($response['headers']['status-code'], 200); - $response = $this->client->call(Client::METHOD_DELETE, '/account/sessions/' . $sessionNewId, array_merge([ + $response = $this->client->call(Client::METHOD_DELETE, '/account/sessions/'.$sessionNewId, array_merge([ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $sessionNew, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$sessionNew, ])); $this->assertEquals($response['headers']['status-code'], 204); @@ -979,7 +977,7 @@ trait AccountBase 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ])); $this->assertEquals($response['headers']['status-code'], 200); @@ -991,7 +989,7 @@ trait AccountBase 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $sessionNew, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$sessionNew, ]); $this->assertEquals($response['headers']['status-code'], 401); @@ -1019,14 +1017,14 @@ trait AccountBase 'password' => $password, ]); - $sessionNew = $this->client->parseCookie((string)$response['headers']['set-cookie'])['a_session_' . $this->getProject()['$id']]; + $sessionNew = $this->client->parseCookie((string) $response['headers']['set-cookie'])['a_session_'.$this->getProject()['$id']]; $this->assertEquals($response['headers']['status-code'], 201); $response = $this->client->call(Client::METHOD_GET, '/account', [ 'origin' => 'http://localhost', 'content-type' => 'application/json', - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $sessionNew, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$sessionNew, 'x-appwrite-project' => $this->getProject()['$id'], ]); @@ -1035,7 +1033,7 @@ trait AccountBase $response = $this->client->call(Client::METHOD_DELETE, '/account/sessions/current', [ 'origin' => 'http://localhost', 'content-type' => 'application/json', - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $sessionNew, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$sessionNew, 'x-appwrite-project' => $this->getProject()['$id'], ]); @@ -1047,7 +1045,7 @@ trait AccountBase $response = $this->client->call(Client::METHOD_GET, '/account', [ 'origin' => 'http://localhost', 'content-type' => 'application/json', - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $sessionNew, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$sessionNew, 'x-appwrite-project' => $this->getProject()['$id'], ]); @@ -1070,7 +1068,7 @@ trait AccountBase 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ])); $this->assertEquals($response['headers']['status-code'], 204); @@ -1101,7 +1099,7 @@ trait AccountBase 'password' => $password, ]); - $data['session'] = $this->client->parseCookie((string)$response['headers']['set-cookie'])['a_session_' . $this->getProject()['$id']]; + $data['session'] = $this->client->parseCookie((string) $response['headers']['set-cookie'])['a_session_'.$this->getProject()['$id']]; return $data; } @@ -1140,15 +1138,15 @@ trait AccountBase $recovery = substr($lastEmail['text'], strpos($lastEmail['text'], '&secret=', 0) + 8, 256); - $expireTime = strpos($lastEmail['text'], 'expire=' . urlencode(DateTime::format(new \DateTime($response['body']['expire']))), 0); + $expireTime = strpos($lastEmail['text'], 'expire='.urlencode(DateTime::format(new \DateTime($response['body']['expire']))), 0); $this->assertNotFalse($expireTime); - $secretTest = strpos($lastEmail['text'], 'secret=' . $response['body']['secret'], 0); + $secretTest = strpos($lastEmail['text'], 'secret='.$response['body']['secret'], 0); $this->assertNotFalse($secretTest); - $userIDTest = strpos($lastEmail['text'], 'userId=' . $response['body']['userId'], 0); + $userIDTest = strpos($lastEmail['text'], 'userId='.$response['body']['userId'], 0); $this->assertNotFalse($userIDTest); @@ -1255,7 +1253,7 @@ trait AccountBase ]), [ 'userId' => $id, 'secret' => $recovery, - 'password' => $newPassowrd . 'x', + 'password' => $newPassowrd.'x', 'passwordAgain' => $newPassowrd, ]); @@ -1266,7 +1264,7 @@ trait AccountBase public function testCreateMagicUrl(): array { - $email = \time() . 'user@appwrite.io'; + $email = \time().'user@appwrite.io'; /** * Test for SUCCESS @@ -1295,15 +1293,15 @@ trait AccountBase $token = substr($lastEmail['text'], strpos($lastEmail['text'], '&secret=', 0) + 8, 256); - $expireTime = strpos($lastEmail['text'], 'expire=' . urlencode(DateTime::format(new \DateTime($response['body']['expire']))), 0); + $expireTime = strpos($lastEmail['text'], 'expire='.urlencode(DateTime::format(new \DateTime($response['body']['expire']))), 0); $this->assertNotFalse($expireTime); - $secretTest = strpos($lastEmail['text'], 'secret=' . $response['body']['secret'], 0); + $secretTest = strpos($lastEmail['text'], 'secret='.$response['body']['secret'], 0); $this->assertNotFalse($secretTest); - $userIDTest = strpos($lastEmail['text'], 'userId=' . $response['body']['userId'], 0); + $userIDTest = strpos($lastEmail['text'], 'userId='.$response['body']['userId'], 0); $this->assertNotFalse($userIDTest); @@ -1379,13 +1377,13 @@ trait AccountBase $this->assertNotEmpty($response['body']['userId']); $sessionId = $response['body']['$id']; - $session = $this->client->parseCookie((string)$response['headers']['set-cookie'])['a_session_' . $this->getProject()['$id']]; + $session = $this->client->parseCookie((string) $response['headers']['set-cookie'])['a_session_'.$this->getProject()['$id']]; $response = $this->client->call(Client::METHOD_GET, '/account', array_merge([ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ])); $this->assertEquals($response['headers']['status-code'], 200); @@ -1421,7 +1419,6 @@ trait AccountBase $this->assertEquals(401, $response['headers']['status-code']); - $data['sessionId'] = $sessionId; $data['session'] = $session; @@ -1443,9 +1440,9 @@ trait AccountBase 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), [ - 'password' => 'new-password' + 'password' => 'new-password', ]); $this->assertEquals($response['headers']['status-code'], 200); @@ -1482,7 +1479,7 @@ trait AccountBase 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), []); $this->assertEquals($response['headers']['status-code'], 400); @@ -1494,7 +1491,7 @@ trait AccountBase 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), [ 'password' => 'new-password', 'oldPassword' => 'wrong-password', @@ -1508,9 +1505,9 @@ trait AccountBase 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), [ - 'password' => 'new-password' + 'password' => 'new-password', ]); $this->assertEquals($response['headers']['status-code'], 401); diff --git a/tests/e2e/Services/Account/AccountConsoleClientTest.php b/tests/e2e/Services/Account/AccountConsoleClientTest.php index 4aa2462f89..3e12b485d7 100644 --- a/tests/e2e/Services/Account/AccountConsoleClientTest.php +++ b/tests/e2e/Services/Account/AccountConsoleClientTest.php @@ -2,8 +2,8 @@ namespace Tests\E2E\Services\Account; -use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\ProjectConsole; +use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\SideClient; class AccountConsoleClientTest extends Scope diff --git a/tests/e2e/Services/Account/AccountCustomClientTest.php b/tests/e2e/Services/Account/AccountCustomClientTest.php index 82002eb485..661a629475 100644 --- a/tests/e2e/Services/Account/AccountCustomClientTest.php +++ b/tests/e2e/Services/Account/AccountCustomClientTest.php @@ -2,18 +2,16 @@ namespace Tests\E2E\Services\Account; -use Appwrite\SMS\Adapter\Mock; use Appwrite\Tests\Retry; +use function sleep; use Tests\E2E\Client; -use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\ProjectCustom; +use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\SideClient; use Utopia\Database\DateTime; use Utopia\Database\Helpers\ID; use Utopia\Database\Validator\DatetimeValidator; -use function sleep; - class AccountCustomClientTest extends Scope { use AccountBase; @@ -32,11 +30,11 @@ class AccountCustomClientTest extends Scope /** * Test for SUCCESS */ - $response = $this->client->call(Client::METHOD_PATCH, '/projects/' . $this->getProject()['$id'] . '/oauth2', array_merge([ + $response = $this->client->call(Client::METHOD_PATCH, '/projects/'.$this->getProject()['$id'].'/oauth2', array_merge([ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => 'console', - 'cookie' => 'a_session_console=' . $this->getRoot()['session'], + 'cookie' => 'a_session_console='.$this->getRoot()['session'], ]), [ 'provider' => $provider, 'appId' => $appId, @@ -46,7 +44,7 @@ class AccountCustomClientTest extends Scope $this->assertEquals($response['headers']['status-code'], 200); - $response = $this->client->call(Client::METHOD_GET, '/account/sessions/oauth2/' . $provider, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/account/sessions/oauth2/'.$provider, array_merge([ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], @@ -61,11 +59,11 @@ class AccountCustomClientTest extends Scope /** * Test for Failure when disabled */ - $response = $this->client->call(Client::METHOD_PATCH, '/projects/' . $this->getProject()['$id'] . '/oauth2', array_merge([ + $response = $this->client->call(Client::METHOD_PATCH, '/projects/'.$this->getProject()['$id'].'/oauth2', array_merge([ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => 'console', - 'cookie' => 'a_session_console=' . $this->getRoot()['session'], + 'cookie' => 'a_session_console='.$this->getRoot()['session'], ]), [ 'provider' => $provider, 'appId' => $appId, @@ -75,7 +73,7 @@ class AccountCustomClientTest extends Scope $this->assertEquals($response['headers']['status-code'], 200); - $response = $this->client->call(Client::METHOD_GET, '/account/sessions/oauth2/' . $provider, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/account/sessions/oauth2/'.$provider, array_merge([ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], @@ -91,7 +89,7 @@ class AccountCustomClientTest extends Scope public function testBlockedAccount(): array { - $email = uniqid() . 'user@localhost.test'; + $email = uniqid().'user@localhost.test'; $password = 'password'; $name = 'User Name (blocked)'; @@ -125,18 +123,18 @@ class AccountCustomClientTest extends Scope $this->assertEquals($response['headers']['status-code'], 201); $sessionId = $response['body']['$id']; - $session = $this->client->parseCookie((string)$response['headers']['set-cookie'])['a_session_' . $this->getProject()['$id']]; + $session = $this->client->parseCookie((string) $response['headers']['set-cookie'])['a_session_'.$this->getProject()['$id']]; $response = $this->client->call(Client::METHOD_GET, '/account', array_merge([ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ])); $this->assertEquals($response['headers']['status-code'], 200); - $response = $this->client->call(Client::METHOD_PATCH, '/users/' . $id . '/status', [ + $response = $this->client->call(Client::METHOD_PATCH, '/users/'.$id.'/status', [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], 'x-appwrite-key' => $this->getProject()['apiKey'], @@ -150,7 +148,7 @@ class AccountCustomClientTest extends Scope 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ])); $this->assertEquals($response['headers']['status-code'], 401); @@ -169,10 +167,9 @@ class AccountCustomClientTest extends Scope return []; } - public function testSelfBlockedAccount(): array { - $email = uniqid() . 'user55@localhost.test'; + $email = uniqid().'user55@localhost.test'; $password = 'password'; $name = 'User Name (self blocked)'; @@ -205,13 +202,13 @@ class AccountCustomClientTest extends Scope $this->assertEquals($response['headers']['status-code'], 201); - $session = $this->client->parseCookie((string)$response['headers']['set-cookie'])['a_session_' . $this->getProject()['$id']]; + $session = $this->client->parseCookie((string) $response['headers']['set-cookie'])['a_session_'.$this->getProject()['$id']]; $response = $this->client->call(Client::METHOD_GET, '/account', array_merge([ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ])); $this->assertEquals($response['headers']['status-code'], 200); @@ -219,7 +216,7 @@ class AccountCustomClientTest extends Scope $response = $this->client->call(Client::METHOD_PATCH, '/account/status', [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ], [ 'status' => false, ]); @@ -230,7 +227,7 @@ class AccountCustomClientTest extends Scope 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ])); $this->assertEquals($response['headers']['status-code'], 401); @@ -251,7 +248,7 @@ class AccountCustomClientTest extends Scope public function testCreateJWT(): array { - $email = uniqid() . 'user@localhost.test'; + $email = uniqid().'user@localhost.test'; $password = 'password'; $name = 'User Name (JWT)'; @@ -285,13 +282,13 @@ class AccountCustomClientTest extends Scope $this->assertEquals($response['headers']['status-code'], 201); $sessionId = $response['body']['$id']; - $session = $this->client->parseCookie((string)$response['headers']['set-cookie'])['a_session_' . $this->getProject()['$id']]; + $session = $this->client->parseCookie((string) $response['headers']['set-cookie'])['a_session_'.$this->getProject()['$id']]; $response = $this->client->call(Client::METHOD_GET, '/account', array_merge([ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ])); $this->assertEquals($response['headers']['status-code'], 200); @@ -300,7 +297,7 @@ class AccountCustomClientTest extends Scope 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ])); $this->assertEquals($response['headers']['status-code'], 201); @@ -328,11 +325,11 @@ class AccountCustomClientTest extends Scope $this->assertEquals($response['headers']['status-code'], 200); - $response = $this->client->call(Client::METHOD_DELETE, '/account/sessions/' . $sessionId, array_merge([ + $response = $this->client->call(Client::METHOD_DELETE, '/account/sessions/'.$sessionId, array_merge([ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ])); $this->assertEquals($response['headers']['status-code'], 204); @@ -365,7 +362,7 @@ class AccountCustomClientTest extends Scope $this->assertNotEmpty($response['body']); $this->assertNotEmpty($response['body']['$id']); - $session = $this->client->parseCookie((string)$response['headers']['set-cookie'])['a_session_' . $this->getProject()['$id']]; + $session = $this->client->parseCookie((string) $response['headers']['set-cookie'])['a_session_'.$this->getProject()['$id']]; /** * Test for FAILURE @@ -374,7 +371,7 @@ class AccountCustomClientTest extends Scope 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]); $this->assertEquals(401, $response['headers']['status-code']); @@ -394,7 +391,7 @@ class AccountCustomClientTest extends Scope 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), [ 'oldPassword' => '', ]); @@ -409,7 +406,7 @@ class AccountCustomClientTest extends Scope */ public function testUpdateAnonymousAccountEmail($session) { - $email = uniqid() . 'new@localhost.test'; + $email = uniqid().'new@localhost.test'; /** * Test for FAILURE @@ -418,7 +415,7 @@ class AccountCustomClientTest extends Scope 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), [ 'email' => $email, 'password' => '', @@ -432,7 +429,7 @@ class AccountCustomClientTest extends Scope public function testConvertAnonymousAccount() { $session = $this->testCreateAnonymousAccount(); - $email = uniqid() . 'new@localhost.test'; + $email = uniqid().'new@localhost.test'; $password = 'new-password'; /** @@ -445,14 +442,14 @@ class AccountCustomClientTest extends Scope ]), [ 'userId' => ID::unique(), 'email' => $email, - 'password' => $password + 'password' => $password, ]); $response = $this->client->call(Client::METHOD_PATCH, '/account/email', array_merge([ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), [ 'email' => $email, 'password' => $password, @@ -463,13 +460,13 @@ class AccountCustomClientTest extends Scope /** * Test for SUCCESS */ - $email = uniqid() . 'new@localhost.test'; + $email = uniqid().'new@localhost.test'; $response = $this->client->call(Client::METHOD_PATCH, '/account/email', array_merge([ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), [ 'email' => $email, 'password' => $password, @@ -511,18 +508,18 @@ class AccountCustomClientTest extends Scope 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ])); $this->assertEquals($response['headers']['status-code'], 200); $userId = $response['body']['$id'] ?? ''; - $response = $this->client->call(Client::METHOD_PATCH, '/projects/' . $this->getProject()['$id'] . '/oauth2', array_merge([ + $response = $this->client->call(Client::METHOD_PATCH, '/projects/'.$this->getProject()['$id'].'/oauth2', array_merge([ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => 'console', - 'cookie' => 'a_session_console=' . $this->getRoot()['session'], + 'cookie' => 'a_session_console='.$this->getRoot()['session'], ]), [ 'provider' => $provider, 'appId' => $appId, @@ -532,17 +529,17 @@ class AccountCustomClientTest extends Scope $this->assertEquals($response['headers']['status-code'], 200); - $response = $this->client->call(Client::METHOD_GET, '/account/sessions/oauth2/' . $provider, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/account/sessions/oauth2/'.$provider, array_merge([ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), [ 'success' => 'http://localhost/v1/mock/tests/general/oauth2/success', 'failure' => 'http://localhost/v1/mock/tests/general/oauth2/failure', ]); - $session = $this->client->parseCookie((string)$response['headers']['set-cookie'])['a_session_' . $this->getProject()['$id']]; + $session = $this->client->parseCookie((string) $response['headers']['set-cookie'])['a_session_'.$this->getProject()['$id']]; $this->assertEquals(200, $response['headers']['status-code']); $this->assertEquals('success', $response['body']['result']); @@ -551,7 +548,7 @@ class AccountCustomClientTest extends Scope 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ])); $this->assertEquals($response['headers']['status-code'], 200); @@ -567,7 +564,7 @@ class AccountCustomClientTest extends Scope 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ])); $this->assertEquals(200, $response['headers']['status-code']); @@ -583,7 +580,7 @@ class AccountCustomClientTest extends Scope 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ])); $this->assertEquals(200, $response['headers']['status-code']); @@ -602,7 +599,7 @@ class AccountCustomClientTest extends Scope 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ])); $this->assertEquals($response['headers']['status-code'], 200); @@ -610,11 +607,11 @@ class AccountCustomClientTest extends Scope $sessionID = $response['body']['$id']; - $response = $this->client->call(Client::METHOD_GET, '/account/sessions/' . $sessionID, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/account/sessions/'.$sessionID, array_merge([ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ])); $this->assertEquals($response['headers']['status-code'], 200); @@ -624,7 +621,7 @@ class AccountCustomClientTest extends Scope 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ])); $this->assertEquals($response['headers']['status-code'], 404); @@ -687,7 +684,7 @@ class AccountCustomClientTest extends Scope 'x-appwrite-project' => $this->getProject()['$id'], 'x-appwrite-key' => $this->getProject()['apiKey'], ], [ - 'search' => '"' . $email . '"', + 'search' => '"'.$email.'"', ]); @@ -712,7 +709,6 @@ class AccountCustomClientTest extends Scope $this->assertEquals($response['body']['users'][0]['email'], $email); } - public function testCreatePhone(): array { $number = '+123456789'; @@ -745,7 +741,7 @@ class AccountCustomClientTest extends Scope 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ]), [ - 'userId' => ID::unique() + 'userId' => ID::unique(), ]); $this->assertEquals(400, $response['headers']['status-code']); @@ -821,13 +817,13 @@ class AccountCustomClientTest extends Scope $this->assertNotEmpty($response['body']['$id']); $this->assertNotEmpty($response['body']['userId']); - $session = $this->client->parseCookie((string)$response['headers']['set-cookie'])['a_session_' . $this->getProject()['$id']]; + $session = $this->client->parseCookie((string) $response['headers']['set-cookie'])['a_session_'.$this->getProject()['$id']]; $response = $this->client->call(Client::METHOD_GET, '/account', array_merge([ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ])); $this->assertEquals($response['headers']['status-code'], 200); @@ -863,19 +859,19 @@ class AccountCustomClientTest extends Scope public function testConvertPhoneToPassword(array $data): array { $session = $data['session']; - $email = uniqid() . 'new@localhost.test'; + $email = uniqid().'new@localhost.test'; $password = 'new-password'; /** * Test for SUCCESS */ - $email = uniqid() . 'new@localhost.test'; + $email = uniqid().'new@localhost.test'; $response = $this->client->call(Client::METHOD_PATCH, '/account/email', array_merge([ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), [ 'email' => $email, 'password' => $password, @@ -918,10 +914,10 @@ class AccountCustomClientTest extends Scope 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), [ 'phone' => $newPhone, - 'password' => 'new-password' + 'password' => 'new-password', ]); $this->assertEquals($response['headers']['status-code'], 200); @@ -947,7 +943,7 @@ class AccountCustomClientTest extends Scope 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), []); $this->assertEquals($response['headers']['status-code'], 400); @@ -972,7 +968,7 @@ class AccountCustomClientTest extends Scope 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ])); @@ -987,7 +983,7 @@ class AccountCustomClientTest extends Scope $smsRequest = $this->getLastRequest(); return \array_merge($data, [ - 'token' => $smsRequest['data']['message'] + 'token' => $smsRequest['data']['message'], ]); } @@ -1007,7 +1003,7 @@ class AccountCustomClientTest extends Scope 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), [ 'userId' => $id, 'secret' => $secret, @@ -1022,7 +1018,7 @@ class AccountCustomClientTest extends Scope 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), [ 'userId' => ID::custom('ewewe'), 'secret' => $secret, @@ -1034,7 +1030,7 @@ class AccountCustomClientTest extends Scope 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), [ 'userId' => $id, 'secret' => '999999', diff --git a/tests/e2e/Services/Account/AccountCustomServerTest.php b/tests/e2e/Services/Account/AccountCustomServerTest.php index 143277608d..6c6c2df654 100644 --- a/tests/e2e/Services/Account/AccountCustomServerTest.php +++ b/tests/e2e/Services/Account/AccountCustomServerTest.php @@ -15,7 +15,7 @@ class AccountCustomServerTest extends Scope public function testCreateAccount(): array { - $email = uniqid() . 'user@localhost.test'; + $email = uniqid().'user@localhost.test'; $password = 'password'; $name = 'User Name'; diff --git a/tests/e2e/Services/Avatars/AvatarsBase.php b/tests/e2e/Services/Avatars/AvatarsBase.php index e2ddc1a863..a7518d38af 100644 --- a/tests/e2e/Services/Avatars/AvatarsBase.php +++ b/tests/e2e/Services/Avatars/AvatarsBase.php @@ -45,7 +45,6 @@ trait AvatarsBase /** * Test for FAILURE */ - $response = $this->client->call(Client::METHOD_GET, '/avatars/credit-cards/unknown', [ 'x-appwrite-project' => $this->getProject()['$id'], ], [ @@ -108,7 +107,6 @@ trait AvatarsBase /** * Test for FAILURE */ - $response = $this->client->call(Client::METHOD_GET, '/avatars/browsers/unknown', [ 'x-appwrite-project' => $this->getProject()['$id'], ], [ @@ -262,7 +260,7 @@ trait AvatarsBase $response = $this->client->call(Client::METHOD_GET, '/avatars/image', [ 'x-appwrite-project' => $this->getProject()['$id'], ], [ - 'url' => 'invalid://appwrite.io/images/apple.png' + 'url' => 'invalid://appwrite.io/images/apple.png', ]); $this->assertEquals(400, $response['headers']['status-code']); @@ -349,7 +347,7 @@ trait AvatarsBase $this->assertEquals(400, $image->getImageWidth()); $this->assertEquals(400, $image->getImageHeight()); $this->assertEquals('PNG', $image->getImageFormat()); - $this->assertEquals(strlen(\file_get_contents(__DIR__ . '/../../../resources/qr/qr-default.png')), strlen($response['body'])); + $this->assertEquals(strlen(\file_get_contents(__DIR__.'/../../../resources/qr/qr-default.png')), strlen($response['body'])); $response = $this->client->call(Client::METHOD_GET, '/avatars/qr', [ 'x-appwrite-project' => $this->getProject()['$id'], @@ -367,7 +365,7 @@ trait AvatarsBase $this->assertEquals(200, $image->getImageWidth()); $this->assertEquals(200, $image->getImageHeight()); $this->assertEquals('PNG', $image->getImageFormat()); - $this->assertEquals(strlen(\file_get_contents(__DIR__ . '/../../../resources/qr/qr-size-200.png')), strlen($response['body'])); + $this->assertEquals(strlen(\file_get_contents(__DIR__.'/../../../resources/qr/qr-size-200.png')), strlen($response['body'])); $response = $this->client->call(Client::METHOD_GET, '/avatars/qr', [ 'x-appwrite-project' => $this->getProject()['$id'], @@ -386,7 +384,7 @@ trait AvatarsBase $this->assertEquals(200, $image->getImageWidth()); $this->assertEquals(200, $image->getImageHeight()); $this->assertEquals('PNG', $image->getImageFormat()); - $this->assertEquals(strlen(\file_get_contents(__DIR__ . '/../../../resources/qr/qr-size-200-margin-10.png')), strlen($response['body'])); + $this->assertEquals(strlen(\file_get_contents(__DIR__.'/../../../resources/qr/qr-size-200-margin-10.png')), strlen($response['body'])); $response = $this->client->call(Client::METHOD_GET, '/avatars/qr', [ 'x-appwrite-project' => $this->getProject()['$id'], @@ -402,7 +400,7 @@ trait AvatarsBase $this->assertEquals(200, $image->getImageWidth()); $this->assertEquals(200, $image->getImageHeight()); $this->assertEquals('PNG', $image->getImageFormat()); - $this->assertEquals(strlen(\file_get_contents(__DIR__ . '/../../../resources/qr/qr-size-200-margin-10.png')), strlen($response['body'])); + $this->assertEquals(strlen(\file_get_contents(__DIR__.'/../../../resources/qr/qr-size-200-margin-10.png')), strlen($response['body'])); $this->assertEquals(200, $response['headers']['status-code']); $this->assertEquals('attachment; filename="qr.png"', $response['headers']['content-disposition']); @@ -448,7 +446,6 @@ trait AvatarsBase return []; } - public function testGetInitials() { /** @@ -529,11 +526,11 @@ trait AvatarsBase $image = new \Imagick(); $image->readImageBlob($response['body']); - $original = new \Imagick(__DIR__ . '/../../../resources/initials.png'); + $original = new \Imagick(__DIR__.'/../../../resources/initials.png'); $this->assertEquals($image->getImageWidth(), $original->getImageWidth()); $this->assertEquals($image->getImageHeight(), $original->getImageHeight()); $this->assertEquals('PNG', $image->getImageFormat()); - $this->assertEquals(strlen(\file_get_contents(__DIR__ . '/../../../resources/initials.png')), strlen($response['body'])); + $this->assertEquals(strlen(\file_get_contents(__DIR__.'/../../../resources/initials.png')), strlen($response['body'])); } } diff --git a/tests/e2e/Services/Avatars/AvatarsConsoleClientTest.php b/tests/e2e/Services/Avatars/AvatarsConsoleClientTest.php index a59d694114..bfd17ef1e9 100644 --- a/tests/e2e/Services/Avatars/AvatarsConsoleClientTest.php +++ b/tests/e2e/Services/Avatars/AvatarsConsoleClientTest.php @@ -2,8 +2,8 @@ namespace Tests\E2E\Services\Avatars; -use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\ProjectConsole; +use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\SideClient; class AvatarsConsoleClientTest extends Scope diff --git a/tests/e2e/Services/Avatars/AvatarsCustomClientTest.php b/tests/e2e/Services/Avatars/AvatarsCustomClientTest.php index dc399971a0..edf09d5ba1 100644 --- a/tests/e2e/Services/Avatars/AvatarsCustomClientTest.php +++ b/tests/e2e/Services/Avatars/AvatarsCustomClientTest.php @@ -2,8 +2,8 @@ namespace Tests\E2E\Services\Avatars; -use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\ProjectCustom; +use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\SideClient; class AvatarsCustomClientTest extends Scope diff --git a/tests/e2e/Services/Databases/DatabasesBase.php b/tests/e2e/Services/Databases/DatabasesBase.php index 13a95c9f09..c38322190e 100644 --- a/tests/e2e/Services/Databases/DatabasesBase.php +++ b/tests/e2e/Services/Databases/DatabasesBase.php @@ -18,10 +18,10 @@ trait DatabasesBase $database = $this->client->call(Client::METHOD_POST, '/databases', [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ], [ 'databaseId' => ID::unique(), - 'name' => 'Test Database' + 'name' => 'Test Database', ]); $this->assertNotEmpty($database['body']['$id']); @@ -40,10 +40,10 @@ trait DatabasesBase /** * Test for SUCCESS */ - $movies = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections', array_merge([ + $movies = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'collectionId' => ID::unique(), 'name' => 'Movies', @@ -68,10 +68,10 @@ trait DatabasesBase /** * Test for SUCCESS */ - $response = $this->client->call(Client::METHOD_PUT, '/databases/' . $databaseId . '/collections/' . $data['moviesId'], array_merge([ + $response = $this->client->call(Client::METHOD_PUT, '/databases/'.$databaseId.'/collections/'.$data['moviesId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'name' => 'Movies', 'enabled' => false, @@ -82,7 +82,7 @@ trait DatabasesBase $this->assertFalse($response['body']['enabled']); if ($this->getSide() === 'client') { - $responseCreateDocument = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents', array_merge([ + $responseCreateDocument = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -99,14 +99,14 @@ trait DatabasesBase $this->assertEquals(404, $responseCreateDocument['headers']['status-code']); - $responseListDocument = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents', array_merge([ + $responseListDocument = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); $this->assertEquals(404, $responseListDocument['headers']['status-code']); - $responseGetDocument = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents/someID', array_merge([ + $responseGetDocument = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents/someID', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -114,10 +114,10 @@ trait DatabasesBase $this->assertEquals(404, $responseGetDocument['headers']['status-code']); } - $response = $this->client->call(Client::METHOD_PUT, '/databases/' . $databaseId . '/collections/' . $data['moviesId'], array_merge([ + $response = $this->client->call(Client::METHOD_PUT, '/databases/'.$databaseId.'/collections/'.$data['moviesId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'name' => 'Movies', 'enabled' => true, @@ -128,45 +128,44 @@ trait DatabasesBase $this->assertTrue($response['body']['enabled']); } - /** * @depends testCreateCollection */ public function testCreateAttributes(array $data): array { $databaseId = $data['databaseId']; - $title = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/attributes/string', array_merge([ + $title = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/attributes/string', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'title', 'size' => 256, 'required' => true, ]); - $releaseYear = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/attributes/integer', array_merge([ + $releaseYear = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/attributes/integer', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'releaseYear', 'required' => true, ]); - $duration = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/attributes/integer', array_merge([ + $duration = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/attributes/integer', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'duration', 'required' => false, ]); - $actors = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/attributes/string', array_merge([ + $actors = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/attributes/string', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'actors', 'size' => 256, @@ -174,10 +173,10 @@ trait DatabasesBase 'array' => true, ]); - $datetime = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/attributes/datetime', array_merge([ + $datetime = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/attributes/datetime', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'birthDay', 'required' => false, @@ -213,10 +212,10 @@ trait DatabasesBase // wait for database worker to create attributes sleep(2); - $movies = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'], array_merge([ + $movies = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), []); $this->assertIsArray($movies['body']['attributes']); @@ -236,10 +235,10 @@ trait DatabasesBase public function testAttributeResponseModels(array $data): array { $databaseId = $data['databaseId']; - $collection = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections', array_merge([ + $collection = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'collectionId' => ID::unique(), 'name' => 'Response Models', @@ -252,12 +251,12 @@ trait DatabasesBase $collectionId = $collection['body']['$id']; - $attributesPath = "/databases/" . $databaseId . "/collections/{$collectionId}/attributes"; + $attributesPath = '/databases/'.$databaseId."/collections/{$collectionId}/attributes"; - $string = $this->client->call(Client::METHOD_POST, $attributesPath . '/string', array_merge([ + $string = $this->client->call(Client::METHOD_POST, $attributesPath.'/string', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'string', 'size' => 16, @@ -265,20 +264,20 @@ trait DatabasesBase 'default' => 'default', ]); - $email = $this->client->call(Client::METHOD_POST, $attributesPath . '/email', array_merge([ + $email = $this->client->call(Client::METHOD_POST, $attributesPath.'/email', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'email', 'required' => false, 'default' => 'default@example.com', ]); - $enum = $this->client->call(Client::METHOD_POST, $attributesPath . '/enum', array_merge([ + $enum = $this->client->call(Client::METHOD_POST, $attributesPath.'/enum', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'enum', 'elements' => ['yes', 'no', 'maybe'], @@ -286,64 +285,64 @@ trait DatabasesBase 'default' => 'maybe', ]); - $ip = $this->client->call(Client::METHOD_POST, $attributesPath . '/ip', array_merge([ + $ip = $this->client->call(Client::METHOD_POST, $attributesPath.'/ip', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'ip', 'required' => false, 'default' => '192.0.2.0', ]); - $url = $this->client->call(Client::METHOD_POST, $attributesPath . '/url', array_merge([ + $url = $this->client->call(Client::METHOD_POST, $attributesPath.'/url', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'url', 'required' => false, 'default' => 'http://example.com', ]); - $integer = $this->client->call(Client::METHOD_POST, $attributesPath . '/integer', array_merge([ + $integer = $this->client->call(Client::METHOD_POST, $attributesPath.'/integer', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'integer', 'required' => false, 'min' => 1, 'max' => 5, - 'default' => 3 + 'default' => 3, ]); - $float = $this->client->call(Client::METHOD_POST, $attributesPath . '/float', array_merge([ + $float = $this->client->call(Client::METHOD_POST, $attributesPath.'/float', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'float', 'required' => false, 'min' => 1.5, 'max' => 5.5, - 'default' => 3.5 + 'default' => 3.5, ]); - $boolean = $this->client->call(Client::METHOD_POST, $attributesPath . '/boolean', array_merge([ + $boolean = $this->client->call(Client::METHOD_POST, $attributesPath.'/boolean', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'boolean', 'required' => false, 'default' => true, ]); - $datetime = $this->client->call(Client::METHOD_POST, $attributesPath . '/datetime', array_merge([ + $datetime = $this->client->call(Client::METHOD_POST, $attributesPath.'/datetime', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'datetime', 'required' => false, @@ -427,58 +426,58 @@ trait DatabasesBase // wait for database worker to create attributes sleep(30); - $stringResponse = $this->client->call(Client::METHOD_GET, $attributesPath . '/' . $string['body']['key'], array_merge([ + $stringResponse = $this->client->call(Client::METHOD_GET, $attributesPath.'/'.$string['body']['key'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ])); - $emailResponse = $this->client->call(Client::METHOD_GET, $attributesPath . '/' . $email['body']['key'], array_merge([ + $emailResponse = $this->client->call(Client::METHOD_GET, $attributesPath.'/'.$email['body']['key'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ])); - $enumResponse = $this->client->call(Client::METHOD_GET, $attributesPath . '/' . $enum['body']['key'], array_merge([ + $enumResponse = $this->client->call(Client::METHOD_GET, $attributesPath.'/'.$enum['body']['key'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ])); - $ipResponse = $this->client->call(Client::METHOD_GET, $attributesPath . '/' . $ip['body']['key'], array_merge([ + $ipResponse = $this->client->call(Client::METHOD_GET, $attributesPath.'/'.$ip['body']['key'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ])); - $urlResponse = $this->client->call(Client::METHOD_GET, $attributesPath . '/' . $url['body']['key'], array_merge([ + $urlResponse = $this->client->call(Client::METHOD_GET, $attributesPath.'/'.$url['body']['key'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ])); - $integerResponse = $this->client->call(Client::METHOD_GET, $attributesPath . '/' . $integer['body']['key'], array_merge([ + $integerResponse = $this->client->call(Client::METHOD_GET, $attributesPath.'/'.$integer['body']['key'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ])); - $floatResponse = $this->client->call(Client::METHOD_GET, $attributesPath . '/' . $float['body']['key'], array_merge([ + $floatResponse = $this->client->call(Client::METHOD_GET, $attributesPath.'/'.$float['body']['key'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ])); - $booleanResponse = $this->client->call(Client::METHOD_GET, $attributesPath . '/' . $boolean['body']['key'], array_merge([ + $booleanResponse = $this->client->call(Client::METHOD_GET, $attributesPath.'/'.$boolean['body']['key'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ])); - $datetimeResponse = $this->client->call(Client::METHOD_GET, $attributesPath . '/' . $datetime['body']['key'], array_merge([ + $datetimeResponse = $this->client->call(Client::METHOD_GET, $attributesPath.'/'.$datetime['body']['key'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ])); $this->assertEquals(200, $stringResponse['headers']['status-code']); @@ -563,10 +562,10 @@ trait DatabasesBase $this->assertEquals($datetime['body']['array'], $datetimeResponse['body']['array']); $this->assertEquals($datetime['body']['default'], $datetimeResponse['body']['default']); - $attributes = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $collectionId . '/attributes', array_merge([ + $attributes = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$collectionId.'/attributes', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ])); $this->assertEquals(200, $attributes['headers']['status-code']); @@ -650,10 +649,10 @@ trait DatabasesBase $this->assertEquals($datetimeResponse['body']['array'], $attributes[8]['array']); $this->assertEquals($datetimeResponse['body']['default'], $attributes[8]['default']); - $collection = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $collectionId, array_merge([ + $collection = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$collectionId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ])); $this->assertEquals(200, $collection['headers']['status-code']); @@ -739,10 +738,10 @@ trait DatabasesBase /** * Test for FAILURE */ - $badEnum = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/attributes/enum', array_merge([ + $badEnum = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/attributes/enum', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'enum', 'elements' => ['yes', 'no', ''], @@ -762,10 +761,10 @@ trait DatabasesBase public function testCreateIndexes(array $data): array { $databaseId = $data['databaseId']; - $titleIndex = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/indexes', array_merge([ + $titleIndex = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/indexes', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'titleIndex', 'type' => 'fulltext', @@ -778,10 +777,10 @@ trait DatabasesBase $this->assertCount(1, $titleIndex['body']['attributes']); $this->assertEquals('title', $titleIndex['body']['attributes'][0]); - $releaseYearIndex = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/indexes', array_merge([ + $releaseYearIndex = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/indexes', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'releaseYear', 'type' => 'key', @@ -794,10 +793,10 @@ trait DatabasesBase $this->assertCount(1, $releaseYearIndex['body']['attributes']); $this->assertEquals('releaseYear', $releaseYearIndex['body']['attributes'][0]); - $releaseWithDate = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/indexes', array_merge([ + $releaseWithDate = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/indexes', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'releaseYearDated', 'type' => 'key', @@ -815,10 +814,10 @@ trait DatabasesBase // wait for database worker to create index sleep(2); - $movies = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'], array_merge([ + $movies = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), []); $this->assertIsArray($movies['body']['indexes']); @@ -830,11 +829,10 @@ trait DatabasesBase $this->assertEquals('available', $movies['body']['indexes'][1]['status']); $this->assertEquals('available', $movies['body']['indexes'][2]['status']); - - $releaseWithDate = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/indexes', array_merge([ + $releaseWithDate = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/indexes', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'birthDay', 'type' => 'key', @@ -856,7 +854,7 @@ trait DatabasesBase public function testCreateDocument(array $data): array { $databaseId = $data['databaseId']; - $document1 = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents', array_merge([ + $document1 = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -868,16 +866,16 @@ trait DatabasesBase 'actors' => [ 'Chris Evans', 'Samuel Jackson', - ] + ], ], 'permissions' => [ Permission::read(Role::user($this->getUser()['$id'])), Permission::update(Role::user($this->getUser()['$id'])), Permission::delete(Role::user($this->getUser()['$id'])), - ] + ], ]); - $document2 = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents', array_merge([ + $document2 = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -890,16 +888,16 @@ trait DatabasesBase 'Tom Holland', 'Zendaya Maree Stoermer', 'Samuel Jackson', - ] + ], ], 'permissions' => [ Permission::read(Role::user($this->getUser()['$id'])), Permission::update(Role::user($this->getUser()['$id'])), Permission::delete(Role::user($this->getUser()['$id'])), - ] + ], ]); - $document3 = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents', array_merge([ + $document3 = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -918,10 +916,10 @@ trait DatabasesBase Permission::read(Role::user($this->getUser()['$id'])), Permission::update(Role::user($this->getUser()['$id'])), Permission::delete(Role::user($this->getUser()['$id'])), - ] + ], ]); - $document4 = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents', array_merge([ + $document4 = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -933,7 +931,7 @@ trait DatabasesBase Permission::read(Role::user($this->getUser()['$id'])), Permission::update(Role::user($this->getUser()['$id'])), Permission::delete(Role::user($this->getUser()['$id'])), - ] + ], ]); $this->assertEquals(201, $document1['headers']['status-code']); @@ -989,7 +987,7 @@ trait DatabasesBase public function testListDocuments(array $data): array { $databaseId = $data['databaseId']; - $documents = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents', array_merge([ + $documents = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1011,7 +1009,7 @@ trait DatabasesBase $this->assertEquals($databaseId, $document['$databaseId']); } - $documents = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents', array_merge([ + $documents = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1033,10 +1031,10 @@ trait DatabasesBase $database = $this->client->call(Client::METHOD_POST, '/databases', [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ], [ 'databaseId' => ID::custom('default'), - 'name' => 'Default' + 'name' => 'Default', ]); $this->assertNotEmpty($database['body']['$id']); @@ -1045,11 +1043,10 @@ trait DatabasesBase /** * Test for SUCCESS */ - $movies = $this->client->call(Client::METHOD_POST, '/database/collections', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'collectionId' => ID::unique(), 'name' => 'Movies', @@ -1071,8 +1068,7 @@ trait DatabasesBase /** * Test for SUCCESS */ - - $documents = $this->client->call(Client::METHOD_GET, '/database/collections/' . $data['moviesId'] . '/documents', array_merge([ + $documents = $this->client->call(Client::METHOD_GET, '/database/collections/'.$data['moviesId'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -1090,7 +1086,7 @@ trait DatabasesBase { $databaseId = $data['databaseId']; foreach ($data['documents'] as $document) { - $response = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $document['$collectionId'] . '/documents/' . $document['$id'], array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$document['$collectionId'].'/documents/'.$document['$id'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -1117,7 +1113,7 @@ trait DatabasesBase /** * Test after without order. */ - $base = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents', array_merge([ + $base = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -1128,11 +1124,11 @@ trait DatabasesBase $this->assertEquals('Spider-Man: Homecoming', $base['body']['documents'][2]['title']); $this->assertCount(3, $base['body']['documents']); - $documents = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents', array_merge([ + $documents = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => ['cursorAfter("' . $base['body']['documents'][0]['$id'] . '")'], + 'queries' => ['cursorAfter("'.$base['body']['documents'][0]['$id'].'")'], ]); $this->assertEquals(200, $documents['headers']['status-code']); @@ -1140,11 +1136,11 @@ trait DatabasesBase $this->assertEquals($base['body']['documents'][2]['$id'], $documents['body']['documents'][1]['$id']); $this->assertCount(2, $documents['body']['documents']); - $documents = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents', array_merge([ + $documents = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => ['cursorAfter("' . $base['body']['documents'][2]['$id'] . '")'], + 'queries' => ['cursorAfter("'.$base['body']['documents'][2]['$id'].'")'], ]); $this->assertEquals(200, $documents['headers']['status-code']); @@ -1153,7 +1149,7 @@ trait DatabasesBase /** * Test with ASC order and after. */ - $base = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents', array_merge([ + $base = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1166,11 +1162,11 @@ trait DatabasesBase $this->assertEquals(2019, $base['body']['documents'][2]['releaseYear']); $this->assertCount(3, $base['body']['documents']); - $documents = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents', array_merge([ + $documents = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => ['cursorAfter("' . $base['body']['documents'][1]['$id'] . '")', 'orderAsc("releaseYear")'], + 'queries' => ['cursorAfter("'.$base['body']['documents'][1]['$id'].'")', 'orderAsc("releaseYear")'], ]); $this->assertEquals(200, $documents['headers']['status-code']); @@ -1180,7 +1176,7 @@ trait DatabasesBase /** * Test with DESC order and after. */ - $base = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents', array_merge([ + $base = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1193,11 +1189,11 @@ trait DatabasesBase $this->assertEquals(2019, $base['body']['documents'][0]['releaseYear']); $this->assertCount(3, $base['body']['documents']); - $documents = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents', array_merge([ + $documents = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => ['cursorAfter("' . $base['body']['documents'][1]['$id'] . '")', 'orderDesc("releaseYear")'], + 'queries' => ['cursorAfter("'.$base['body']['documents'][1]['$id'].'")', 'orderDesc("releaseYear")'], ]); $this->assertEquals(200, $documents['headers']['status-code']); @@ -1207,7 +1203,7 @@ trait DatabasesBase /** * Test after with unknown document. */ - $documents = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents', array_merge([ + $documents = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1228,7 +1224,7 @@ trait DatabasesBase /** * Test before without order. */ - $base = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents', array_merge([ + $base = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -1239,11 +1235,11 @@ trait DatabasesBase $this->assertEquals('Spider-Man: Homecoming', $base['body']['documents'][2]['title']); $this->assertCount(3, $base['body']['documents']); - $documents = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents', array_merge([ + $documents = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => ['cursorBefore("' . $base['body']['documents'][2]['$id'] . '")'], + 'queries' => ['cursorBefore("'.$base['body']['documents'][2]['$id'].'")'], ]); $this->assertEquals(200, $documents['headers']['status-code']); @@ -1251,11 +1247,11 @@ trait DatabasesBase $this->assertEquals($base['body']['documents'][1]['$id'], $documents['body']['documents'][1]['$id']); $this->assertCount(2, $documents['body']['documents']); - $documents = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents', array_merge([ + $documents = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => ['cursorBefore("' . $base['body']['documents'][0]['$id'] . '")'], + 'queries' => ['cursorBefore("'.$base['body']['documents'][0]['$id'].'")'], ]); $this->assertEquals(200, $documents['headers']['status-code']); @@ -1264,7 +1260,7 @@ trait DatabasesBase /** * Test with ASC order and after. */ - $base = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents', array_merge([ + $base = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1277,11 +1273,11 @@ trait DatabasesBase $this->assertEquals(2019, $base['body']['documents'][2]['releaseYear']); $this->assertCount(3, $base['body']['documents']); - $documents = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents', array_merge([ + $documents = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => ['cursorBefore("' . $base['body']['documents'][1]['$id'] . '")', 'orderAsc("releaseYear")'], + 'queries' => ['cursorBefore("'.$base['body']['documents'][1]['$id'].'")', 'orderAsc("releaseYear")'], ]); $this->assertEquals(200, $documents['headers']['status-code']); @@ -1291,7 +1287,7 @@ trait DatabasesBase /** * Test with DESC order and after. */ - $base = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents', array_merge([ + $base = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1304,11 +1300,11 @@ trait DatabasesBase $this->assertEquals(2019, $base['body']['documents'][0]['releaseYear']); $this->assertCount(3, $base['body']['documents']); - $documents = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents', array_merge([ + $documents = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => ['cursorBefore("' . $base['body']['documents'][1]['$id'] . '")', 'orderDesc("releaseYear")'], + 'queries' => ['cursorBefore("'.$base['body']['documents'][1]['$id'].'")', 'orderDesc("releaseYear")'], ]); $this->assertEquals(200, $documents['headers']['status-code']); @@ -1324,7 +1320,7 @@ trait DatabasesBase public function testListDocumentsLimitAndOffset(array $data): array { $databaseId = $data['databaseId']; - $documents = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents', array_merge([ + $documents = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1335,7 +1331,7 @@ trait DatabasesBase $this->assertEquals(1944, $documents['body']['documents'][0]['releaseYear']); $this->assertCount(1, $documents['body']['documents']); - $documents = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents', array_merge([ + $documents = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1356,7 +1352,7 @@ trait DatabasesBase public function testDocumentsListQueries(array $data): array { $databaseId = $data['databaseId']; - $documents = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents', array_merge([ + $documents = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1367,18 +1363,18 @@ trait DatabasesBase $this->assertEquals(1944, $documents['body']['documents'][0]['releaseYear']); $this->assertCount(1, $documents['body']['documents']); - $documents = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents', array_merge([ + $documents = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => ['equal("$id", "' . $documents['body']['documents'][0]['$id'] . '")'], + 'queries' => ['equal("$id", "'.$documents['body']['documents'][0]['$id'].'")'], ]); $this->assertEquals(200, $documents['headers']['status-code']); $this->assertEquals(1944, $documents['body']['documents'][0]['releaseYear']); $this->assertCount(1, $documents['body']['documents']); - $documents = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents', array_merge([ + $documents = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1389,7 +1385,7 @@ trait DatabasesBase $this->assertEquals(2017, $documents['body']['documents'][0]['releaseYear']); $this->assertCount(1, $documents['body']['documents']); - $documents = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents', array_merge([ + $documents = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1401,7 +1397,7 @@ trait DatabasesBase $this->assertEquals(2017, $documents['body']['documents'][1]['releaseYear']); $this->assertCount(2, $documents['body']['documents']); - $documents = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents', array_merge([ + $documents = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1411,7 +1407,7 @@ trait DatabasesBase $this->assertCount(1, $documents['body']['documents']); $this->assertEquals('Captain America', $documents['body']['documents'][0]['title']); - $documents = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents', array_merge([ + $documents = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1422,7 +1418,7 @@ trait DatabasesBase $this->assertEquals('Spider-Man: Far From Home', $documents['body']['documents'][0]['title']); $this->assertEquals('Spider-Man: Homecoming', $documents['body']['documents'][1]['title']); - $documents = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents', array_merge([ + $documents = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1431,7 +1427,7 @@ trait DatabasesBase $this->assertCount(3, $documents['body']['documents']); - $documents = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents', array_merge([ + $documents = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1443,7 +1439,7 @@ trait DatabasesBase /** * Test for Failure */ - $documents = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents', array_merge([ + $documents = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1458,11 +1454,11 @@ trait DatabasesBase $conditions[] = $i; } - $documents = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents', array_merge([ + $documents = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => ['equal("releaseYear", [' . implode(',', $conditions) . '])'], + 'queries' => ['equal("releaseYear", ['.implode(',', $conditions).'])'], ]); $this->assertEquals(400, $documents['headers']['status-code']); @@ -1470,20 +1466,19 @@ trait DatabasesBase $conditions = []; for ($i = 0; $i < 101; $i++) { - $conditions[] = "[" . $i . "] Too long title to cross 2k chars query limit"; + $conditions[] = '['.$i.'] Too long title to cross 2k chars query limit'; } - $documents = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents', array_merge([ + $documents = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => ['search("title", ' . implode(',', $conditions) . ')'], + 'queries' => ['search("title", '.implode(',', $conditions).')'], ]); $this->assertEquals(400, $documents['headers']['status-code']); - - $documents = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents', array_merge([ + $documents = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1504,7 +1499,7 @@ trait DatabasesBase public function testUpdateDocument(array $data): array { $databaseId = $data['databaseId']; - $document = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents', array_merge([ + $document = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1514,7 +1509,7 @@ trait DatabasesBase 'releaseYear' => 2017, 'birthDay' => '1976-06-12 14:12:55', 'actors' => [], - '$createdAt' => 5 // Should be ignored + '$createdAt' => 5, // Should be ignored ], 'permissions' => [ Permission::read(Role::user($this->getUser()['$id'])), @@ -1538,7 +1533,7 @@ trait DatabasesBase $this->assertContains(Permission::update(Role::user($this->getUser()['$id'])), $document['body']['$permissions']); $this->assertContains(Permission::delete(Role::user($this->getUser()['$id'])), $document['body']['$permissions']); - $document = $this->client->call(Client::METHOD_PATCH, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents/' . $id, array_merge([ + $document = $this->client->call(Client::METHOD_PATCH, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents/'.$id, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1563,7 +1558,7 @@ trait DatabasesBase $this->assertContains(Permission::update(Role::users()), $document['body']['$permissions']); $this->assertContains(Permission::delete(Role::users()), $document['body']['$permissions']); - $document = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents/' . $id, array_merge([ + $document = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents/'.$id, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -1586,7 +1581,7 @@ trait DatabasesBase public function testDeleteDocument(array $data): array { $databaseId = $data['databaseId']; - $document = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents', array_merge([ + $document = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1601,28 +1596,28 @@ trait DatabasesBase Permission::read(Role::user($this->getUser()['$id'])), Permission::update(Role::user($this->getUser()['$id'])), Permission::delete(Role::user($this->getUser()['$id'])), - ] + ], ]); $id = $document['body']['$id']; $this->assertEquals(201, $document['headers']['status-code']); - $document = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents/' . $id, array_merge([ + $document = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents/'.$id, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); $this->assertEquals(200, $document['headers']['status-code']); - $document = $this->client->call(Client::METHOD_DELETE, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents/' . $id, array_merge([ + $document = $this->client->call(Client::METHOD_DELETE, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents/'.$id, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); $this->assertEquals(204, $document['headers']['status-code']); - $document = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents/' . $id, array_merge([ + $document = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents/'.$id, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -1637,7 +1632,7 @@ trait DatabasesBase $database = $this->client->call(Client::METHOD_POST, '/databases', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'databaseId' => ID::unique(), 'name' => 'InvalidDocumentDatabase', @@ -1646,10 +1641,10 @@ trait DatabasesBase $this->assertEquals('InvalidDocumentDatabase', $database['body']['name']); $databaseId = $database['body']['$id']; - $collection = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections', array_merge([ + $collection = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'collectionId' => ID::unique(), 'name' => 'invalidDocumentStructure', @@ -1665,48 +1660,48 @@ trait DatabasesBase $collectionId = $collection['body']['$id']; - $email = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/attributes/email', array_merge([ + $email = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/attributes/email', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'email', 'required' => false, ]); - $enum = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/attributes/enum', array_merge([ + $enum = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/attributes/enum', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'enum', 'elements' => ['yes', 'no', 'maybe'], 'required' => false, ]); - $ip = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/attributes/ip', array_merge([ + $ip = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/attributes/ip', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'ip', 'required' => false, ]); - $url = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/attributes/url', array_merge([ + $url = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/attributes/url', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'url', 'size' => 256, 'required' => false, ]); - $range = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/attributes/integer', array_merge([ + $range = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/attributes/integer', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'range', 'required' => false, @@ -1715,10 +1710,10 @@ trait DatabasesBase ]); // TODO@kodumbeats min and max are rounded in error message - $floatRange = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/attributes/float', array_merge([ + $floatRange = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/attributes/float', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'floatRange', 'required' => false, @@ -1726,10 +1721,10 @@ trait DatabasesBase 'max' => 1.4, ]); - $probability = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/attributes/float', array_merge([ + $probability = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/attributes/float', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'probability', 'required' => false, @@ -1738,20 +1733,20 @@ trait DatabasesBase 'max' => 1, ]); - $upperBound = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/attributes/integer', array_merge([ + $upperBound = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/attributes/integer', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'upperBound', 'required' => false, 'max' => 10, ]); - $lowerBound = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/attributes/integer', array_merge([ + $lowerBound = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/attributes/integer', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'lowerBound', 'required' => false, @@ -1761,10 +1756,9 @@ trait DatabasesBase /** * Test for failure */ - - $invalidRange = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/attributes/integer', array_merge([ + $invalidRange = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/attributes/integer', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'invalidRange', 'required' => false, @@ -1772,9 +1766,9 @@ trait DatabasesBase 'max' => 3, ]); - $defaultArray = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/attributes/integer', array_merge([ + $defaultArray = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/attributes/integer', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'defaultArray', 'required' => false, @@ -1782,54 +1776,54 @@ trait DatabasesBase 'array' => true, ]); - $defaultRequired = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/attributes/integer', array_merge([ + $defaultRequired = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/attributes/integer', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'attributeId' => ID::custom('defaultRequired'), 'required' => true, - 'default' => 12 + 'default' => 12, ]); - $enumDefault = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/attributes/enum', array_merge([ + $enumDefault = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/attributes/enum', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'attributeId' => ID::custom('enumDefault'), 'elements' => ['north', 'west'], - 'default' => 'south' + 'default' => 'south', ]); - $enumDefaultStrict = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/attributes/enum', array_merge([ + $enumDefaultStrict = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/attributes/enum', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'attributeId' => ID::custom('enumDefault'), 'elements' => ['north', 'west'], - 'default' => 'NORTH' + 'default' => 'NORTH', ]); - $goodDatetime = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/attributes/datetime', array_merge([ + $goodDatetime = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/attributes/datetime', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'birthDay', 'required' => false, - 'default' => null + 'default' => null, ]); - $datetimeDefault = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/attributes/datetime', array_merge([ + $datetimeDefault = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/attributes/datetime', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'badBirthDay', 'required' => false, - 'default' => 'bad' + 'default' => 'bad', ]); $this->assertEquals(202, $email['headers']['status-code']); @@ -1853,7 +1847,7 @@ trait DatabasesBase // wait for worker to add attributes sleep(3); - $collection = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $collectionId, array_merge([ + $collection = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$collectionId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], 'x-appwrite-key' => $this->getProject()['apiKey'], @@ -1864,8 +1858,7 @@ trait DatabasesBase /** * Test for successful validation */ - - $goodEmail = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents', array_merge([ + $goodEmail = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1877,10 +1870,10 @@ trait DatabasesBase Permission::read(Role::user(ID::custom($this->getUser()['$id']))), Permission::update(Role::user(ID::custom($this->getUser()['$id']))), Permission::delete(Role::user(ID::custom($this->getUser()['$id']))), - ] + ], ]); - $goodEnum = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents', array_merge([ + $goodEnum = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1892,10 +1885,10 @@ trait DatabasesBase Permission::read(Role::user(ID::custom($this->getUser()['$id']))), Permission::update(Role::user(ID::custom($this->getUser()['$id']))), Permission::delete(Role::user(ID::custom($this->getUser()['$id']))), - ] + ], ]); - $goodIp = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents', array_merge([ + $goodIp = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1907,10 +1900,10 @@ trait DatabasesBase Permission::read(Role::user(ID::custom($this->getUser()['$id']))), Permission::update(Role::user(ID::custom($this->getUser()['$id']))), Permission::delete(Role::user(ID::custom($this->getUser()['$id']))), - ] + ], ]); - $goodUrl = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents', array_merge([ + $goodUrl = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1922,10 +1915,10 @@ trait DatabasesBase Permission::read(Role::user(ID::custom($this->getUser()['$id']))), Permission::update(Role::user(ID::custom($this->getUser()['$id']))), Permission::delete(Role::user(ID::custom($this->getUser()['$id']))), - ] + ], ]); - $goodRange = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents', array_merge([ + $goodRange = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1937,10 +1930,10 @@ trait DatabasesBase Permission::read(Role::user(ID::custom($this->getUser()['$id']))), Permission::update(Role::user(ID::custom($this->getUser()['$id']))), Permission::delete(Role::user(ID::custom($this->getUser()['$id']))), - ] + ], ]); - $goodFloatRange = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents', array_merge([ + $goodFloatRange = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1952,10 +1945,10 @@ trait DatabasesBase Permission::read(Role::user(ID::custom($this->getUser()['$id']))), Permission::update(Role::user(ID::custom($this->getUser()['$id']))), Permission::delete(Role::user(ID::custom($this->getUser()['$id']))), - ] + ], ]); - $goodProbability = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents', array_merge([ + $goodProbability = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1967,10 +1960,10 @@ trait DatabasesBase Permission::read(Role::user(ID::custom($this->getUser()['$id']))), Permission::update(Role::user(ID::custom($this->getUser()['$id']))), Permission::delete(Role::user(ID::custom($this->getUser()['$id']))), - ] + ], ]); - $notTooHigh = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents', array_merge([ + $notTooHigh = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1982,10 +1975,10 @@ trait DatabasesBase Permission::read(Role::user(ID::custom($this->getUser()['$id']))), Permission::update(Role::user(ID::custom($this->getUser()['$id']))), Permission::delete(Role::user(ID::custom($this->getUser()['$id']))), - ] + ], ]); - $notTooLow = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents', array_merge([ + $notTooLow = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1997,7 +1990,7 @@ trait DatabasesBase Permission::read(Role::user(ID::custom($this->getUser()['$id']))), Permission::update(Role::user(ID::custom($this->getUser()['$id']))), Permission::delete(Role::user(ID::custom($this->getUser()['$id']))), - ] + ], ]); $this->assertEquals(201, $goodEmail['headers']['status-code']); @@ -2014,7 +2007,7 @@ trait DatabasesBase * Test that custom validators reject documents */ - $badEmail = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents', array_merge([ + $badEmail = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -2026,10 +2019,10 @@ trait DatabasesBase Permission::read(Role::user(ID::custom($this->getUser()['$id']))), Permission::update(Role::user(ID::custom($this->getUser()['$id']))), Permission::delete(Role::user(ID::custom($this->getUser()['$id']))), - ] + ], ]); - $badEnum = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents', array_merge([ + $badEnum = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -2041,10 +2034,10 @@ trait DatabasesBase Permission::read(Role::user(ID::custom($this->getUser()['$id']))), Permission::update(Role::user(ID::custom($this->getUser()['$id']))), Permission::delete(Role::user(ID::custom($this->getUser()['$id']))), - ] + ], ]); - $badIp = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents', array_merge([ + $badIp = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -2056,10 +2049,10 @@ trait DatabasesBase Permission::read(Role::user(ID::custom($this->getUser()['$id']))), Permission::update(Role::user(ID::custom($this->getUser()['$id']))), Permission::delete(Role::user(ID::custom($this->getUser()['$id']))), - ] + ], ]); - $badUrl = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents', array_merge([ + $badUrl = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -2071,10 +2064,10 @@ trait DatabasesBase Permission::read(Role::user(ID::custom($this->getUser()['$id']))), Permission::update(Role::user(ID::custom($this->getUser()['$id']))), Permission::delete(Role::user(ID::custom($this->getUser()['$id']))), - ] + ], ]); - $badRange = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents', array_merge([ + $badRange = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -2086,10 +2079,10 @@ trait DatabasesBase Permission::read(Role::user(ID::custom($this->getUser()['$id']))), Permission::update(Role::user(ID::custom($this->getUser()['$id']))), Permission::delete(Role::user(ID::custom($this->getUser()['$id']))), - ] + ], ]); - $badFloatRange = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents', array_merge([ + $badFloatRange = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -2101,10 +2094,10 @@ trait DatabasesBase Permission::read(Role::user(ID::custom($this->getUser()['$id']))), Permission::update(Role::user(ID::custom($this->getUser()['$id']))), Permission::delete(Role::user(ID::custom($this->getUser()['$id']))), - ] + ], ]); - $badProbability = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents', array_merge([ + $badProbability = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -2116,10 +2109,10 @@ trait DatabasesBase Permission::read(Role::user(ID::custom($this->getUser()['$id']))), Permission::update(Role::user(ID::custom($this->getUser()['$id']))), Permission::delete(Role::user(ID::custom($this->getUser()['$id']))), - ] + ], ]); - $tooHigh = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents', array_merge([ + $tooHigh = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -2131,10 +2124,10 @@ trait DatabasesBase Permission::read(Role::user(ID::custom($this->getUser()['$id']))), Permission::update(Role::user(ID::custom($this->getUser()['$id']))), Permission::delete(Role::user(ID::custom($this->getUser()['$id']))), - ] + ], ]); - $tooLow = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents', array_merge([ + $tooLow = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -2146,10 +2139,10 @@ trait DatabasesBase Permission::read(Role::user(ID::custom($this->getUser()['$id']))), Permission::update(Role::user(ID::custom($this->getUser()['$id']))), Permission::delete(Role::user(ID::custom($this->getUser()['$id']))), - ] + ], ]); - $badTime = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents', array_merge([ + $badTime = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -2157,8 +2150,8 @@ trait DatabasesBase 'data' => [ 'birthDay' => '2020-10-10 27:30:10+01:00', ], - 'read' => ['user:' . $this->getUser()['$id']], - 'write' => ['user:' . $this->getUser()['$id']], + 'read' => ['user:'.$this->getUser()['$id']], + 'write' => ['user:'.$this->getUser()['$id']], ]); $this->assertEquals(400, $badEmail['headers']['status-code']); @@ -2188,7 +2181,7 @@ trait DatabasesBase public function testDefaultPermissions(array $data): array { $databaseId = $data['databaseId']; - $document = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents', array_merge([ + $document = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -2221,7 +2214,7 @@ trait DatabasesBase // Updated Permissions - $document = $this->client->call(Client::METHOD_PATCH, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents/' . $id, array_merge([ + $document = $this->client->call(Client::METHOD_PATCH, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents/'.$id, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -2232,7 +2225,7 @@ trait DatabasesBase ], 'permissions' => [ Permission::read(Role::user($this->getUser()['$id'])), - Permission::update(Role::user($this->getUser()['$id'])) + Permission::update(Role::user($this->getUser()['$id'])), ], ]); @@ -2249,7 +2242,7 @@ trait DatabasesBase Permission::update(Role::user($this->getUser()['$id'])), ], $document['body']['$permissions']); - $document = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents/' . $id, array_merge([ + $document = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents/'.$id, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -2266,7 +2259,7 @@ trait DatabasesBase // Reset Permissions - $document = $this->client->call(Client::METHOD_PATCH, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents/' . $id, array_merge([ + $document = $this->client->call(Client::METHOD_PATCH, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents/'.$id, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -2285,7 +2278,7 @@ trait DatabasesBase $this->assertEquals([], $document['body']['$permissions']); // Check client side can no longer read the document. - $document = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents/' . $id, array_merge([ + $document = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents/'.$id, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -2307,7 +2300,7 @@ trait DatabasesBase $database = $this->client->call(Client::METHOD_POST, '/databases', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'databaseId' => ID::unique(), 'name' => 'EnforceCollectionAndDocumentPermissions', @@ -2317,10 +2310,10 @@ trait DatabasesBase $databaseId = $database['body']['$id']; $user = $this->getUser()['$id']; - $collection = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections', array_merge([ + $collection = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'collectionId' => ID::unique(), 'name' => 'enforceCollectionAndDocumentPermissions', @@ -2341,10 +2334,10 @@ trait DatabasesBase sleep(2); - $attribute = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/attributes/string', array_merge([ + $attribute = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/attributes/string', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'attribute', 'size' => 64, @@ -2357,10 +2350,10 @@ trait DatabasesBase // wait for db to add attribute sleep(2); - $index = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/indexes', array_merge([ + $index = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/indexes', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'key_attribute', 'type' => 'key', @@ -2373,7 +2366,7 @@ trait DatabasesBase // wait for db to add attribute sleep(2); - $document1 = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents', array_merge([ + $document1 = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -2385,12 +2378,12 @@ trait DatabasesBase Permission::read(Role::user($user)), Permission::update(Role::user($user)), Permission::delete(Role::user($user)), - ] + ], ]); $this->assertEquals(201, $document1['headers']['status-code']); - $document2 = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents', array_merge([ + $document2 = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -2401,15 +2394,15 @@ trait DatabasesBase 'permissions' => [ Permission::update(Role::user($user)), Permission::delete(Role::user($user)), - ] + ], ]); $this->assertEquals(201, $document2['headers']['status-code']); - $document3 = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents', [ + $document3 = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents', [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ], [ 'documentId' => ID::unique(), 'data' => [ @@ -2423,7 +2416,7 @@ trait DatabasesBase $this->assertEquals(201, $document3['headers']['status-code']); - $documentsUser1 = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents', array_merge([ + $documentsUser1 = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -2432,7 +2425,7 @@ trait DatabasesBase $this->assertEquals(3, $documentsUser1['body']['total']); $this->assertCount(3, $documentsUser1['body']['documents']); - $document3GetWithCollectionRead = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents/' . $document3['body']['$id'], array_merge([ + $document3GetWithCollectionRead = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents/'.$document3['body']['$id'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -2440,7 +2433,7 @@ trait DatabasesBase // Current user has read permission on the collection so can get any document $this->assertEquals(200, $document3GetWithCollectionRead['headers']['status-code']); - $email = uniqid() . 'user@localhost.test'; + $email = uniqid().'user@localhost.test'; $password = 'password'; $name = 'User Name'; $this->client->call(Client::METHOD_POST, '/account', [ @@ -2461,33 +2454,33 @@ trait DatabasesBase 'email' => $email, 'password' => $password, ]); - $session2 = $this->client->parseCookie((string)$session2['headers']['set-cookie'])['a_session_' . $this->getProject()['$id']]; + $session2 = $this->client->parseCookie((string) $session2['headers']['set-cookie'])['a_session_'.$this->getProject()['$id']]; - $document3GetWithDocumentRead = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents/' . $document3['body']['$id'], [ + $document3GetWithDocumentRead = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents/'.$document3['body']['$id'], [ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session2, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session2, ]); // Current user has no collection permissions but has read permission for this document $this->assertEquals(200, $document3GetWithDocumentRead['headers']['status-code']); - $document2GetFailure = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents/' . $document2['body']['$id'], [ + $document2GetFailure = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents/'.$document2['body']['$id'], [ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session2, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session2, ]); // Current user has no collection or document permissions for this document $this->assertEquals(404, $document2GetFailure['headers']['status-code']); - $documentsUser2 = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents', [ + $documentsUser2 = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents', [ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session2, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session2, ]); // Current user has no collection permissions but has read permission for one document @@ -2500,7 +2493,7 @@ trait DatabasesBase $database = $this->client->call(Client::METHOD_POST, '/databases', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'databaseId' => ID::unique(), 'name' => 'EnforceCollectionPermissions', @@ -2510,10 +2503,10 @@ trait DatabasesBase $databaseId = $database['body']['$id']; $user = $this->getUser()['$id']; - $collection = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections', array_merge([ + $collection = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'collectionId' => ID::unique(), 'name' => 'enforceCollectionPermissions', @@ -2533,10 +2526,10 @@ trait DatabasesBase sleep(2); - $attribute = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/attributes/string', array_merge([ + $attribute = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/attributes/string', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'attribute', 'size' => 64, @@ -2549,10 +2542,10 @@ trait DatabasesBase // wait for db to add attribute sleep(2); - $index = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/indexes', array_merge([ + $index = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/indexes', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'key_attribute', 'type' => 'key', @@ -2565,7 +2558,7 @@ trait DatabasesBase // wait for db to add attribute sleep(2); - $document1 = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents', array_merge([ + $document1 = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -2577,12 +2570,12 @@ trait DatabasesBase Permission::read(Role::user($user)), Permission::update(Role::user($user)), Permission::delete(Role::user($user)), - ] + ], ]); $this->assertEquals(201, $document1['headers']['status-code']); - $document2 = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents', array_merge([ + $document2 = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -2593,15 +2586,15 @@ trait DatabasesBase 'permissions' => [ Permission::update(Role::user($user)), Permission::delete(Role::user($user)), - ] + ], ]); $this->assertEquals(201, $document2['headers']['status-code']); - $document3 = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents', [ + $document3 = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents', [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ], [ 'documentId' => ID::unique(), 'data' => [ @@ -2615,7 +2608,7 @@ trait DatabasesBase $this->assertEquals(201, $document3['headers']['status-code']); - $documentsUser1 = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents', array_merge([ + $documentsUser1 = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -2624,7 +2617,7 @@ trait DatabasesBase $this->assertEquals(3, $documentsUser1['body']['total']); $this->assertCount(3, $documentsUser1['body']['documents']); - $document3GetWithCollectionRead = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents/' . $document3['body']['$id'], array_merge([ + $document3GetWithCollectionRead = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents/'.$document3['body']['$id'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -2632,7 +2625,7 @@ trait DatabasesBase // Current user has read permission on the collection so can get any document $this->assertEquals(200, $document3GetWithCollectionRead['headers']['status-code']); - $email = uniqid() . 'user2@localhost.test'; + $email = uniqid().'user2@localhost.test'; $password = 'password'; $name = 'User Name'; $this->client->call(Client::METHOD_POST, '/account', [ @@ -2653,44 +2646,43 @@ trait DatabasesBase 'email' => $email, 'password' => $password, ]); - $session2 = $this->client->parseCookie((string)$session2['headers']['set-cookie'])['a_session_' . $this->getProject()['$id']]; + $session2 = $this->client->parseCookie((string) $session2['headers']['set-cookie'])['a_session_'.$this->getProject()['$id']]; - $document3GetWithDocumentRead = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents/' . $document3['body']['$id'], [ + $document3GetWithDocumentRead = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents/'.$document3['body']['$id'], [ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session2, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session2, ]); // Current user has no collection permissions and document permissions are disabled $this->assertEquals(401, $document3GetWithDocumentRead['headers']['status-code']); - $documentsUser2 = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents', [ + $documentsUser2 = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents', [ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session2, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session2, ]); // Current user has no collection permissions and document permissions are disabled $this->assertEquals(401, $documentsUser2['headers']['status-code']); - // Enable document permissions - $collection = $this->client->call(CLient::METHOD_PUT, '/databases/' . $databaseId . '/collections/' . $collectionId, [ + $collection = $this->client->call(CLient::METHOD_PUT, '/databases/'.$databaseId.'/collections/'.$collectionId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ], [ 'name' => $collection['body']['name'], 'documentSecurity' => true, ]); - $documentsUser2 = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents', [ + $documentsUser2 = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents', [ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session2, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session2, ]); // Current user has no collection permissions read access to one document @@ -2704,10 +2696,10 @@ trait DatabasesBase public function testUniqueIndexDuplicate(array $data): array { $databaseId = $data['databaseId']; - $uniqueIndex = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/indexes', array_merge([ + $uniqueIndex = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/indexes', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'unique_title', 'type' => 'unique', @@ -2719,7 +2711,7 @@ trait DatabasesBase sleep(2); // test for failure - $duplicate = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents', array_merge([ + $duplicate = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -2730,19 +2722,19 @@ trait DatabasesBase 'actors' => [ 'Chris Evans', 'Samuel Jackson', - ] + ], ], 'permissions' => [ Permission::read(Role::user(ID::custom($this->getUser()['$id']))), Permission::update(Role::user(ID::custom($this->getUser()['$id']))), Permission::delete(Role::user(ID::custom($this->getUser()['$id']))), - ] + ], ]); $this->assertEquals(409, $duplicate['headers']['status-code']); // Test for exception when updating document to conflict - $document = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents', array_merge([ + $document = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -2753,19 +2745,19 @@ trait DatabasesBase 'actors' => [ 'Chris Evans', 'Samuel Jackson', - ] + ], ], 'permissions' => [ Permission::read(Role::user(ID::custom($this->getUser()['$id']))), Permission::update(Role::user(ID::custom($this->getUser()['$id']))), Permission::delete(Role::user(ID::custom($this->getUser()['$id']))), - ] + ], ]); $this->assertEquals(201, $document['headers']['status-code']); // Test for exception when updating document to conflict - $duplicate = $this->client->call(Client::METHOD_PATCH, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/documents/' . $document['body']['$id'], array_merge([ + $duplicate = $this->client->call(Client::METHOD_PATCH, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/documents/'.$document['body']['$id'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -2776,13 +2768,13 @@ trait DatabasesBase 'actors' => [ 'Chris Evans', 'Samuel Jackson', - ] + ], ], 'permissions' => [ Permission::read(Role::user(ID::custom($this->getUser()['$id']))), Permission::update(Role::user(ID::custom($this->getUser()['$id']))), Permission::delete(Role::user(ID::custom($this->getUser()['$id']))), - ] + ], ]); $this->assertEquals(409, $duplicate['headers']['status-code']); @@ -2801,15 +2793,15 @@ trait DatabasesBase ], $this->getHeaders()) : [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]; - $document = $this->client->call(Client::METHOD_POST, '/databases/' . $data['databaseId'] . '/collections/' . $data['moviesId'] . '/documents', $headers, [ + $document = $this->client->call(Client::METHOD_POST, '/databases/'.$data['databaseId'].'/collections/'.$data['moviesId'].'/documents', $headers, [ 'documentId' => ID::unique(), 'data' => [ 'title' => 'Creation Date Test', - 'releaseYear' => 2000 - ] + 'releaseYear' => 2000, + ], ]); $this->assertEquals($document['body']['title'], 'Creation Date Test'); @@ -2820,10 +2812,10 @@ trait DatabasesBase \sleep(1); - $document = $this->client->call(Client::METHOD_PATCH, '/databases/' . $data['databaseId'] . '/collections/' . $data['moviesId'] . '/documents/' . $documentId, $headers, [ + $document = $this->client->call(Client::METHOD_PATCH, '/databases/'.$data['databaseId'].'/collections/'.$data['moviesId'].'/documents/'.$documentId, $headers, [ 'data' => [ 'title' => 'Updated Date Test', - ] + ], ]); $updatedAtSecond = $document['body']['$updatedAt']; @@ -2834,12 +2826,12 @@ trait DatabasesBase \sleep(1); - $document = $this->client->call(Client::METHOD_PATCH, '/databases/' . $data['databaseId'] . '/collections/' . $data['moviesId'] . '/documents/' . $documentId, $headers, [ + $document = $this->client->call(Client::METHOD_PATCH, '/databases/'.$data['databaseId'].'/collections/'.$data['moviesId'].'/documents/'.$documentId, $headers, [ 'data' => [ 'title' => 'Again Updated Date Test', '$createdAt' => '2022-08-01 13:09:23.040', // $createdAt is not updatable - '$updatedAt' => '2022-08-01 13:09:23.050' // system will update it not api - ] + '$updatedAt' => '2022-08-01 13:09:23.050', // system will update it not api + ], ]); $this->assertEquals($document['body']['title'], 'Again Updated Date Test'); @@ -2858,7 +2850,7 @@ trait DatabasesBase $database = $this->client->call(Client::METHOD_POST, '/databases', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'databaseId' => ID::unique(), 'name' => 'Empty Permissions', @@ -2868,10 +2860,10 @@ trait DatabasesBase $databaseId = $database['body']['$id']; // Create collection - $movies = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/', array_merge([ + $movies = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'collectionId' => ID::unique(), 'name' => 'Movies', @@ -2890,10 +2882,10 @@ trait DatabasesBase $moviesId = $movies['body']['$id']; // create attribute - $title = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $moviesId . '/attributes/string', array_merge([ + $title = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$moviesId.'/attributes/string', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'title', 'size' => 256, @@ -2906,7 +2898,7 @@ trait DatabasesBase sleep(2); // add document - $document = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $moviesId . '/documents', array_merge([ + $document = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$moviesId.'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -2930,20 +2922,20 @@ trait DatabasesBase $this->assertContains(Permission::delete(Role::any()), $document['body']['$permissions']); // Send only read permission - $document = $this->client->call(Client::METHOD_PATCH, '/databases/' . $databaseId . '/collections/' . $moviesId . '/documents/' . $id, array_merge([ + $document = $this->client->call(Client::METHOD_PATCH, '/databases/'.$databaseId.'/collections/'.$moviesId.'/documents/'.$id, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'permissions' => [ Permission::read(Role::user(ID::custom($this->getUser()['$id']))), - ] + ], ]); $this->assertEquals(200, $document['headers']['status-code']); $this->assertCount(1, $document['body']['$permissions']); // Send only mutation permissions - $document = $this->client->call(Client::METHOD_PATCH, '/databases/' . $databaseId . '/collections/' . $moviesId . '/documents/' . $id, array_merge([ + $document = $this->client->call(Client::METHOD_PATCH, '/databases/'.$databaseId.'/collections/'.$moviesId.'/documents/'.$id, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -2961,7 +2953,7 @@ trait DatabasesBase } // remove collection - $this->client->call(Client::METHOD_DELETE, '/databases/' . $databaseId . '/collections/' . $moviesId, array_merge([ + $this->client->call(Client::METHOD_DELETE, '/databases/'.$databaseId.'/collections/'.$moviesId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -2979,39 +2971,39 @@ trait DatabasesBase /** * Test for SUCCESS */ - $collection = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections', array_merge([ + $collection = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'collectionId' => ID::unique(), - 'name' => 'Boolean' + 'name' => 'Boolean', ]); $this->assertEquals(201, $collection['headers']['status-code']); $collectionId = $collection['body']['$id']; - $true = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/attributes/boolean', array_merge([ + $true = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/attributes/boolean', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'true', 'required' => false, - 'default' => true + 'default' => true, ]); $this->assertEquals(202, $true['headers']['status-code']); - $false = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/attributes/boolean', array_merge([ + $false = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/attributes/boolean', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'false', 'required' => false, - 'default' => false + 'default' => false, ]); $this->assertEquals(202, $false['headers']['status-code']); diff --git a/tests/e2e/Services/Databases/DatabasesConsoleClientTest.php b/tests/e2e/Services/Databases/DatabasesConsoleClientTest.php index ad97a2bb3e..92d0a6027a 100644 --- a/tests/e2e/Services/Databases/DatabasesConsoleClientTest.php +++ b/tests/e2e/Services/Databases/DatabasesConsoleClientTest.php @@ -2,9 +2,9 @@ namespace Tests\E2E\Services\Databases; -use Tests\E2E\Scopes\Scope; -use Tests\E2E\Scopes\ProjectCustom; use Tests\E2E\Client; +use Tests\E2E\Scopes\ProjectCustom; +use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\SideConsole; use Utopia\Database\Helpers\ID; use Utopia\Database\Helpers\Permission; @@ -20,7 +20,7 @@ class DatabasesConsoleClientTest extends Scope $database = $this->client->call(Client::METHOD_POST, '/databases', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'databaseId' => ID::unique(), 'name' => 'invalidDocumentDatabase', @@ -32,7 +32,7 @@ class DatabasesConsoleClientTest extends Scope /** * Test for SUCCESS */ - $movies = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections', array_merge([ + $movies = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -98,7 +98,6 @@ class DatabasesConsoleClientTest extends Scope // $this->assertIsArray($response['body']['collectionsDelete']); // } - /** * @depends testCreateCollection */ @@ -108,21 +107,20 @@ class DatabasesConsoleClientTest extends Scope /** * Test for FAILURE */ - - $response = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/usage', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/usage', array_merge([ 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'] + 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'range' => '32h' + 'range' => '32h', ]); $this->assertEquals(400, $response['headers']['status-code']); - $response = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/randomCollectionId/usage', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/randomCollectionId/usage', array_merge([ 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'] + 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'range' => '24h' + 'range' => '24h', ]); $this->assertEquals(404, $response['headers']['status-code']); @@ -130,11 +128,11 @@ class DatabasesConsoleClientTest extends Scope /** * Test for SUCCESS */ - $response = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/usage', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/usage', array_merge([ 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'] + 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'range' => '24h' + 'range' => '24h', ]); $this->assertEquals(200, $response['headers']['status-code']); @@ -156,7 +154,7 @@ class DatabasesConsoleClientTest extends Scope /** * Test for SUCCESS */ - $logs = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/logs', array_merge([ + $logs = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/logs', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -165,11 +163,11 @@ class DatabasesConsoleClientTest extends Scope $this->assertIsArray($logs['body']['logs']); $this->assertIsNumeric($logs['body']['total']); - $logs = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/logs', array_merge([ + $logs = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/logs', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'limit' => 1 + 'limit' => 1, ]); $this->assertEquals(200, $logs['headers']['status-code']); @@ -177,23 +175,23 @@ class DatabasesConsoleClientTest extends Scope $this->assertLessThanOrEqual(1, count($logs['body']['logs'])); $this->assertIsNumeric($logs['body']['total']); - $logs = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/logs', array_merge([ + $logs = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/logs', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'offset' => 1 + 'offset' => 1, ]); $this->assertEquals(200, $logs['headers']['status-code']); $this->assertIsArray($logs['body']['logs']); $this->assertIsNumeric($logs['body']['total']); - $logs = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['moviesId'] . '/logs', array_merge([ + $logs = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['moviesId'].'/logs', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'offset' => 1, - 'limit' => 1 + 'limit' => 1, ]); $this->assertEquals(200, $logs['headers']['status-code']); diff --git a/tests/e2e/Services/Databases/DatabasesCustomClientTest.php b/tests/e2e/Services/Databases/DatabasesCustomClientTest.php index 748070161d..a41c4b739c 100644 --- a/tests/e2e/Services/Databases/DatabasesCustomClientTest.php +++ b/tests/e2e/Services/Databases/DatabasesCustomClientTest.php @@ -3,8 +3,8 @@ namespace Tests\E2E\Services\Databases; use Tests\E2E\Client; -use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\ProjectCustom; +use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\SideClient; use Utopia\Database\Helpers\ID; use Utopia\Database\Helpers\Permission; @@ -21,23 +21,22 @@ class DatabasesCustomClientTest extends Scope /** * Test for SUCCESS */ - $database = $this->client->call(Client::METHOD_POST, '/databases', [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ], [ 'databaseId' => ID::unique(), - 'name' => 'Test Database' + 'name' => 'Test Database', ]); $databaseId = $database['body']['$id']; // Collection aliases write to create, update, delete - $movies = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections', array_merge([ + $movies = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'collectionId' => ID::unique(), 'name' => 'Movies', @@ -53,10 +52,10 @@ class DatabasesCustomClientTest extends Scope $this->assertContains(Permission::update(Role::user($this->getUser()['$id'])), $movies['body']['$permissions']); $this->assertContains(Permission::delete(Role::user($this->getUser()['$id'])), $movies['body']['$permissions']); - $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $moviesId . '/attributes/string', array_merge([ + $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$moviesId.'/attributes/string', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'title', 'size' => 256, @@ -66,7 +65,7 @@ class DatabasesCustomClientTest extends Scope sleep(1); // Document aliases write to update, delete - $document1 = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $moviesId . '/documents', array_merge([ + $document1 = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$moviesId.'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -76,7 +75,7 @@ class DatabasesCustomClientTest extends Scope ], 'permissions' => [ Permission::write(Role::user($this->getUser()['$id'])), - ] + ], ]); $this->assertNotContains(Permission::create(Role::user($this->getUser()['$id'])), $document1['body']['$permissions']); @@ -88,7 +87,7 @@ class DatabasesCustomClientTest extends Scope */ // Document does not allow create permission - $document2 = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $moviesId . '/documents', array_merge([ + $document2 = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$moviesId.'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -98,7 +97,7 @@ class DatabasesCustomClientTest extends Scope ], 'permissions' => [ Permission::create(Role::user($this->getUser()['$id'])), - ] + ], ]); $this->assertEquals(400, $document2['headers']['status-code']); @@ -112,7 +111,7 @@ class DatabasesCustomClientTest extends Scope $response = $this->client->call(Client::METHOD_GET, '/account', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ], $this->getHeaders())); $this->assertEquals(200, $response['headers']['status-code']); @@ -121,7 +120,7 @@ class DatabasesCustomClientTest extends Scope $database = $this->client->call(Client::METHOD_POST, '/databases', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'databaseId' => ID::custom('permissionCheckDatabase'), 'name' => 'Test Database', @@ -131,10 +130,10 @@ class DatabasesCustomClientTest extends Scope $databaseId = $database['body']['$id']; // Create collection - $response = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections', array_merge([ + $response = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'collectionId' => ID::custom('permissionCheck'), 'name' => 'permissionCheck', @@ -144,10 +143,10 @@ class DatabasesCustomClientTest extends Scope $this->assertEquals(201, $response['headers']['status-code']); // Add attribute to collection - $response = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/permissionCheck/attributes/string', array_merge([ + $response = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/permissionCheck/attributes/string', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'name', 'size' => 255, @@ -159,10 +158,10 @@ class DatabasesCustomClientTest extends Scope sleep(2); // Creating document by server, give read permission to our user + some other user - $response = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/permissionCheck/documents', array_merge([ + $response = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/permissionCheck/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'documentId' => ID::custom('permissionCheckDocument'), 'data' => [ @@ -180,44 +179,43 @@ class DatabasesCustomClientTest extends Scope // Update document // This is the point of this test. We should be allowed to do this action, and it should not fail on permission check - $response = $this->client->call(Client::METHOD_PATCH, '/databases/' . $databaseId . '/collections/permissionCheck/documents/permissionCheckDocument', array_merge([ + $response = $this->client->call(Client::METHOD_PATCH, '/databases/'.$databaseId.'/collections/permissionCheck/documents/permissionCheckDocument', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'data' => [ 'name' => 'AppwriteExpert', - ] + ], ]); $this->assertEquals(200, $response['headers']['status-code']); // Get name of the document, should be the new one - $response = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/permissionCheck/documents/permissionCheckDocument', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/permissionCheck/documents/permissionCheckDocument', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); $this->assertEquals(200, $response['headers']['status-code']); - $this->assertEquals("AppwriteExpert", $response['body']['name']); + $this->assertEquals('AppwriteExpert', $response['body']['name']); // Cleanup to prevent collision with other tests // Delete collection - $response = $this->client->call(Client::METHOD_DELETE, '/databases/' . $databaseId . '/collections/permissionCheck', array_merge([ + $response = $this->client->call(Client::METHOD_DELETE, '/databases/'.$databaseId.'/collections/permissionCheck', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ])); $this->assertEquals(204, $response['headers']['status-code']); - // Wait for database worker to finish deleting collection sleep(2); // Make sure collection has been deleted - $response = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/permissionCheck', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/permissionCheck', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ])); $this->assertEquals(404, $response['headers']['status-code']); diff --git a/tests/e2e/Services/Databases/DatabasesCustomServerTest.php b/tests/e2e/Services/Databases/DatabasesCustomServerTest.php index 19a56941eb..a560de4724 100644 --- a/tests/e2e/Services/Databases/DatabasesCustomServerTest.php +++ b/tests/e2e/Services/Databases/DatabasesCustomServerTest.php @@ -2,10 +2,10 @@ namespace Tests\E2E\Services\Databases; +use Tests\E2E\Client; use Tests\E2E\Scopes\ProjectCustom; use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\SideServer; -use Tests\E2E\Client; use Utopia\Database\Helpers\ID; use Utopia\Database\Helpers\Permission; use Utopia\Database\Helpers\Role; @@ -21,7 +21,7 @@ class DatabasesCustomServerTest extends Scope $test1 = $this->client->call(Client::METHOD_POST, '/databases', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'databaseId' => ID::custom('first'), 'name' => 'Test 1', @@ -32,7 +32,7 @@ class DatabasesCustomServerTest extends Scope $test2 = $this->client->call(Client::METHOD_POST, '/databases', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'databaseId' => ID::custom('second'), 'name' => 'Test 2', @@ -55,7 +55,7 @@ class DatabasesCustomServerTest extends Scope 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'limit(1)' ], + 'queries' => ['limit(1)'], ]); $this->assertEquals(200, $databases['headers']['status-code']); $this->assertCount(1, $databases['body']['databases']); @@ -64,7 +64,7 @@ class DatabasesCustomServerTest extends Scope 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'offset(1)' ], + 'queries' => ['offset(1)'], ]); $this->assertEquals(200, $databases['headers']['status-code']); $this->assertCount(1, $databases['body']['databases']); @@ -73,7 +73,7 @@ class DatabasesCustomServerTest extends Scope 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'equal("name", ["Test 1", "Test 2"])' ], + 'queries' => ['equal("name", ["Test 1", "Test 2"])'], ]); $this->assertEquals(200, $databases['headers']['status-code']); $this->assertCount(2, $databases['body']['databases']); @@ -82,7 +82,7 @@ class DatabasesCustomServerTest extends Scope 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'equal("name", "Test 2")' ], + 'queries' => ['equal("name", "Test 2")'], ]); $this->assertEquals(200, $databases['headers']['status-code']); $this->assertCount(1, $databases['body']['databases']); @@ -91,7 +91,7 @@ class DatabasesCustomServerTest extends Scope 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'equal("$id", "first")' ], + 'queries' => ['equal("$id", "first")'], ]); $this->assertEquals(200, $databases['headers']['status-code']); $this->assertCount(1, $databases['body']['databases']); @@ -103,7 +103,7 @@ class DatabasesCustomServerTest extends Scope 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'orderDesc("")' ], + 'queries' => ['orderDesc("")'], ]); $this->assertEquals(2, $databases['body']['total']); @@ -122,7 +122,7 @@ class DatabasesCustomServerTest extends Scope 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'cursorAfter("' . $base['body']['databases'][0]['$id'] . '")' ], + 'queries' => ['cursorAfter("'.$base['body']['databases'][0]['$id'].'")'], ]); $this->assertCount(1, $databases['body']['databases']); @@ -132,7 +132,7 @@ class DatabasesCustomServerTest extends Scope 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'cursorAfter("' . $base['body']['databases'][1]['$id'] . '")' ], + 'queries' => ['cursorAfter("'.$base['body']['databases'][1]['$id'].'")'], ]); $this->assertCount(0, $databases['body']['databases']); @@ -150,7 +150,7 @@ class DatabasesCustomServerTest extends Scope 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'cursorBefore("' . $base['body']['databases'][1]['$id'] . '")' ], + 'queries' => ['cursorBefore("'.$base['body']['databases'][1]['$id'].'")'], ]); $this->assertCount(1, $databases['body']['databases']); @@ -160,7 +160,7 @@ class DatabasesCustomServerTest extends Scope 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'cursorBefore("' . $base['body']['databases'][0]['$id'] . '")' ], + 'queries' => ['cursorBefore("'.$base['body']['databases'][0]['$id'].'")'], ]); $this->assertCount(0, $databases['body']['databases']); @@ -173,7 +173,7 @@ class DatabasesCustomServerTest extends Scope 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'search' => 'first' + 'search' => 'first', ]); $this->assertEquals(1, $databases['body']['total']); @@ -183,7 +183,7 @@ class DatabasesCustomServerTest extends Scope 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'search' => 'Test' + 'search' => 'Test', ]); $this->assertEquals(2, $databases['body']['total']); @@ -194,7 +194,7 @@ class DatabasesCustomServerTest extends Scope 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'search' => 'Nonexistent' + 'search' => 'Nonexistent', ]); $this->assertEquals(0, $databases['body']['total']); @@ -206,7 +206,7 @@ class DatabasesCustomServerTest extends Scope 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'cursorAfter("unknown")' ], + 'queries' => ['cursorAfter("unknown")'], ]); $this->assertEquals(400, $response['headers']['status-code']); @@ -215,13 +215,14 @@ class DatabasesCustomServerTest extends Scope $response = $this->client->call(Client::METHOD_POST, '/databases', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'name' => 'Test 1', 'databaseId' => ID::custom('first'), ]); $this->assertEquals(409, $response['headers']['status-code']); + return ['databaseId' => $test1['body']['$id']]; } @@ -234,10 +235,10 @@ class DatabasesCustomServerTest extends Scope /** * Test for SUCCESS */ - $database = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId, [ + $database = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]); $this->assertEquals(200, $database['headers']['status-code']); @@ -254,19 +255,19 @@ class DatabasesCustomServerTest extends Scope { $databaseId = $data['databaseId']; - $response = $this->client->call(Client::METHOD_DELETE, '/databases/' . $databaseId, array_merge([ + $response = $this->client->call(Client::METHOD_DELETE, '/databases/'.$databaseId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ], $this->getHeaders())); $this->assertEquals(204, $response['headers']['status-code']); - $this->assertEquals("", $response['body']); + $this->assertEquals('', $response['body']); // Try to get the collection and check if it has been deleted - $response = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId, array_merge([ 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'] + 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); $this->assertEquals(404, $response['headers']['status-code']); @@ -277,7 +278,7 @@ class DatabasesCustomServerTest extends Scope $database = $this->client->call(Client::METHOD_POST, '/databases', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'databaseId' => ID::unique(), 'name' => 'invalidDocumentDatabase', @@ -289,10 +290,10 @@ class DatabasesCustomServerTest extends Scope /** * Test for SUCCESS */ - $test1 = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections', array_merge([ + $test1 = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'name' => 'Test 1', 'collectionId' => ID::custom('first'), @@ -305,10 +306,10 @@ class DatabasesCustomServerTest extends Scope 'documentSecurity' => true, ]); - $test2 = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections', array_merge([ + $test2 = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'name' => 'Test 2', 'collectionId' => ID::custom('second'), @@ -321,7 +322,7 @@ class DatabasesCustomServerTest extends Scope 'documentSecurity' => true, ]); - $collections = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections', array_merge([ + $collections = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -332,41 +333,41 @@ class DatabasesCustomServerTest extends Scope $base = array_reverse($collections['body']['collections']); - $collections = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections', array_merge([ + $collections = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'limit(1)' ] + 'queries' => ['limit(1)'], ]); $this->assertEquals(200, $collections['headers']['status-code']); $this->assertCount(1, $collections['body']['collections']); - $collections = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections', array_merge([ + $collections = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'offset(1)' ] + 'queries' => ['offset(1)'], ]); $this->assertEquals(200, $collections['headers']['status-code']); $this->assertCount(1, $collections['body']['collections']); - $collections = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections', array_merge([ + $collections = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'equal("enabled", true)' ] + 'queries' => ['equal("enabled", true)'], ]); $this->assertEquals(200, $collections['headers']['status-code']); $this->assertCount(2, $collections['body']['collections']); - $collections = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections', array_merge([ + $collections = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'equal("enabled", false)' ] + 'queries' => ['equal("enabled", false)'], ]); $this->assertEquals(200, $collections['headers']['status-code']); @@ -375,11 +376,11 @@ class DatabasesCustomServerTest extends Scope /** * Test for Order */ - $collections = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections', array_merge([ + $collections = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'orderDesc("")' ], + 'queries' => ['orderDesc("")'], ]); $this->assertEquals(2, $collections['body']['total']); @@ -389,26 +390,26 @@ class DatabasesCustomServerTest extends Scope /** * Test for After */ - $base = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections', array_merge([ + $base = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); - $collections = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections', array_merge([ + $collections = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'cursorAfter("' . $base['body']['collections'][0]['$id'] . '")' ], + 'queries' => ['cursorAfter("'.$base['body']['collections'][0]['$id'].'")'], ]); $this->assertCount(1, $collections['body']['collections']); $this->assertEquals($base['body']['collections'][1]['$id'], $collections['body']['collections'][0]['$id']); - $collections = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections', array_merge([ + $collections = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'cursorAfter("' . $base['body']['collections'][1]['$id'] . '")' ], + 'queries' => ['cursorAfter("'.$base['body']['collections'][1]['$id'].'")'], ]); $this->assertCount(0, $collections['body']['collections']); @@ -417,26 +418,26 @@ class DatabasesCustomServerTest extends Scope /** * Test for Before */ - $base = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections', array_merge([ + $base = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); - $collections = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections', array_merge([ + $collections = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'cursorBefore("' . $base['body']['collections'][1]['$id'] . '")' ], + 'queries' => ['cursorBefore("'.$base['body']['collections'][1]['$id'].'")'], ]); $this->assertCount(1, $collections['body']['collections']); $this->assertEquals($base['body']['collections'][0]['$id'], $collections['body']['collections'][0]['$id']); - $collections = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections', array_merge([ + $collections = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'cursorBefore("' . $base['body']['collections'][0]['$id'] . '")' ], + 'queries' => ['cursorBefore("'.$base['body']['collections'][0]['$id'].'")'], ]); $this->assertCount(0, $collections['body']['collections']); @@ -445,32 +446,32 @@ class DatabasesCustomServerTest extends Scope /** * Test for Search */ - $collections = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections', array_merge([ + $collections = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'search' => 'first' + 'search' => 'first', ]); $this->assertEquals(1, $collections['body']['total']); $this->assertEquals('first', $collections['body']['collections'][0]['$id']); - $collections = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections', array_merge([ + $collections = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'search' => 'Test' + 'search' => 'Test', ]); $this->assertEquals(2, $collections['body']['total']); $this->assertEquals('Test 1', $collections['body']['collections'][0]['name']); $this->assertEquals('Test 2', $collections['body']['collections'][1]['name']); - $collections = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections', array_merge([ + $collections = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'search' => 'Nonexistent' + 'search' => 'Nonexistent', ]); $this->assertEquals(0, $collections['body']['total']); @@ -478,20 +479,20 @@ class DatabasesCustomServerTest extends Scope /** * Test for FAILURE */ - $response = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'cursorAfter("unknown")' ], + 'queries' => ['cursorAfter("unknown")'], ]); $this->assertEquals(400, $response['headers']['status-code']); // This collection already exists - $response = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections', array_merge([ + $response = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'name' => 'Test 1', 'collectionId' => ID::custom('first'), @@ -512,7 +513,7 @@ class DatabasesCustomServerTest extends Scope $database = $this->client->call(Client::METHOD_POST, '/databases', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'databaseId' => ID::unique(), 'name' => 'invalidDocumentDatabase', @@ -526,10 +527,10 @@ class DatabasesCustomServerTest extends Scope */ // Create collection - $actors = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections', array_merge([ + $actors = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'collectionId' => ID::unique(), 'name' => 'Actors', @@ -545,30 +546,30 @@ class DatabasesCustomServerTest extends Scope $this->assertEquals(201, $actors['headers']['status-code']); $this->assertEquals($actors['body']['name'], 'Actors'); - $firstName = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $actors['body']['$id'] . '/attributes/string', array_merge([ + $firstName = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$actors['body']['$id'].'/attributes/string', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'firstName', 'size' => 256, 'required' => true, ]); - $lastName = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $actors['body']['$id'] . '/attributes/string', array_merge([ + $lastName = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$actors['body']['$id'].'/attributes/string', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'lastName', 'size' => 256, 'required' => true, ]); - $unneeded = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $actors['body']['$id'] . '/attributes/string', array_merge([ + $unneeded = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$actors['body']['$id'].'/attributes/string', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'unneeded', 'size' => 256, @@ -579,16 +580,16 @@ class DatabasesCustomServerTest extends Scope sleep(2); // Creating document to ensure cache is purged on schema change - $document = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $actors['body']['$id'] . '/documents', array_merge([ + $document = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$actors['body']['$id'].'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'documentId' => ID::unique(), 'data' => [ 'firstName' => 'lorem', 'lastName' => 'ipsum', - 'unneeded' => 'dolor' + 'unneeded' => 'dolor', ], 'permissions' => [ Permission::read(Role::any()), @@ -597,10 +598,10 @@ class DatabasesCustomServerTest extends Scope ], ]); - $index = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $actors['body']['$id'] . '/indexes', array_merge([ + $index = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$actors['body']['$id'].'/indexes', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'key_lastName', 'type' => 'key', @@ -612,10 +613,10 @@ class DatabasesCustomServerTest extends Scope // Wait for database worker to finish creating index sleep(2); - $collection = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $actors['body']['$id'], array_merge([ + $collection = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$actors['body']['$id'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), []); $unneededId = $unneeded['body']['key']; @@ -630,10 +631,10 @@ class DatabasesCustomServerTest extends Scope $this->assertEquals($collection['body']['indexes'][0]['key'], $index['body']['key']); // Delete attribute - $attribute = $this->client->call(Client::METHOD_DELETE, '/databases/' . $databaseId . '/collections/' . $actors ['body']['$id'] . '/attributes/' . $unneededId, array_merge([ + $attribute = $this->client->call(Client::METHOD_DELETE, '/databases/'.$databaseId.'/collections/'.$actors['body']['$id'].'/attributes/'.$unneededId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ])); $this->assertEquals(204, $attribute['headers']['status-code']); @@ -641,18 +642,18 @@ class DatabasesCustomServerTest extends Scope sleep(2); // Check document to ensure cache is purged on schema change - $document = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $actors['body']['$id'] . '/documents/' . $document['body']['$id'], array_merge([ + $document = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$actors['body']['$id'].'/documents/'.$document['body']['$id'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ])); $this->assertNotContains($unneededId, $document['body']); - $collection = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $actors['body']['$id'], array_merge([ + $collection = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$actors['body']['$id'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), []); $this->assertEquals(200, $collection['headers']['status-code']); @@ -664,7 +665,7 @@ class DatabasesCustomServerTest extends Scope return [ 'collectionId' => $actors['body']['$id'], 'key' => $index['body']['key'], - 'databaseId' => $databaseId + 'databaseId' => $databaseId, ]; } @@ -674,10 +675,10 @@ class DatabasesCustomServerTest extends Scope public function testDeleteIndex($data): array { $databaseId = $data['databaseId']; - $index = $this->client->call(Client::METHOD_DELETE, '/databases/' . $databaseId . '/collections/' . $data['collectionId'] . '/indexes/' . $data['key'], array_merge([ + $index = $this->client->call(Client::METHOD_DELETE, '/databases/'.$databaseId.'/collections/'.$data['collectionId'].'/indexes/'.$data['key'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ])); $this->assertEquals(204, $index['headers']['status-code']); @@ -685,10 +686,10 @@ class DatabasesCustomServerTest extends Scope // Wait for database worker to finish deleting index sleep(2); - $collection = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['collectionId'], array_merge([ + $collection = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['collectionId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), []); $this->assertCount(0, $collection['body']['indexes']); @@ -702,20 +703,20 @@ class DatabasesCustomServerTest extends Scope public function testDeleteIndexOnDeleteAttribute($data) { $databaseId = $data['databaseId']; - $attribute1 = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $data['collectionId'] . '/attributes/string', array_merge([ + $attribute1 = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$data['collectionId'].'/attributes/string', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'attribute1', 'size' => 16, 'required' => true, ]); - $attribute2 = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $data['collectionId'] . '/attributes/string', array_merge([ + $attribute2 = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$data['collectionId'].'/attributes/string', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'attribute2', 'size' => 16, @@ -729,10 +730,10 @@ class DatabasesCustomServerTest extends Scope sleep(2); - $index1 = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $data['collectionId'] . '/indexes', array_merge([ + $index1 = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$data['collectionId'].'/indexes', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'index1', 'type' => 'key', @@ -740,10 +741,10 @@ class DatabasesCustomServerTest extends Scope 'orders' => ['ASC', 'ASC'], ]); - $index2 = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $data['collectionId'] . '/indexes', array_merge([ + $index2 = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$data['collectionId'].'/indexes', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'index2', 'type' => 'key', @@ -758,10 +759,10 @@ class DatabasesCustomServerTest extends Scope sleep(2); // Expected behavior: deleting attribute2 will cause index2 to be dropped, and index1 rebuilt with a single key - $deleted = $this->client->call(Client::METHOD_DELETE, '/databases/' . $databaseId . '/collections/' . $data['collectionId'] . '/attributes/' . $attribute2['body']['key'], array_merge([ + $deleted = $this->client->call(Client::METHOD_DELETE, '/databases/'.$databaseId.'/collections/'.$data['collectionId'].'/attributes/'.$attribute2['body']['key'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ])); $this->assertEquals(204, $deleted['headers']['status-code']); @@ -769,10 +770,10 @@ class DatabasesCustomServerTest extends Scope // wait for database worker to complete sleep(2); - $collection = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $data['collectionId'], array_merge([ + $collection = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$data['collectionId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ])); $this->assertEquals(200, $collection['headers']['status-code']); @@ -784,10 +785,10 @@ class DatabasesCustomServerTest extends Scope $this->assertEquals($attribute1['body']['key'], $collection['body']['indexes'][0]['attributes'][0]); // Delete attribute - $deleted = $this->client->call(Client::METHOD_DELETE, '/databases/' . $databaseId . '/collections/' . $data['collectionId'] . '/attributes/' . $attribute1['body']['key'], array_merge([ + $deleted = $this->client->call(Client::METHOD_DELETE, '/databases/'.$databaseId.'/collections/'.$data['collectionId'].'/attributes/'.$attribute1['body']['key'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ])); $this->assertEquals(204, $deleted['headers']['status-code']); @@ -800,7 +801,7 @@ class DatabasesCustomServerTest extends Scope $database = $this->client->call(Client::METHOD_POST, '/databases', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'databaseId' => ID::unique(), 'name' => 'invalidDocumentDatabase', @@ -809,10 +810,10 @@ class DatabasesCustomServerTest extends Scope $this->assertEquals('invalidDocumentDatabase', $database['body']['name']); $databaseId = $database['body']['$id']; - $collection = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections', array_merge([ + $collection = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'collectionId' => ID::unique(), 'name' => 'TestCleanupDuplicateIndexOnDeleteAttribute', @@ -830,20 +831,20 @@ class DatabasesCustomServerTest extends Scope $collectionId = $collection['body']['$id']; - $attribute1 = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/attributes/string', array_merge([ + $attribute1 = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/attributes/string', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'attribute1', 'size' => 16, 'required' => true, ]); - $attribute2 = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/attributes/string', array_merge([ + $attribute2 = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/attributes/string', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'attribute2', 'size' => 16, @@ -857,10 +858,10 @@ class DatabasesCustomServerTest extends Scope sleep(2); - $index1 = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/indexes', array_merge([ + $index1 = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/indexes', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'index1', 'type' => 'key', @@ -868,10 +869,10 @@ class DatabasesCustomServerTest extends Scope 'orders' => ['ASC', 'ASC'], ]); - $index2 = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/indexes', array_merge([ + $index2 = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/indexes', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'index2', 'type' => 'key', @@ -886,10 +887,10 @@ class DatabasesCustomServerTest extends Scope sleep(2); // Expected behavior: deleting attribute1 would cause index1 to be a duplicate of index2 and automatically removed - $deleted = $this->client->call(Client::METHOD_DELETE, '/databases/' . $databaseId . '/collections/' . $collectionId . '/attributes/' . $attribute1['body']['key'], array_merge([ + $deleted = $this->client->call(Client::METHOD_DELETE, '/databases/'.$databaseId.'/collections/'.$collectionId.'/attributes/'.$attribute1['body']['key'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ])); $this->assertEquals(204, $deleted['headers']['status-code']); @@ -897,10 +898,10 @@ class DatabasesCustomServerTest extends Scope // wait for database worker to complete sleep(2); - $collection = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $collectionId, array_merge([ + $collection = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$collectionId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ])); $this->assertEquals(200, $collection['headers']['status-code']); @@ -912,10 +913,10 @@ class DatabasesCustomServerTest extends Scope $this->assertEquals($attribute2['body']['key'], $collection['body']['indexes'][0]['attributes'][0]); // Delete attribute - $deleted = $this->client->call(Client::METHOD_DELETE, '/databases/' . $databaseId . '/collections/' . $collectionId . '/attributes/' . $attribute2['body']['key'], array_merge([ + $deleted = $this->client->call(Client::METHOD_DELETE, '/databases/'.$databaseId.'/collections/'.$collectionId.'/attributes/'.$attribute2['body']['key'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ])); $this->assertEquals(204, $deleted['headers']['status-code']); @@ -930,7 +931,7 @@ class DatabasesCustomServerTest extends Scope $collectionId = $data['collectionId']; // Add Documents to the collection - $document1 = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents', array_merge([ + $document1 = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -946,7 +947,7 @@ class DatabasesCustomServerTest extends Scope ], ]); - $document2 = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/documents', array_merge([ + $document2 = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -975,19 +976,19 @@ class DatabasesCustomServerTest extends Scope $this->assertEquals($document2['body']['lastName'], 'Jackson'); // Delete the actors collection - $response = $this->client->call(Client::METHOD_DELETE, '/databases/' . $databaseId . '/collections/' . $collectionId, array_merge([ + $response = $this->client->call(Client::METHOD_DELETE, '/databases/'.$databaseId.'/collections/'.$collectionId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ], $this->getHeaders())); $this->assertEquals(204, $response['headers']['status-code']); - $this->assertEquals($response['body'], ""); + $this->assertEquals($response['body'], ''); // Try to get the collection and check if it has been deleted - $response = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $collectionId, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$collectionId, array_merge([ 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'] + 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); $this->assertEquals(404, $response['headers']['status-code']); @@ -1052,7 +1053,7 @@ class DatabasesCustomServerTest extends Scope $database = $this->client->call(Client::METHOD_POST, '/databases', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'databaseId' => ID::unique(), 'name' => 'invalidDocumentDatabase', @@ -1061,10 +1062,10 @@ class DatabasesCustomServerTest extends Scope $this->assertEquals('invalidDocumentDatabase', $database['body']['name']); $databaseId = $database['body']['$id']; - $collection = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections', array_merge([ + $collection = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'collectionId' => ID::custom('attributeRowWidthLimit'), 'name' => 'attributeRowWidthLimit', @@ -1084,10 +1085,10 @@ class DatabasesCustomServerTest extends Scope // Add wide string attributes to approach row width limit for ($i = 0; $i < 15; $i++) { - $attribute = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/attributes/string', array_merge([ + $attribute = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/attributes/string', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => "attribute{$i}", 'size' => 1024, @@ -1099,10 +1100,10 @@ class DatabasesCustomServerTest extends Scope sleep(5); - $tooWide = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/attributes/string', array_merge([ + $tooWide = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/attributes/string', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'tooWide', 'size' => 1024, @@ -1118,7 +1119,7 @@ class DatabasesCustomServerTest extends Scope $database = $this->client->call(Client::METHOD_POST, '/databases', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'databaseId' => ID::unique(), 'name' => 'invalidDocumentDatabase', @@ -1127,10 +1128,10 @@ class DatabasesCustomServerTest extends Scope $this->assertEquals('invalidDocumentDatabase', $database['body']['name']); $databaseId = $database['body']['$id']; - $collection = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections', array_merge([ + $collection = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'collectionId' => ID::custom('testLimitException'), 'name' => 'testLimitException', @@ -1151,10 +1152,10 @@ class DatabasesCustomServerTest extends Scope // 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)); - $attribute = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/attributes/string', array_merge([ + $attribute = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/attributes/string', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => "attribute{$i}", 'size' => 64, @@ -1166,10 +1167,10 @@ class DatabasesCustomServerTest extends Scope sleep(20); - $collection = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $collectionId, array_merge([ + $collection = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$collectionId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ])); $this->assertEquals(200, $collection['headers']['status-code']); @@ -1180,7 +1181,7 @@ class DatabasesCustomServerTest extends Scope $this->assertCount(0, $collection['body']['indexes']); foreach ($collection['body']['attributes'] as $attribute) { - $this->assertEquals('available', $attribute['status'], 'attribute: ' . $attribute['key']); + $this->assertEquals('available', $attribute['status'], 'attribute: '.$attribute['key']); } // Test indexLimit = 64 @@ -1188,10 +1189,10 @@ class DatabasesCustomServerTest extends Scope // Add up to the limit, then check if the next index throws IndexLimitException for ($i = 0; $i < 59; $i++) { // $this->assertEquals(true, static::getDatabase()->createIndex('indexLimit', "index{$i}", Database::INDEX_KEY, ["test{$i}"], [16])); - $index = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/indexes', array_merge([ + $index = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/indexes', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => "key_attribute{$i}", 'type' => 'key', @@ -1204,10 +1205,10 @@ class DatabasesCustomServerTest extends Scope sleep(5); - $collection = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $collectionId, array_merge([ + $collection = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$collectionId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ])); $this->assertEquals(200, $collection['headers']['status-code']); @@ -1217,10 +1218,10 @@ class DatabasesCustomServerTest extends Scope $this->assertCount(64, $collection['body']['attributes']); $this->assertCount(59, $collection['body']['indexes']); - $tooMany = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collectionId . '/indexes', array_merge([ + $tooMany = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collectionId.'/indexes', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'tooMany', 'type' => 'key', @@ -1230,10 +1231,10 @@ class DatabasesCustomServerTest extends Scope $this->assertEquals(400, $tooMany['headers']['status-code']); $this->assertEquals('Index limit exceeded', $tooMany['body']['message']); - $collection = $this->client->call(Client::METHOD_DELETE, '/databases/' . $databaseId . '/collections/' . $collectionId, array_merge([ + $collection = $this->client->call(Client::METHOD_DELETE, '/databases/'.$databaseId.'/collections/'.$collectionId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ])); $this->assertEquals(204, $collection['headers']['status-code']); diff --git a/tests/e2e/Services/Databases/DatabasesPermissionsGuestTest.php b/tests/e2e/Services/Databases/DatabasesPermissionsGuestTest.php index b1d197f010..7f28097e70 100644 --- a/tests/e2e/Services/Databases/DatabasesPermissionsGuestTest.php +++ b/tests/e2e/Services/Databases/DatabasesPermissionsGuestTest.php @@ -3,8 +3,8 @@ namespace Tests\E2E\Services\Databases; use Tests\E2E\Client; -use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\ProjectCustom; +use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\SideClient; use Utopia\Database\Helpers\ID; use Utopia\Database\Helpers\Permission; @@ -22,7 +22,7 @@ class DatabasesPermissionsGuestTest extends Scope $database = $this->client->call(Client::METHOD_POST, '/databases', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'databaseId' => ID::unique(), 'name' => 'InvalidDocumentDatabase', @@ -31,7 +31,7 @@ class DatabasesPermissionsGuestTest extends Scope $this->assertEquals('InvalidDocumentDatabase', $database['body']['name']); $databaseId = $database['body']['$id']; - $publicMovies = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections', $this->getServerHeader(), [ + $publicMovies = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections', $this->getServerHeader(), [ 'collectionId' => ID::unique(), 'name' => 'Movies', 'permissions' => [ @@ -41,7 +41,7 @@ class DatabasesPermissionsGuestTest extends Scope Permission::delete(Role::any()), ], ]); - $privateMovies = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections', $this->getServerHeader(), [ + $privateMovies = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections', $this->getServerHeader(), [ 'collectionId' => ID::unique(), 'name' => 'Movies', 'permissions' => [], @@ -51,12 +51,12 @@ class DatabasesPermissionsGuestTest extends Scope $publicCollection = ['id' => $publicMovies['body']['$id']]; $privateCollection = ['id' => $privateMovies['body']['$id']]; - $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $publicCollection['id'] . '/attributes/string', $this->getServerHeader(), [ + $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$publicCollection['id'].'/attributes/string', $this->getServerHeader(), [ 'key' => 'title', 'size' => 256, 'required' => true, ]); - $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $privateCollection['id'] . '/attributes/string', $this->getServerHeader(), [ + $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$privateCollection['id'].'/attributes/string', $this->getServerHeader(), [ 'key' => 'title', 'size' => 256, 'required' => true, @@ -93,14 +93,14 @@ class DatabasesPermissionsGuestTest extends Scope $privateCollectionId = $data['privateCollectionId']; $databaseId = $data['databaseId']; - $publicResponse = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $publicCollectionId . '/documents', $this->getServerHeader(), [ + $publicResponse = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$publicCollectionId.'/documents', $this->getServerHeader(), [ 'documentId' => ID::unique(), 'data' => [ 'title' => 'Lorem', ], 'permissions' => $permissions, ]); - $privateResponse = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $privateCollectionId . '/documents', $this->getServerHeader(), [ + $privateResponse = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$privateCollectionId.'/documents', $this->getServerHeader(), [ 'documentId' => ID::unique(), 'data' => [ 'title' => 'Lorem', @@ -114,11 +114,11 @@ class DatabasesPermissionsGuestTest extends Scope $roles = Authorization::getRoles(); Authorization::cleanRoles(); - $publicDocuments = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $publicCollectionId . '/documents', [ + $publicDocuments = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$publicCollectionId.'/documents', [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ]); - $privateDocuments = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $privateCollectionId . '/documents', [ + $privateDocuments = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$privateCollectionId.'/documents', [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ]); @@ -148,20 +148,20 @@ class DatabasesPermissionsGuestTest extends Scope $roles = Authorization::getRoles(); Authorization::cleanRoles(); - $publicResponse = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $publicCollectionId . '/documents', [ + $publicResponse = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$publicCollectionId.'/documents', [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], [ 'documentId' => ID::unique(), 'data' => [ 'title' => 'Lorem', - ] + ], ]); $publicDocumentId = $publicResponse['body']['$id']; $this->assertEquals(201, $publicResponse['headers']['status-code']); - $privateResponse = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $privateCollectionId . '/documents', [ + $privateResponse = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$privateCollectionId.'/documents', [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], [ @@ -174,7 +174,7 @@ class DatabasesPermissionsGuestTest extends Scope $this->assertEquals(401, $privateResponse['headers']['status-code']); // Create a document in private collection with API key so we can test that update and delete are also not allowed - $privateResponse = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $privateCollectionId . '/documents', $this->getServerHeader(), [ + $privateResponse = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$privateCollectionId.'/documents', $this->getServerHeader(), [ 'documentId' => ID::unique(), 'data' => [ 'title' => 'Lorem', @@ -184,7 +184,7 @@ class DatabasesPermissionsGuestTest extends Scope $this->assertEquals(201, $privateResponse['headers']['status-code']); $privateDocumentId = $privateResponse['body']['$id']; - $publicDocument = $this->client->call(Client::METHOD_PATCH, '/databases/' . $databaseId . '/collections/' . $publicCollectionId . '/documents/' . $publicDocumentId, [ + $publicDocument = $this->client->call(Client::METHOD_PATCH, '/databases/'.$databaseId.'/collections/'.$publicCollectionId.'/documents/'.$publicDocumentId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], [ @@ -196,7 +196,7 @@ class DatabasesPermissionsGuestTest extends Scope $this->assertEquals(200, $publicDocument['headers']['status-code']); $this->assertEquals('Thor: Ragnarok', $publicDocument['body']['title']); - $privateDocument = $this->client->call(Client::METHOD_PATCH, '/databases/' . $databaseId . '/collections/' . $privateCollectionId . '/documents/' . $privateDocumentId, [ + $privateDocument = $this->client->call(Client::METHOD_PATCH, '/databases/'.$databaseId.'/collections/'.$privateCollectionId.'/documents/'.$privateDocumentId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], [ @@ -207,14 +207,14 @@ class DatabasesPermissionsGuestTest extends Scope $this->assertEquals(401, $privateDocument['headers']['status-code']); - $publicDocument = $this->client->call(Client::METHOD_DELETE, '/databases/' . $databaseId . '/collections/' . $publicCollectionId . '/documents/' . $publicDocumentId, [ + $publicDocument = $this->client->call(Client::METHOD_DELETE, '/databases/'.$databaseId.'/collections/'.$publicCollectionId.'/documents/'.$publicDocumentId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ]); $this->assertEquals(204, $publicDocument['headers']['status-code']); - $privateDocument = $this->client->call(Client::METHOD_DELETE, '/databases/' . $databaseId . '/collections/' . $privateCollectionId . '/documents/' . $privateDocumentId, [ + $privateDocument = $this->client->call(Client::METHOD_DELETE, '/databases/'.$databaseId.'/collections/'.$privateCollectionId.'/documents/'.$privateDocumentId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ]); @@ -231,7 +231,7 @@ class DatabasesPermissionsGuestTest extends Scope $database = $this->client->call(Client::METHOD_POST, '/databases', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'databaseId' => ID::unique(), 'name' => 'GuestPermissionsWrite', @@ -240,18 +240,18 @@ class DatabasesPermissionsGuestTest extends Scope $this->assertEquals('GuestPermissionsWrite', $database['body']['name']); $databaseId = $database['body']['$id']; - $movies = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections', $this->getServerHeader(), [ + $movies = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections', $this->getServerHeader(), [ 'collectionId' => ID::unique(), 'name' => 'Movies', 'permissions' => [ Permission::create(Role::any()), ], - 'documentSecurity' => true + 'documentSecurity' => true, ]); $moviesId = $movies['body']['$id']; - $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $moviesId . '/attributes/string', $this->getServerHeader(), [ + $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$moviesId.'/attributes/string', $this->getServerHeader(), [ 'key' => 'title', 'size' => 256, 'required' => true, @@ -259,7 +259,7 @@ class DatabasesPermissionsGuestTest extends Scope sleep(1); - $document = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $moviesId . '/documents', [ + $document = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$moviesId.'/documents', [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], [ @@ -269,7 +269,7 @@ class DatabasesPermissionsGuestTest extends Scope ], 'permissions' => [ Permission::read(Role::any()), - ] + ], ]); $this->assertEquals(201, $document['headers']['status-code']); diff --git a/tests/e2e/Services/Databases/DatabasesPermissionsMemberTest.php b/tests/e2e/Services/Databases/DatabasesPermissionsMemberTest.php index 860fb7fb12..73393b7efa 100644 --- a/tests/e2e/Services/Databases/DatabasesPermissionsMemberTest.php +++ b/tests/e2e/Services/Databases/DatabasesPermissionsMemberTest.php @@ -110,6 +110,7 @@ class DatabasesPermissionsMemberTest extends Scope * Data providers lose object state so explicitly pass [$users, $collections] to each iteration * * @return array + * * @throws \Exception */ public function testSetupDatabase(): array @@ -124,7 +125,7 @@ class DatabasesPermissionsMemberTest extends Scope $databaseId = $db['body']['$id']; - $public = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections', $this->getServerHeader(), [ + $public = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections', $this->getServerHeader(), [ 'collectionId' => ID::unique(), 'name' => 'Movies', 'permissions' => [ @@ -138,14 +139,14 @@ class DatabasesPermissionsMemberTest extends Scope $this->assertEquals(201, $public['headers']['status-code']); $this->collections = ['public' => $public['body']['$id']]; - $response = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $this->collections['public'] . '/attributes/string', $this->getServerHeader(), [ + $response = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$this->collections['public'].'/attributes/string', $this->getServerHeader(), [ 'key' => 'title', 'size' => 256, 'required' => true, ]); $this->assertEquals(202, $response['headers']['status-code']); - $private = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections', $this->getServerHeader(), [ + $private = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections', $this->getServerHeader(), [ 'collectionId' => ID::unique(), 'name' => 'Private Movies', 'permissions' => [ @@ -159,14 +160,14 @@ class DatabasesPermissionsMemberTest extends Scope $this->assertEquals(201, $private['headers']['status-code']); $this->collections['private'] = $private['body']['$id']; - $response = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $this->collections['private'] . '/attributes/string', $this->getServerHeader(), [ + $response = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$this->collections['private'].'/attributes/string', $this->getServerHeader(), [ 'key' => 'title', 'size' => 256, 'required' => true, ]); $this->assertEquals(202, $response['headers']['status-code']); - $doconly = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections', $this->getServerHeader(), [ + $doconly = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections', $this->getServerHeader(), [ 'collectionId' => ID::unique(), 'name' => 'Document Only Movies', 'permissions' => [], @@ -175,7 +176,7 @@ class DatabasesPermissionsMemberTest extends Scope $this->assertEquals(201, $private['headers']['status-code']); $this->collections['doconly'] = $doconly['body']['$id']; - $response = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $this->collections['doconly'] . '/attributes/string', $this->getServerHeader(), [ + $response = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$this->collections['doconly'].'/attributes/string', $this->getServerHeader(), [ 'key' => 'title', 'size' => 256, 'required' => true, @@ -187,12 +188,13 @@ class DatabasesPermissionsMemberTest extends Scope return [ 'users' => $this->users, 'collections' => $this->collections, - 'databaseId' => $databaseId + 'databaseId' => $databaseId, ]; } /** * Data provider params are passed before test dependencies + * * @dataProvider permissionsProvider * @depends testSetupDatabase */ @@ -202,41 +204,41 @@ class DatabasesPermissionsMemberTest extends Scope $collections = $data['collections']; $databaseId = $data['databaseId']; - $response = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collections['public'] . '/documents', $this->getServerHeader(), [ + $response = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collections['public'].'/documents', $this->getServerHeader(), [ 'documentId' => ID::unique(), 'data' => [ 'title' => 'Lorem', ], - 'permissions' => $permissions + 'permissions' => $permissions, ]); $this->assertEquals(201, $response['headers']['status-code']); - $response = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collections['private'] . '/documents', $this->getServerHeader(), [ + $response = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collections['private'].'/documents', $this->getServerHeader(), [ 'documentId' => ID::unique(), 'data' => [ 'title' => 'Lorem', ], - 'permissions' => $permissions + 'permissions' => $permissions, ]); $this->assertEquals(201, $response['headers']['status-code']); - $response = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $collections['doconly'] . '/documents', $this->getServerHeader(), [ + $response = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$collections['doconly'].'/documents', $this->getServerHeader(), [ 'documentId' => ID::unique(), 'data' => [ 'title' => 'Lorem', ], - 'permissions' => $permissions + 'permissions' => $permissions, ]); $this->assertEquals(201, $response['headers']['status-code']); /** * Check "any" permission collection */ - $documents = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $collections['public'] . '/documents', [ + $documents = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$collections['public'].'/documents', [ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $users['user1']['session'], + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$users['user1']['session'], ]); $this->assertEquals(200, $documents['headers']['status-code']); @@ -245,11 +247,11 @@ class DatabasesPermissionsMemberTest extends Scope /** * Check "users" permission collection */ - $documents = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $collections['private'] . '/documents', [ + $documents = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$collections['private'].'/documents', [ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $users['user1']['session'], + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$users['user1']['session'], ]); $this->assertEquals(200, $documents['headers']['status-code']); @@ -258,11 +260,11 @@ class DatabasesPermissionsMemberTest extends Scope /** * Check "user:user1" document only permission collection */ - $documents = $this->client->call(Client::METHOD_GET, '/databases/' . $databaseId . '/collections/' . $collections['doconly'] . '/documents', [ + $documents = $this->client->call(Client::METHOD_GET, '/databases/'.$databaseId.'/collections/'.$collections['doconly'].'/documents', [ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $users['user1']['session'], + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$users['user1']['session'], ]); $this->assertEquals(200, $documents['headers']['status-code']); diff --git a/tests/e2e/Services/Databases/DatabasesPermissionsScope.php b/tests/e2e/Services/Databases/DatabasesPermissionsScope.php index 181231adc5..a78153cf7d 100644 --- a/tests/e2e/Services/Databases/DatabasesPermissionsScope.php +++ b/tests/e2e/Services/Databases/DatabasesPermissionsScope.php @@ -7,6 +7,7 @@ use Tests\E2E\Client; trait DatabasesPermissionsScope { public array $users = []; + public array $teams = []; public function createUser(string $id, string $email, string $password = 'test123!'): array @@ -18,7 +19,7 @@ trait DatabasesPermissionsScope ], [ 'userId' => $id, 'email' => $email, - 'password' => $password + 'password' => $password, ]); $this->assertEquals(201, $user['headers']['status-code']); @@ -32,7 +33,7 @@ trait DatabasesPermissionsScope 'password' => $password, ]); - $session = $this->client->parseCookie((string)$session['headers']['set-cookie'])['a_session_' . $this->getProject()['$id']]; + $session = $this->client->parseCookie((string) $session['headers']['set-cookie'])['a_session_'.$this->getProject()['$id']]; $user = [ '$id' => $user['body']['$id'], @@ -53,7 +54,7 @@ trait DatabasesPermissionsScope { $team = $this->client->call(Client::METHOD_POST, '/teams', $this->getServerHeader(), [ 'teamId' => $id, - 'name' => $name + 'name' => $name, ]); $this->teams[$id] = $team['body']; @@ -62,16 +63,16 @@ trait DatabasesPermissionsScope public function addToTeam(string $user, string $team, array $roles = []): array { - $membership = $this->client->call(Client::METHOD_POST, '/teams/' . $team . '/memberships', $this->getServerHeader(), [ + $membership = $this->client->call(Client::METHOD_POST, '/teams/'.$team.'/memberships', $this->getServerHeader(), [ 'teamId' => $team, 'email' => $this->getCreatedUser($user)['email'], 'roles' => $roles, - 'url' => 'http://localhost:5000/join-us#title' + 'url' => 'http://localhost:5000/join-us#title', ]); return [ 'user' => $membership['body']['userId'], - 'membership' => $membership['body']['$id'] + 'membership' => $membership['body']['$id'], ]; } @@ -80,7 +81,7 @@ trait DatabasesPermissionsScope return [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]; } } diff --git a/tests/e2e/Services/Databases/DatabasesPermissionsTeamTest.php b/tests/e2e/Services/Databases/DatabasesPermissionsTeamTest.php index 8377b9c803..5505fe68d9 100644 --- a/tests/e2e/Services/Databases/DatabasesPermissionsTeamTest.php +++ b/tests/e2e/Services/Databases/DatabasesPermissionsTeamTest.php @@ -3,8 +3,8 @@ namespace Tests\E2E\Services\Databases; use Tests\E2E\Client; -use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\ProjectCustom; +use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\SideClient; use Utopia\Database\Helpers\ID; use Utopia\Database\Helpers\Permission; @@ -17,6 +17,7 @@ class DatabasesPermissionsTeamTest extends Scope use DatabasesPermissionsScope; public array $collections = []; + public string $databaseId = 'testpermissiondb'; public function createTeams(): array @@ -44,7 +45,7 @@ class DatabasesPermissionsTeamTest extends Scope ]); $this->assertEquals(201, $db['headers']['status-code']); - $collection1 = $this->client->call(Client::METHOD_POST, '/databases/' . $this->databaseId . '/collections', $this->getServerHeader(), [ + $collection1 = $this->client->call(Client::METHOD_POST, '/databases/'.$this->databaseId.'/collections', $this->getServerHeader(), [ 'collectionId' => ID::custom('collection1'), 'name' => 'Collection 1', 'permissions' => [ @@ -57,13 +58,13 @@ class DatabasesPermissionsTeamTest extends Scope $this->collections['collection1'] = $collection1['body']['$id']; - $this->client->call(Client::METHOD_POST, '/databases/' . $this->databaseId . '/collections/' . $this->collections['collection1'] . '/attributes/string', $this->getServerHeader(), [ + $this->client->call(Client::METHOD_POST, '/databases/'.$this->databaseId.'/collections/'.$this->collections['collection1'].'/attributes/string', $this->getServerHeader(), [ 'key' => 'title', 'size' => 256, 'required' => true, ]); - $collection2 = $this->client->call(Client::METHOD_POST, '/databases/' . $this->databaseId . '/collections', $this->getServerHeader(), [ + $collection2 = $this->client->call(Client::METHOD_POST, '/databases/'.$this->databaseId.'/collections', $this->getServerHeader(), [ 'collectionId' => ID::custom('collection2'), 'name' => 'Collection 2', 'permissions' => [ @@ -71,12 +72,12 @@ class DatabasesPermissionsTeamTest extends Scope Permission::create(Role::team($teams['team2']['$id'], 'owner')), Permission::update(Role::team($teams['team2']['$id'], 'owner')), Permission::delete(Role::team($teams['team2']['$id'], 'owner')), - ] + ], ]); $this->collections['collection2'] = $collection2['body']['$id']; - $this->client->call(Client::METHOD_POST, '/databases/' . $this->databaseId . '/collections/' . $this->collections['collection2'] . '/attributes/string', $this->getServerHeader(), [ + $this->client->call(Client::METHOD_POST, '/databases/'.$this->databaseId.'/collections/'.$this->collections['collection2'].'/attributes/string', $this->getServerHeader(), [ 'key' => 'title', 'size' => 256, 'required' => true, @@ -124,6 +125,7 @@ class DatabasesPermissionsTeamTest extends Scope * * Data providers lose object state * so explicitly pass $users to each iteration + * * @return array $users */ public function testSetupDatabase(): array @@ -140,7 +142,7 @@ class DatabasesPermissionsTeamTest extends Scope $this->createCollections($this->teams); - $response = $this->client->call(Client::METHOD_POST, '/databases/' . $this->databaseId . '/collections/' . $this->collections['collection1'] . '/documents', $this->getServerHeader(), [ + $response = $this->client->call(Client::METHOD_POST, '/databases/'.$this->databaseId.'/collections/'.$this->collections['collection1'].'/documents', $this->getServerHeader(), [ 'documentId' => ID::unique(), 'data' => [ 'title' => 'Lorem', @@ -148,7 +150,7 @@ class DatabasesPermissionsTeamTest extends Scope ]); $this->assertEquals(201, $response['headers']['status-code']); - $response = $this->client->call(Client::METHOD_POST, '/databases/' . $this->databaseId . '/collections/' . $this->collections['collection2'] . '/documents', $this->getServerHeader(), [ + $response = $this->client->call(Client::METHOD_POST, '/databases/'.$this->databaseId.'/collections/'.$this->collections['collection2'].'/documents', $this->getServerHeader(), [ 'documentId' => ID::unique(), 'data' => [ 'title' => 'Ipsum', @@ -161,16 +163,17 @@ class DatabasesPermissionsTeamTest extends Scope /** * Data provider params are passed before test dependencies + * * @depends testSetupDatabase * @dataProvider readDocumentsProvider */ public function testReadDocuments($user, $collection, $success, $users) { - $documents = $this->client->call(Client::METHOD_GET, '/databases/' . $this->databaseId . '/collections/' . $collection . '/documents', [ + $documents = $this->client->call(Client::METHOD_GET, '/databases/'.$this->databaseId.'/collections/'.$collection.'/documents', [ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $users[$user]['session'], + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$users[$user]['session'], ]); if ($success) { @@ -186,11 +189,11 @@ class DatabasesPermissionsTeamTest extends Scope */ public function testWriteDocuments($user, $collection, $success, $users) { - $documents = $this->client->call(Client::METHOD_POST, '/databases/' . $this->databaseId . '/collections/' . $collection . '/documents', [ + $documents = $this->client->call(Client::METHOD_POST, '/databases/'.$this->databaseId.'/collections/'.$collection.'/documents', [ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $users[$user]['session'], + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$users[$user]['session'], ], [ 'documentId' => ID::unique(), 'data' => [ diff --git a/tests/e2e/Services/Domains/DomainsBase.php b/tests/e2e/Services/Domains/DomainsBase.php index 79a1cd9d0f..a7f1f6e031 100644 --- a/tests/e2e/Services/Domains/DomainsBase.php +++ b/tests/e2e/Services/Domains/DomainsBase.php @@ -2,8 +2,6 @@ namespace Tests\E2E\Services\Domains; -use Tests\E2E\Client; - trait DomainsBase { } diff --git a/tests/e2e/Services/Domains/DomainsRegistrarClientTest.php b/tests/e2e/Services/Domains/DomainsRegistrarClientTest.php index 797d9cd840..40afde4cd8 100644 --- a/tests/e2e/Services/Domains/DomainsRegistrarClientTest.php +++ b/tests/e2e/Services/Domains/DomainsRegistrarClientTest.php @@ -2,306 +2,298 @@ namespace Tests\E2E\Services\Projects; -use Appwrite\Auth\Auth; -use Tests\E2E\Scopes\Scope; +use Tests\E2E\Client; use Tests\E2E\Scopes\ProjectConsole; +use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\SideClient; use Tests\E2E\Services\Domains\DomainsBase; -use Tests\E2E\Client; -use Utopia\Database\Database; -use Utopia\Database\DateTime; use Utopia\Database\Helpers\ID; -use function PHPUnit\Framework\isEmpty; - class DomainsRegistrarClientTest extends Scope { - use DomainsBase; - use ProjectConsole; - use SideClient; + use DomainsBase; + use ProjectConsole; + use SideClient; - - public function testCreateProject(): array - { - /** - * Test for SUCCESS - */ - $team = $this->client->call(Client::METHOD_POST, '/teams', array_merge([ - 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'], - ], $this->getHeaders()), [ - 'teamId' => ID::unique(), - 'name' => 'Project Test', - ]); - - $this->assertEquals(201, $team['headers']['status-code']); - $this->assertEquals('Project Test', $team['body']['name']); - $this->assertNotEmpty($team['body']['$id']); - - $response = $this->client->call(Client::METHOD_POST, '/projects', array_merge([ - 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'], - ], $this->getHeaders()), [ - 'projectId' => ID::unique(), - 'name' => 'Project Test', - 'teamId' => $team['body']['$id'], - 'region' => 'default', - ]); - - $this->assertEquals(201, $response['headers']['status-code']); - $this->assertNotEmpty($response['body']['$id']); - $this->assertEquals('Project Test', $response['body']['name']); - $this->assertEquals($team['body']['$id'], $response['body']['teamId']); - $this->assertArrayHasKey('platforms', $response['body']); - $this->assertArrayHasKey('webhooks', $response['body']); - $this->assertArrayHasKey('keys', $response['body']); - - $projectId = $response['body']['$id']; - - $response = $this->client->call(Client::METHOD_POST, '/projects', array_merge([ - 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'], - ], $this->getHeaders()), [ - 'projectId' => ID::unique(), - 'name' => 'Project Test', - 'teamId' => $team['body']['$id'], - ]); - - $this->assertEquals(201, $response['headers']['status-code']); - $this->assertNotEmpty($response['body']['$id']); - $this->assertEquals('Project Test', $response['body']['name']); - $this->assertEquals($team['body']['$id'], $response['body']['teamId']); - $this->assertArrayHasKey('platforms', $response['body']); - $this->assertArrayHasKey('webhooks', $response['body']); - $this->assertArrayHasKey('keys', $response['body']); - - return ['projectId' => $projectId]; - } - - /** - * @depends testCreateProject - */ - public function testSuggestDomain($data): void + public function testCreateProject(): array { - $id = $data['projectId'] ?? ''; + /** + * Test for SUCCESS + */ + $team = $this->client->call(Client::METHOD_POST, '/teams', array_merge([ + 'content-type' => 'application/json', + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), [ + 'teamId' => ID::unique(), + 'name' => 'Project Test', + ]); - $response = $this->client->call(Client::METHOD_POST, '/domains/suggest', array_merge([ - 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'], - ], $this->getHeaders()), [ - 'projectId' => $id, - 'domain' => 'kittens.com', - ]); + $this->assertEquals(201, $team['headers']['status-code']); + $this->assertEquals('Project Test', $team['body']['name']); + $this->assertNotEmpty($team['body']['$id']); - $this->assertEquals(200, $response['headers']['status-code']); - $this->assertNotEmpty($response['body']['domains']); + $response = $this->client->call(Client::METHOD_POST, '/projects', array_merge([ + 'content-type' => 'application/json', + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), [ + 'projectId' => ID::unique(), + 'name' => 'Project Test', + 'teamId' => $team['body']['$id'], + 'region' => 'default', + ]); + + $this->assertEquals(201, $response['headers']['status-code']); + $this->assertNotEmpty($response['body']['$id']); + $this->assertEquals('Project Test', $response['body']['name']); + $this->assertEquals($team['body']['$id'], $response['body']['teamId']); + $this->assertArrayHasKey('platforms', $response['body']); + $this->assertArrayHasKey('webhooks', $response['body']); + $this->assertArrayHasKey('keys', $response['body']); + + $projectId = $response['body']['$id']; + + $response = $this->client->call(Client::METHOD_POST, '/projects', array_merge([ + 'content-type' => 'application/json', + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), [ + 'projectId' => ID::unique(), + 'name' => 'Project Test', + 'teamId' => $team['body']['$id'], + ]); + + $this->assertEquals(201, $response['headers']['status-code']); + $this->assertNotEmpty($response['body']['$id']); + $this->assertEquals('Project Test', $response['body']['name']); + $this->assertEquals($team['body']['$id'], $response['body']['teamId']); + $this->assertArrayHasKey('platforms', $response['body']); + $this->assertArrayHasKey('webhooks', $response['body']); + $this->assertArrayHasKey('keys', $response['body']); + + return ['projectId' => $projectId]; } - /** - * @depends testCreateProject - */ - public function testAvailableDomain($data): void - { - $id = $data['projectId'] ?? ''; - - $response = $this->client->call(Client::METHOD_POST, '/domains/available', array_merge([ - 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'], - ], $this->getHeaders()), [ - 'projectId' => $id, - 'domain' => 'google.com', - ]); - - $available = $response['body']['domain']['available']; - - $this->assertEquals(200, $response['headers']['status-code']); - $this->assertNotEmpty($response['body']['domain']); - $this->assertFalse($available); - } - - /** - * @depends testCreateProject - */ - public function testCreate3rdPartyDomain($data): array - { - $id = $data['projectId'] ?? ''; - $domain = $this->generateRandomString() . '.net'; - - $response = $this->client->call(Client::METHOD_POST, '/domains', array_merge([ - 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'], - ], $this->getHeaders()), [ - 'projectId' => $id, - 'domain' => $domain, - ]); - - $this->assertEquals(201, $response['headers']['status-code']); - $this->assertNotEmpty($response['body']['$id']); - $this->assertEquals($domain, $response['body']['domain']); - $this->assertEquals(false, $response['body']['verification']); - - /** - * Test for FAILURE + * @depends testCreateProject */ - $response = $response = $this->client->call(Client::METHOD_POST, '/domains', array_merge([ - 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'], - ], $this->getHeaders()), [ - 'projectId' => $id, - 'domain' => 'sdkljgfhsdflkjghsdflkgjsh.com', - ]); + public function testSuggestDomain($data): void + { + $id = $data['projectId'] ?? ''; - return []; - } + $response = $this->client->call(Client::METHOD_POST, '/domains/suggest', array_merge([ + 'content-type' => 'application/json', + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), [ + 'projectId' => $id, + 'domain' => 'kittens.com', + ]); - /** - * @depends testCreateProject - */ - public function testPurchaseDomain($data): array - { - $id = $data['projectId'] ?? ''; - $domain = $this->generateRandomString() . '.net'; + $this->assertEquals(200, $response['headers']['status-code']); + $this->assertNotEmpty($response['body']['domains']); + } - $response = $this->client->call(Client::METHOD_POST, '/domains/purchase', array_merge([ - 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'], - ], $this->getHeaders()), [ - 'projectId' => $id, - 'domain' => $domain, - 'firstname' => 'firstname', - 'lastname' => 'lastname', - 'phone' => '+18037889693', - 'email' => 'email@email.com', - 'address1' => 'address1 st', - 'address2' => 'unit address2', - 'address3' => 'apt. address3', - 'city' => 'city', - 'state' => 'state', - 'country' => 'us', - 'postalcode' => '29223', - 'org' => 'myorg', - ]); + /** + * @depends testCreateProject + */ + public function testAvailableDomain($data): void + { + $id = $data['projectId'] ?? ''; - $this->assertEquals(201, $response['headers']['status-code']); - $this->assertTrue($response['body']['registered']); + $response = $this->client->call(Client::METHOD_POST, '/domains/available', array_merge([ + 'content-type' => 'application/json', + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), [ + 'projectId' => $id, + 'domain' => 'google.com', + ]); - return [ - 'projectId' => $id, - 'domain' => $domain, - ]; - } + $available = $response['body']['domain']['available']; - public function testTransferInDomain(): void - { - // This will always fail mainly because it's a test env, - // but also because: - // - we use random domains to test - // - transfer lock is default - // - unable to unlock transfer because domains (in tests) are new. - // ** Even when testing against my own live domains, it failed. - // So we test for a proper formatted response, - // with "successful" being "false". + $this->assertEquals(200, $response['headers']['status-code']); + $this->assertNotEmpty($response['body']['domain']); + $this->assertFalse($available); + } - $this->markTestSkipped("Transfer test skipped because it always fails."); - } + /** + * @depends testCreateProject + */ + public function testCreate3rdPartyDomain($data): array + { + $id = $data['projectId'] ?? ''; + $domain = $this->generateRandomString().'.net'; - public function testTransferOutDomain(): void - { - // This will always fail mainly because it's a test env, - // but also because: - // - we use random domains to test - // - transfer lock is default - // - unable to unlock transfer because domains (in tests) are new. - // ** Even when testing against my own live domains, it failed. - // So we test for a proper formatted response, - // with "successful" being "false". + $response = $this->client->call(Client::METHOD_POST, '/domains', array_merge([ + 'content-type' => 'application/json', + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), [ + 'projectId' => $id, + 'domain' => $domain, + ]); - $this->markTestSkipped("Transfer test skipped because it always fails."); - } + $this->assertEquals(201, $response['headers']['status-code']); + $this->assertNotEmpty($response['body']['$id']); + $this->assertEquals($domain, $response['body']['domain']); + $this->assertEquals(false, $response['body']['verification']); - /** - * @depends testCreateProject - */ - public function testDomainList($data): array - { - $id = $data['projectId'] ?? ''; + /** + * Test for FAILURE + */ + $response = $response = $this->client->call(Client::METHOD_POST, '/domains', array_merge([ + 'content-type' => 'application/json', + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), [ + 'projectId' => $id, + 'domain' => 'sdkljgfhsdflkjghsdflkgjsh.com', + ]); - $response = $this->client->call(Client::METHOD_GET, '/domains', array_merge([ - 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'], - ], $this->getHeaders()), [ - 'projectId' => $id, - ]); + return []; + } - $this->assertEquals(200, $response['headers']['status-code']); - $this->assertTrue($response['body']['total'] > 0); - $this->assertTrue(count($response['body']['domains']) > 0); + /** + * @depends testCreateProject + */ + public function testPurchaseDomain($data): array + { + $id = $data['projectId'] ?? ''; + $domain = $this->generateRandomString().'.net'; - return [ - 'projectId' => $id, - 'domains' => $response['body']['domains'], - ]; - } + $response = $this->client->call(Client::METHOD_POST, '/domains/purchase', array_merge([ + 'content-type' => 'application/json', + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), [ + 'projectId' => $id, + 'domain' => $domain, + 'firstname' => 'firstname', + 'lastname' => 'lastname', + 'phone' => '+18037889693', + 'email' => 'email@email.com', + 'address1' => 'address1 st', + 'address2' => 'unit address2', + 'address3' => 'apt. address3', + 'city' => 'city', + 'state' => 'state', + 'country' => 'us', + 'postalcode' => '29223', + 'org' => 'myorg', + ]); - /** - * @depends testDomainList - */ - public function testDomainGet($data): array - { - $id = $data['projectId'] ?? ''; - $domains = $data['domains'] ?? []; - $domain = $domains[0]; - $domainId = $domain['$id']; + $this->assertEquals(201, $response['headers']['status-code']); + $this->assertTrue($response['body']['registered']); - $response = $this->client->call(Client::METHOD_GET, '/domains/' . $domainId, array_merge([ - 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'], - ], $this->getHeaders()), [ - 'projectId' => $id, - 'domainId' => $domains[0]['$id'], - ]); + return [ + 'projectId' => $id, + 'domain' => $domain, + ]; + } - $this->assertEquals(200, $response['headers']['status-code']); + public function testTransferInDomain(): void + { + // This will always fail mainly because it's a test env, + // but also because: + // - we use random domains to test + // - transfer lock is default + // - unable to unlock transfer because domains (in tests) are new. + // ** Even when testing against my own live domains, it failed. + // So we test for a proper formatted response, + // with "successful" being "false". - return [ - 'projectId' => $id, - 'domainId' => $domainId - ]; - } + $this->markTestSkipped('Transfer test skipped because it always fails.'); + } - /** - * @depends testDomainGet - */ - public function testDomainDelete($data): string - { - $id = $data['projectId'] ?? ''; - $domainId = $data['domainId'] ?? ''; + public function testTransferOutDomain(): void + { + // This will always fail mainly because it's a test env, + // but also because: + // - we use random domains to test + // - transfer lock is default + // - unable to unlock transfer because domains (in tests) are new. + // ** Even when testing against my own live domains, it failed. + // So we test for a proper formatted response, + // with "successful" being "false". - $response = $this->client->call(Client::METHOD_DELETE, '/domains/' . $domainId, array_merge([ - 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'], - ], $this->getHeaders()), [ - 'projectId' => $id, - 'domainId' => $domainId, - ]); + $this->markTestSkipped('Transfer test skipped because it always fails.'); + } - $this->assertEquals(204, $response['headers']['status-code']); + /** + * @depends testCreateProject + */ + public function testDomainList($data): array + { + $id = $data['projectId'] ?? ''; - return $domainId; - } + $response = $this->client->call(Client::METHOD_GET, '/domains', array_merge([ + 'content-type' => 'application/json', + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), [ + 'projectId' => $id, + ]); - private function generateRandomString(int $length = 10): string - { - $characters = 'abcdefghijklmnopqrstuvwxyz'; - $charactersLength = strlen($characters); - $randomString = ''; - - for ($i = 0; $i < $length; $i++) { - $randomString .= $characters[random_int(0, $charactersLength - 1)]; - } - - return $randomString; - } - -} \ No newline at end of file + $this->assertEquals(200, $response['headers']['status-code']); + $this->assertTrue($response['body']['total'] > 0); + $this->assertTrue(count($response['body']['domains']) > 0); + + return [ + 'projectId' => $id, + 'domains' => $response['body']['domains'], + ]; + } + + /** + * @depends testDomainList + */ + public function testDomainGet($data): array + { + $id = $data['projectId'] ?? ''; + $domains = $data['domains'] ?? []; + $domain = $domains[0]; + $domainId = $domain['$id']; + + $response = $this->client->call(Client::METHOD_GET, '/domains/'.$domainId, array_merge([ + 'content-type' => 'application/json', + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), [ + 'projectId' => $id, + 'domainId' => $domains[0]['$id'], + ]); + + $this->assertEquals(200, $response['headers']['status-code']); + + return [ + 'projectId' => $id, + 'domainId' => $domainId, + ]; + } + + /** + * @depends testDomainGet + */ + public function testDomainDelete($data): string + { + $id = $data['projectId'] ?? ''; + $domainId = $data['domainId'] ?? ''; + + $response = $this->client->call(Client::METHOD_DELETE, '/domains/'.$domainId, array_merge([ + 'content-type' => 'application/json', + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), [ + 'projectId' => $id, + 'domainId' => $domainId, + ]); + + $this->assertEquals(204, $response['headers']['status-code']); + + return $domainId; + } + + private function generateRandomString(int $length = 10): string + { + $characters = 'abcdefghijklmnopqrstuvwxyz'; + $charactersLength = strlen($characters); + $randomString = ''; + + for ($i = 0; $i < $length; $i++) { + $randomString .= $characters[random_int(0, $charactersLength - 1)]; + } + + return $randomString; + } +} diff --git a/tests/e2e/Services/Functions/FunctionsBase.php b/tests/e2e/Services/Functions/FunctionsBase.php index c45ebbe068..ad41ab7e47 100644 --- a/tests/e2e/Services/Functions/FunctionsBase.php +++ b/tests/e2e/Services/Functions/FunctionsBase.php @@ -8,11 +8,12 @@ use Utopia\CLI\Console; trait FunctionsBase { protected string $stdout = ''; + protected string $stderr = ''; protected function packageCode($folder) { - Console::execute('cd ' . realpath(__DIR__ . "/../../../resources/functions") . "/$folder && tar --exclude code.tar.gz -czf code.tar.gz .", '', $this->stdout, $this->stderr); + Console::execute('cd '.realpath(__DIR__.'/../../../resources/functions')."/$folder && tar --exclude code.tar.gz -czf code.tar.gz .", '', $this->stdout, $this->stderr); } // /** diff --git a/tests/e2e/Services/Functions/FunctionsConsoleClientTest.php b/tests/e2e/Services/Functions/FunctionsConsoleClientTest.php index cd01b257a1..f1db496504 100644 --- a/tests/e2e/Services/Functions/FunctionsConsoleClientTest.php +++ b/tests/e2e/Services/Functions/FunctionsConsoleClientTest.php @@ -2,9 +2,9 @@ namespace Tests\E2E\Services\Functions; -use Tests\E2E\Scopes\Scope; -use Tests\E2E\Scopes\ProjectCustom; use Tests\E2E\Client; +use Tests\E2E\Scopes\ProjectCustom; +use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\SideConsole; use Utopia\Database\Helpers\ID; use Utopia\Database\Helpers\Role; @@ -41,13 +41,13 @@ class FunctionsConsoleClientTest extends Scope 'functionId' => ID::unique(), 'name' => 'Test Failure', 'execute' => ['some-random-string'], - 'runtime' => 'php-8.0' + 'runtime' => 'php-8.0', ]); $this->assertEquals(400, $response['headers']['status-code']); return [ - 'functionId' => $function['body']['$id'] + 'functionId' => $function['body']['$id'], ]; } @@ -59,21 +59,20 @@ class FunctionsConsoleClientTest extends Scope /** * Test for FAILURE */ - - $response = $this->client->call(Client::METHOD_GET, '/functions/' . $data['functionId'] . '/usage', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/functions/'.$data['functionId'].'/usage', array_merge([ 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'] + 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'range' => '232h' + 'range' => '232h', ]); $this->assertEquals(400, $response['headers']['status-code']); $response = $this->client->call(Client::METHOD_GET, '/functions/randomFunctionId/usage', array_merge([ 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'] + 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'range' => '24h' + 'range' => '24h', ]); $this->assertEquals(404, $response['headers']['status-code']); @@ -81,12 +80,11 @@ class FunctionsConsoleClientTest extends Scope /** * Test for SUCCESS */ - - $response = $this->client->call(Client::METHOD_GET, '/functions/' . $data['functionId'] . '/usage', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/functions/'.$data['functionId'].'/usage', array_merge([ 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'] + 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'range' => '24h' + 'range' => '24h', ]); $this->assertEquals($response['headers']['status-code'], 200); @@ -110,13 +108,12 @@ class FunctionsConsoleClientTest extends Scope /** * Test for SUCCESS */ - - $response = $this->client->call(Client::METHOD_POST, '/functions/' . $data['functionId'] . '/variables', array_merge([ + $response = $this->client->call(Client::METHOD_POST, '/functions/'.$data['functionId'].'/variables', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'key' => 'APP_TEST', - 'value' => 'TESTINGVALUE' + 'value' => 'TESTINGVALUE', ]); $this->assertEquals(201, $response['headers']['status-code']); @@ -125,13 +122,12 @@ class FunctionsConsoleClientTest extends Scope /** * Test for FAILURE */ - - $response = $this->client->call(Client::METHOD_POST, '/functions/' . $data['functionId'] . '/variables', array_merge([ + $response = $this->client->call(Client::METHOD_POST, '/functions/'.$data['functionId'].'/variables', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'key' => 'APP_TEST', - 'value' => 'ANOTHER_TESTINGVALUE' + 'value' => 'ANOTHER_TESTINGVALUE', ]); $this->assertEquals(409, $response['headers']['status-code']); @@ -139,28 +135,28 @@ class FunctionsConsoleClientTest extends Scope return array_merge( $data, [ - 'variableId' => $variableId + 'variableId' => $variableId, ] ); - $longKey = str_repeat("A", 256); - $response = $this->client->call(Client::METHOD_POST, '/functions/' . $data['functionId'] . '/variables', array_merge([ + $longKey = str_repeat('A', 256); + $response = $this->client->call(Client::METHOD_POST, '/functions/'.$data['functionId'].'/variables', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'key' => $longKey, - 'value' => 'TESTINGVALUE' + 'value' => 'TESTINGVALUE', ]); $this->assertEquals(400, $response['headers']['status-code']); - $longValue = str_repeat("#", 8193); - $response = $this->client->call(Client::METHOD_POST, '/functions/' . $data['functionId'] . '/variables', array_merge([ + $longValue = str_repeat('#', 8193); + $response = $this->client->call(Client::METHOD_POST, '/functions/'.$data['functionId'].'/variables', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'key' => 'LONGKEY', - 'value' => $longValue + 'value' => $longValue, ]); $this->assertEquals(400, $response['headers']['status-code']); @@ -174,17 +170,16 @@ class FunctionsConsoleClientTest extends Scope /** * Test for SUCCESS */ - - $response = $this->client->call(Client::METHOD_GET, '/functions/' . $data['functionId'] . '/variables', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/functions/'.$data['functionId'].'/variables', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); $this->assertEquals(200, $response['headers']['status-code']); - $this->assertEquals(1, sizeof($response['body']['variables'])); + $this->assertEquals(1, count($response['body']['variables'])); $this->assertEquals(1, $response['body']['total']); - $this->assertEquals("APP_TEST", $response['body']['variables'][0]['key']); - $this->assertEquals("TESTINGVALUE", $response['body']['variables'][0]['value']); + $this->assertEquals('APP_TEST', $response['body']['variables'][0]['key']); + $this->assertEquals('TESTINGVALUE', $response['body']['variables'][0]['value']); /** * Test for FAILURE @@ -201,21 +196,19 @@ class FunctionsConsoleClientTest extends Scope /** * Test for SUCCESS */ - - $response = $this->client->call(Client::METHOD_GET, '/functions/' . $data['functionId'] . '/variables/' . $data['variableId'], array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/functions/'.$data['functionId'].'/variables/'.$data['variableId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); $this->assertEquals(200, $response['headers']['status-code']); - $this->assertEquals("APP_TEST", $response['body']['key']); - $this->assertEquals("TESTINGVALUE", $response['body']['value']); + $this->assertEquals('APP_TEST', $response['body']['key']); + $this->assertEquals('TESTINGVALUE', $response['body']['value']); /** * Test for FAILURE */ - - $response = $this->client->call(Client::METHOD_GET, '/functions/' . $data['functionId'] . '/variables/NON_EXISTING_VARIABLE', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/functions/'.$data['functionId'].'/variables/NON_EXISTING_VARIABLE', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -233,29 +226,28 @@ class FunctionsConsoleClientTest extends Scope /** * Test for SUCCESS */ - - $response = $this->client->call(Client::METHOD_PUT, '/functions/' . $data['functionId'] . '/variables/' . $data['variableId'], array_merge([ + $response = $this->client->call(Client::METHOD_PUT, '/functions/'.$data['functionId'].'/variables/'.$data['variableId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'key' => 'APP_TEST_UPDATE', - 'value' => 'TESTINGVALUEUPDATED' + 'value' => 'TESTINGVALUEUPDATED', ]); $this->assertEquals(200, $response['headers']['status-code']); - $this->assertEquals("APP_TEST_UPDATE", $response['body']['key']); - $this->assertEquals("TESTINGVALUEUPDATED", $response['body']['value']); + $this->assertEquals('APP_TEST_UPDATE', $response['body']['key']); + $this->assertEquals('TESTINGVALUEUPDATED', $response['body']['value']); - $variable = $this->client->call(Client::METHOD_GET, '/functions/' . $data['functionId'] . '/variables/' . $data['variableId'], array_merge([ + $variable = $this->client->call(Client::METHOD_GET, '/functions/'.$data['functionId'].'/variables/'.$data['variableId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); $this->assertEquals(200, $variable['headers']['status-code']); - $this->assertEquals("APP_TEST_UPDATE", $variable['body']['key']); - $this->assertEquals("TESTINGVALUEUPDATED", $variable['body']['value']); + $this->assertEquals('APP_TEST_UPDATE', $variable['body']['key']); + $this->assertEquals('TESTINGVALUEUPDATED', $variable['body']['value']); - $response = $this->client->call(Client::METHOD_PUT, '/functions/' . $data['functionId'] . '/variables/' . $data['variableId'], array_merge([ + $response = $this->client->call(Client::METHOD_PUT, '/functions/'.$data['functionId'].'/variables/'.$data['variableId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -263,56 +255,55 @@ class FunctionsConsoleClientTest extends Scope ]); $this->assertEquals(200, $response['headers']['status-code']); - $this->assertEquals("APP_TEST_UPDATE_2", $response['body']['key']); - $this->assertEquals("TESTINGVALUEUPDATED", $response['body']['value']); + $this->assertEquals('APP_TEST_UPDATE_2', $response['body']['key']); + $this->assertEquals('TESTINGVALUEUPDATED', $response['body']['value']); - $variable = $this->client->call(Client::METHOD_GET, '/functions/' . $data['functionId'] . '/variables/' . $data['variableId'], array_merge([ + $variable = $this->client->call(Client::METHOD_GET, '/functions/'.$data['functionId'].'/variables/'.$data['variableId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); $this->assertEquals(200, $variable['headers']['status-code']); - $this->assertEquals("APP_TEST_UPDATE_2", $variable['body']['key']); - $this->assertEquals("TESTINGVALUEUPDATED", $variable['body']['value']); + $this->assertEquals('APP_TEST_UPDATE_2', $variable['body']['key']); + $this->assertEquals('TESTINGVALUEUPDATED', $variable['body']['value']); /** * Test for FAILURE */ - - $response = $this->client->call(Client::METHOD_PUT, '/functions/' . $data['functionId'] . '/variables/' . $data['variableId'], array_merge([ + $response = $this->client->call(Client::METHOD_PUT, '/functions/'.$data['functionId'].'/variables/'.$data['variableId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); $this->assertEquals(400, $response['headers']['status-code']); - $response = $this->client->call(Client::METHOD_PUT, '/functions/' . $data['functionId'] . '/variables/' . $data['variableId'], array_merge([ + $response = $this->client->call(Client::METHOD_PUT, '/functions/'.$data['functionId'].'/variables/'.$data['variableId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'value' => 'TESTINGVALUEUPDATED_2' + 'value' => 'TESTINGVALUEUPDATED_2', ]); $this->assertEquals(400, $response['headers']['status-code']); - $longKey = str_repeat("A", 256); - $response = $this->client->call(Client::METHOD_PUT, '/functions/' . $data['functionId'] . '/variables/' . $data['variableId'], array_merge([ + $longKey = str_repeat('A', 256); + $response = $this->client->call(Client::METHOD_PUT, '/functions/'.$data['functionId'].'/variables/'.$data['variableId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'key' => $longKey, - 'value' => 'TESTINGVALUEUPDATED' + 'value' => 'TESTINGVALUEUPDATED', ]); $this->assertEquals(400, $response['headers']['status-code']); - $longValue = str_repeat("#", 8193); - $response = $this->client->call(Client::METHOD_PUT, '/functions/' . $data['functionId'] . '/variables/' . $data['variableId'], array_merge([ + $longValue = str_repeat('#', 8193); + $response = $this->client->call(Client::METHOD_PUT, '/functions/'.$data['functionId'].'/variables/'.$data['variableId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'key' => 'APP_TEST_UPDATE', - 'value' => $longValue + 'value' => $longValue, ]); $this->assertEquals(400, $response['headers']['status-code']); @@ -328,28 +319,26 @@ class FunctionsConsoleClientTest extends Scope /** * Test for SUCCESS */ - - $response = $this->client->call(Client::METHOD_DELETE, '/functions/' . $data['functionId'] . '/variables/' . $data['variableId'], array_merge([ + $response = $this->client->call(Client::METHOD_DELETE, '/functions/'.$data['functionId'].'/variables/'.$data['variableId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); $this->assertEquals(204, $response['headers']['status-code']); - $response = $this->client->call(Client::METHOD_GET, '/functions/' . $data['functionId'] . '/variables', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/functions/'.$data['functionId'].'/variables', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); $this->assertEquals(200, $response['headers']['status-code']); - $this->assertEquals(0, sizeof($response['body']['variables'])); + $this->assertEquals(0, count($response['body']['variables'])); $this->assertEquals(0, $response['body']['total']); /** * Test for FAILURE */ - - $response = $this->client->call(Client::METHOD_DELETE, '/functions/' . $data['functionId'] . '/variables/NON_EXISTING_VARIABLE', array_merge([ + $response = $this->client->call(Client::METHOD_DELETE, '/functions/'.$data['functionId'].'/variables/NON_EXISTING_VARIABLE', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); diff --git a/tests/e2e/Services/Functions/FunctionsCustomClientTest.php b/tests/e2e/Services/Functions/FunctionsCustomClientTest.php index 57d237b9af..8853a75e9d 100644 --- a/tests/e2e/Services/Functions/FunctionsCustomClientTest.php +++ b/tests/e2e/Services/Functions/FunctionsCustomClientTest.php @@ -7,8 +7,6 @@ use Tests\E2E\Client; use Tests\E2E\Scopes\ProjectCustom; use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\SideClient; -use Utopia\CLI\Console; -use Utopia\Database\Database; use Utopia\Database\Helpers\ID; use Utopia\Database\Helpers\Role; @@ -67,7 +65,7 @@ class FunctionsCustomClientTest extends Scope $this->assertEquals(201, $function['headers']['status-code']); /** Create Variables */ - $variable = $this->client->call(Client::METHOD_POST, '/functions/' . $function['body']['$id'] . '/variables', [ + $variable = $this->client->call(Client::METHOD_POST, '/functions/'.$function['body']['$id'].'/variables', [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], 'x-appwrite-key' => $this->getProject()['apiKey'], @@ -76,7 +74,7 @@ class FunctionsCustomClientTest extends Scope 'value' => 'funcValue1', ]); - $variable2 = $this->client->call(Client::METHOD_POST, '/functions/' . $function['body']['$id'] . '/variables', [ + $variable2 = $this->client->call(Client::METHOD_POST, '/functions/'.$function['body']['$id'].'/variables', [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], 'x-appwrite-key' => $this->getProject()['apiKey'], @@ -85,7 +83,7 @@ class FunctionsCustomClientTest extends Scope 'value' => 'funcValue2', ]); - $variable3 = $this->client->call(Client::METHOD_POST, '/functions/' . $function['body']['$id'] . '/variables', [ + $variable3 = $this->client->call(Client::METHOD_POST, '/functions/'.$function['body']['$id'].'/variables', [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], 'x-appwrite-key' => $this->getProject()['apiKey'], @@ -99,10 +97,10 @@ class FunctionsCustomClientTest extends Scope $this->assertEquals(201, $variable3['headers']['status-code']); $folder = 'php'; - $code = realpath(__DIR__ . '/../../../resources/functions') . "/$folder/code.tar.gz"; + $code = realpath(__DIR__.'/../../../resources/functions')."/$folder/code.tar.gz"; $this->packageCode($folder); - $deployment = $this->client->call(Client::METHOD_POST, '/functions/' . $function['body']['$id'] . '/deployments', [ + $deployment = $this->client->call(Client::METHOD_POST, '/functions/'.$function['body']['$id'].'/deployments', [ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], 'x-appwrite-key' => $this->getProject()['apiKey'], @@ -118,7 +116,7 @@ class FunctionsCustomClientTest extends Scope // Wait for deployment to be built. sleep(20); - $function = $this->client->call(Client::METHOD_PATCH, '/functions/' . $function['body']['$id'] . '/deployments/' . $deploymentId, [ + $function = $this->client->call(Client::METHOD_PATCH, '/functions/'.$function['body']['$id'].'/deployments/'.$deploymentId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], 'x-appwrite-key' => $this->getProject()['apiKey'], @@ -126,7 +124,7 @@ class FunctionsCustomClientTest extends Scope $this->assertEquals(200, $function['headers']['status-code']); - $execution = $this->client->call(Client::METHOD_POST, '/functions/' . $function['body']['$id'] . '/executions', [ + $execution = $this->client->call(Client::METHOD_POST, '/functions/'.$function['body']['$id'].'/executions', [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], [ @@ -135,7 +133,7 @@ class FunctionsCustomClientTest extends Scope $this->assertEquals(401, $execution['headers']['status-code']); - $execution = $this->client->call(Client::METHOD_POST, '/functions/' . $function['body']['$id'] . '/executions', array_merge([ + $execution = $this->client->call(Client::METHOD_POST, '/functions/'.$function['body']['$id'].'/executions', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -145,7 +143,7 @@ class FunctionsCustomClientTest extends Scope $this->assertEquals(202, $execution['headers']['status-code']); // Cleanup : Delete function - $response = $this->client->call(Client::METHOD_DELETE, '/functions/' . $function['body']['$id'], [ + $response = $this->client->call(Client::METHOD_DELETE, '/functions/'.$function['body']['$id'], [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], 'x-appwrite-key' => $this->getProject()['apiKey'], @@ -181,7 +179,7 @@ class FunctionsCustomClientTest extends Scope $this->assertEquals(201, $function['headers']['status-code']); /** Create Variables */ - $variable = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/variables', [ + $variable = $this->client->call(Client::METHOD_POST, '/functions/'.$functionId.'/variables', [ 'content-type' => 'application/json', 'x-appwrite-project' => $projectId, 'x-appwrite-key' => $apikey, @@ -190,7 +188,7 @@ class FunctionsCustomClientTest extends Scope 'value' => 'funcValue1', ]); - $variable2 = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/variables', [ + $variable2 = $this->client->call(Client::METHOD_POST, '/functions/'.$functionId.'/variables', [ 'content-type' => 'application/json', 'x-appwrite-project' => $projectId, 'x-appwrite-key' => $apikey, @@ -199,7 +197,7 @@ class FunctionsCustomClientTest extends Scope 'value' => 'funcValue2', ]); - $variable3 = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/variables', [ + $variable3 = $this->client->call(Client::METHOD_POST, '/functions/'.$functionId.'/variables', [ 'content-type' => 'application/json', 'x-appwrite-project' => $projectId, 'x-appwrite-key' => $apikey, @@ -213,10 +211,10 @@ class FunctionsCustomClientTest extends Scope $this->assertEquals(201, $variable3['headers']['status-code']); $folder = 'php-fn'; - $code = realpath(__DIR__ . '/../../../resources/functions') . "/$folder/code.tar.gz"; + $code = realpath(__DIR__.'/../../../resources/functions')."/$folder/code.tar.gz"; $this->packageCode($folder); - $deployment = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/deployments', [ + $deployment = $this->client->call(Client::METHOD_POST, '/functions/'.$functionId.'/deployments', [ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $projectId, 'x-appwrite-key' => $apikey, @@ -232,7 +230,7 @@ class FunctionsCustomClientTest extends Scope $this->assertEquals(202, $deployment['headers']['status-code']); - $function = $this->client->call(Client::METHOD_PATCH, '/functions/' . $functionId . '/deployments/' . $deploymentId, [ + $function = $this->client->call(Client::METHOD_PATCH, '/functions/'.$functionId.'/deployments/'.$deploymentId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $projectId, 'x-appwrite-key' => $apikey, @@ -240,12 +238,12 @@ class FunctionsCustomClientTest extends Scope $this->assertEquals(200, $function['headers']['status-code']); - $execution = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/executions', array_merge([ + $execution = $this->client->call(Client::METHOD_POST, '/functions/'.$functionId.'/executions', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $projectId, ], $this->getHeaders()), [ 'data' => 'foobar', - 'async' => true + 'async' => true, ]); $this->assertEquals(202, $execution['headers']['status-code']); @@ -254,7 +252,7 @@ class FunctionsCustomClientTest extends Scope sleep(20); - $executions = $this->client->call(Client::METHOD_GET, '/functions/' . $functionId . '/executions/' . $executionId, [ + $executions = $this->client->call(Client::METHOD_GET, '/functions/'.$functionId.'/executions/'.$executionId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $projectId, 'x-appwrite-key' => $apikey, @@ -277,7 +275,7 @@ class FunctionsCustomClientTest extends Scope $this->assertEquals($projectId, $output['APPWRITE_FUNCTION_PROJECT_ID']); return [ - 'functionId' => $functionId + 'functionId' => $functionId, ]; } @@ -311,10 +309,10 @@ class FunctionsCustomClientTest extends Scope $this->assertEquals(201, $function['headers']['status-code']); $folder = 'php-fn'; - $code = realpath(__DIR__ . '/../../../resources/functions') . "/$folder/code.tar.gz"; + $code = realpath(__DIR__.'/../../../resources/functions')."/$folder/code.tar.gz"; $this->packageCode($folder); - $deployment = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/deployments', [ + $deployment = $this->client->call(Client::METHOD_POST, '/functions/'.$functionId.'/deployments', [ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $projectId, 'x-appwrite-key' => $apikey, @@ -331,7 +329,7 @@ class FunctionsCustomClientTest extends Scope $this->assertEquals(202, $deployment['headers']['status-code']); // Why do we have to do this? - $function = $this->client->call(Client::METHOD_PATCH, '/functions/' . $functionId . '/deployments/' . $deploymentId, [ + $function = $this->client->call(Client::METHOD_PATCH, '/functions/'.$functionId.'/deployments/'.$deploymentId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $projectId, 'x-appwrite-key' => $apikey, @@ -339,7 +337,7 @@ class FunctionsCustomClientTest extends Scope $this->assertEquals(200, $function['headers']['status-code']); - $execution = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/executions', [ + $execution = $this->client->call(Client::METHOD_POST, '/functions/'.$functionId.'/executions', [ 'content-type' => 'application/json', 'x-appwrite-project' => $projectId, ], [ @@ -364,7 +362,7 @@ class FunctionsCustomClientTest extends Scope 'timeout' => 10, ]); - $execution = $this->client->call(Client::METHOD_POST, '/functions/' . $function['body']['$id'] . '/executions', [ + $execution = $this->client->call(Client::METHOD_POST, '/functions/'.$function['body']['$id'].'/executions', [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], [ @@ -385,19 +383,19 @@ class FunctionsCustomClientTest extends Scope $projectId = $this->getProject()['$id']; $apikey = $this->getProject()['apiKey']; - $execution = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/executions', array_merge([ + $execution = $this->client->call(Client::METHOD_POST, '/functions/'.$functionId.'/executions', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $projectId, ], $this->getHeaders()), [ 'data' => 'foobar', - 'async' => true + 'async' => true, ]); $this->assertEquals(202, $execution['headers']['status-code']); sleep(20); - $base = $this->client->call(Client::METHOD_GET, '/functions/' . $functionId . '/executions', [ + $base = $this->client->call(Client::METHOD_GET, '/functions/'.$functionId.'/executions', [ 'content-type' => 'application/json', 'x-appwrite-project' => $projectId, 'x-appwrite-key' => $apikey, @@ -408,71 +406,71 @@ class FunctionsCustomClientTest extends Scope $this->assertEquals('completed', $base['body']['executions'][0]['status']); $this->assertEquals('completed', $base['body']['executions'][1]['status']); - $executions = $this->client->call(Client::METHOD_GET, '/functions/' . $functionId . '/executions', [ + $executions = $this->client->call(Client::METHOD_GET, '/functions/'.$functionId.'/executions', [ 'content-type' => 'application/json', 'x-appwrite-project' => $projectId, 'x-appwrite-key' => $apikey, ], [ - 'queries' => [ 'limit(1)' ] + 'queries' => ['limit(1)'], ]); $this->assertEquals(200, $executions['headers']['status-code']); $this->assertCount(1, $executions['body']['executions']); - $executions = $this->client->call(Client::METHOD_GET, '/functions/' . $functionId . '/executions', [ + $executions = $this->client->call(Client::METHOD_GET, '/functions/'.$functionId.'/executions', [ 'content-type' => 'application/json', 'x-appwrite-project' => $projectId, 'x-appwrite-key' => $apikey, ], [ - 'queries' => [ 'offset(1)' ] + 'queries' => ['offset(1)'], ]); $this->assertEquals(200, $executions['headers']['status-code']); $this->assertCount(1, $executions['body']['executions']); - $executions = $this->client->call(Client::METHOD_GET, '/functions/' . $functionId . '/executions', [ + $executions = $this->client->call(Client::METHOD_GET, '/functions/'.$functionId.'/executions', [ 'content-type' => 'application/json', 'x-appwrite-project' => $projectId, 'x-appwrite-key' => $apikey, ], [ - 'queries' => [ 'equal("status", ["completed"])' ] + 'queries' => ['equal("status", ["completed"])'], ]); $this->assertEquals(200, $executions['headers']['status-code']); $this->assertCount(2, $executions['body']['executions']); - $executions = $this->client->call(Client::METHOD_GET, '/functions/' . $functionId . '/executions', [ + $executions = $this->client->call(Client::METHOD_GET, '/functions/'.$functionId.'/executions', [ 'content-type' => 'application/json', 'x-appwrite-project' => $projectId, 'x-appwrite-key' => $apikey, ], [ - 'queries' => [ 'equal("status", ["failed"])' ] + 'queries' => ['equal("status", ["failed"])'], ]); $this->assertEquals(200, $executions['headers']['status-code']); $this->assertCount(0, $executions['body']['executions']); - $executions = $this->client->call(Client::METHOD_GET, '/functions/' . $functionId . '/executions', [ + $executions = $this->client->call(Client::METHOD_GET, '/functions/'.$functionId.'/executions', [ 'content-type' => 'application/json', 'x-appwrite-project' => $projectId, 'x-appwrite-key' => $apikey, ], [ - 'queries' => [ 'cursorAfter("' . $base['body']['executions'][0]['$id'] . '")' ], + 'queries' => ['cursorAfter("'.$base['body']['executions'][0]['$id'].'")'], ]); $this->assertCount(1, $executions['body']['executions']); $this->assertEquals($base['body']['executions'][1]['$id'], $executions['body']['executions'][0]['$id']); - $executions = $this->client->call(Client::METHOD_GET, '/functions/' . $functionId . '/executions', [ + $executions = $this->client->call(Client::METHOD_GET, '/functions/'.$functionId.'/executions', [ 'content-type' => 'application/json', 'x-appwrite-project' => $projectId, 'x-appwrite-key' => $apikey, ], [ - 'queries' => [ 'cursorBefore("' . $base['body']['executions'][1]['$id'] . '")' ], + 'queries' => ['cursorBefore("'.$base['body']['executions'][1]['$id'].'")'], ]); // Cleanup : Delete function - $response = $this->client->call(Client::METHOD_DELETE, '/functions/' . $functionId, [ + $response = $this->client->call(Client::METHOD_DELETE, '/functions/'.$functionId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], 'x-appwrite-key' => $this->getProject()['apiKey'], @@ -486,7 +484,6 @@ class FunctionsCustomClientTest extends Scope /** * Test for SUCCESS */ - $projectId = $this->getProject()['$id']; $apikey = $this->getProject()['apiKey']; @@ -507,7 +504,7 @@ class FunctionsCustomClientTest extends Scope $this->assertEquals(201, $function['headers']['status-code']); /** Create Variables */ - $variable = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/variables', [ + $variable = $this->client->call(Client::METHOD_POST, '/functions/'.$functionId.'/variables', [ 'content-type' => 'application/json', 'x-appwrite-project' => $projectId, 'x-appwrite-key' => $apikey, @@ -516,7 +513,7 @@ class FunctionsCustomClientTest extends Scope 'value' => 'funcValue1', ]); - $variable2 = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/variables', [ + $variable2 = $this->client->call(Client::METHOD_POST, '/functions/'.$functionId.'/variables', [ 'content-type' => 'application/json', 'x-appwrite-project' => $projectId, 'x-appwrite-key' => $apikey, @@ -525,7 +522,7 @@ class FunctionsCustomClientTest extends Scope 'value' => 'funcValue2', ]); - $variable3 = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/variables', [ + $variable3 = $this->client->call(Client::METHOD_POST, '/functions/'.$functionId.'/variables', [ 'content-type' => 'application/json', 'x-appwrite-project' => $projectId, 'x-appwrite-key' => $apikey, @@ -539,10 +536,10 @@ class FunctionsCustomClientTest extends Scope $this->assertEquals(201, $variable3['headers']['status-code']); $folder = 'php-fn'; - $code = realpath(__DIR__ . '/../../../resources/functions') . "/$folder/code.tar.gz"; + $code = realpath(__DIR__.'/../../../resources/functions')."/$folder/code.tar.gz"; $this->packageCode($folder); - $deployment = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/deployments', [ + $deployment = $this->client->call(Client::METHOD_POST, '/functions/'.$functionId.'/deployments', [ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $projectId, 'x-appwrite-key' => $apikey, @@ -558,7 +555,7 @@ class FunctionsCustomClientTest extends Scope // Wait for deployment to be built. sleep(20); - $function = $this->client->call(Client::METHOD_PATCH, '/functions/' . $functionId . '/deployments/' . $deploymentId, [ + $function = $this->client->call(Client::METHOD_PATCH, '/functions/'.$functionId.'/deployments/'.$deploymentId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $projectId, 'x-appwrite-key' => $apikey, @@ -566,7 +563,7 @@ class FunctionsCustomClientTest extends Scope $this->assertEquals(200, $function['headers']['status-code']); - $execution = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/executions', array_merge([ + $execution = $this->client->call(Client::METHOD_POST, '/functions/'.$functionId.'/executions', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $projectId, ], $this->getHeaders()), [ @@ -594,7 +591,7 @@ class FunctionsCustomClientTest extends Scope $this->assertEmpty($execution['body']['stderr']); // Cleanup : Delete function - $response = $this->client->call(Client::METHOD_DELETE, '/functions/' . $functionId, [ + $response = $this->client->call(Client::METHOD_DELETE, '/functions/'.$functionId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], 'x-appwrite-key' => $this->getProject()['apiKey'], diff --git a/tests/e2e/Services/Functions/FunctionsCustomServerTest.php b/tests/e2e/Services/Functions/FunctionsCustomServerTest.php index 3fb8ee9171..896c28bd5f 100644 --- a/tests/e2e/Services/Functions/FunctionsCustomServerTest.php +++ b/tests/e2e/Services/Functions/FunctionsCustomServerTest.php @@ -55,7 +55,7 @@ class FunctionsCustomServerTest extends Scope $this->assertEquals(10, $response1['body']['timeout']); /** Create Variables */ - $variable = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/variables', array_merge([ + $variable = $this->client->call(Client::METHOD_POST, '/functions/'.$functionId.'/variables', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -63,7 +63,7 @@ class FunctionsCustomServerTest extends Scope 'value' => 'funcValue1', ]); - $variable2 = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/variables', array_merge([ + $variable2 = $this->client->call(Client::METHOD_POST, '/functions/'.$functionId.'/variables', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -71,7 +71,7 @@ class FunctionsCustomServerTest extends Scope 'value' => 'funcValue2', ]); - $variable3 = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/variables', array_merge([ + $variable3 = $this->client->call(Client::METHOD_POST, '/functions/'.$functionId.'/variables', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -108,7 +108,7 @@ class FunctionsCustomServerTest extends Scope 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'search' => $data['functionId'] + 'search' => $data['functionId'], ]); $this->assertEquals($response['headers']['status-code'], 200); @@ -119,7 +119,7 @@ class FunctionsCustomServerTest extends Scope 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'limit(0)' ] + 'queries' => ['limit(0)'], ]); $this->assertEquals($response['headers']['status-code'], 200); @@ -129,7 +129,7 @@ class FunctionsCustomServerTest extends Scope 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'offset(1)' ] + 'queries' => ['offset(1)'], ]); $this->assertEquals($response['headers']['status-code'], 200); @@ -139,7 +139,7 @@ class FunctionsCustomServerTest extends Scope 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'equal("enabled", true)' ] + 'queries' => ['equal("enabled", true)'], ]); $this->assertEquals($response['headers']['status-code'], 200); @@ -149,7 +149,7 @@ class FunctionsCustomServerTest extends Scope 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'equal("enabled", false)' ] + 'queries' => ['equal("enabled", false)'], ]); $this->assertEquals($response['headers']['status-code'], 200); @@ -159,7 +159,7 @@ class FunctionsCustomServerTest extends Scope 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'search' => 'Test' + 'search' => 'Test', ]); $this->assertEquals($response['headers']['status-code'], 200); @@ -170,7 +170,7 @@ class FunctionsCustomServerTest extends Scope 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'search' => 'php-8.0' + 'search' => 'php-8.0', ]); $this->assertEquals($response['headers']['status-code'], 200); @@ -197,7 +197,7 @@ class FunctionsCustomServerTest extends Scope $this->assertNotEmpty($response['body']['$id']); /** Create Variables */ - $variable = $this->client->call(Client::METHOD_POST, '/functions/' . $response['body']['$id'] . '/variables', array_merge([ + $variable = $this->client->call(Client::METHOD_POST, '/functions/'.$response['body']['$id'].'/variables', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -205,7 +205,7 @@ class FunctionsCustomServerTest extends Scope 'value' => 'funcValue1', ]); - $variable2 = $this->client->call(Client::METHOD_POST, '/functions/' . $response['body']['$id'] . '/variables', array_merge([ + $variable2 = $this->client->call(Client::METHOD_POST, '/functions/'.$response['body']['$id'].'/variables', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -213,7 +213,7 @@ class FunctionsCustomServerTest extends Scope 'value' => 'funcValue2', ]); - $variable3 = $this->client->call(Client::METHOD_POST, '/functions/' . $response['body']['$id'] . '/variables', array_merge([ + $variable3 = $this->client->call(Client::METHOD_POST, '/functions/'.$response['body']['$id'].'/variables', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -241,7 +241,7 @@ class FunctionsCustomServerTest extends Scope 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'cursorAfter("' . $functions['body']['functions'][0]['$id'] . '")' ], + 'queries' => ['cursorAfter("'.$functions['body']['functions'][0]['$id'].'")'], ]); $this->assertEquals($response['headers']['status-code'], 200); @@ -252,7 +252,7 @@ class FunctionsCustomServerTest extends Scope 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'cursorBefore("' . $functions['body']['functions'][1]['$id'] . '")' ], + 'queries' => ['cursorBefore("'.$functions['body']['functions'][1]['$id'].'")'], ]); $this->assertEquals($response['headers']['status-code'], 200); @@ -266,7 +266,7 @@ class FunctionsCustomServerTest extends Scope 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'cursorAfter("unknown")' ], + 'queries' => ['cursorAfter("unknown")'], ]); $this->assertEquals($response['headers']['status-code'], 400); @@ -282,7 +282,7 @@ class FunctionsCustomServerTest extends Scope /** * Test for SUCCESS */ - $function = $this->client->call(Client::METHOD_GET, '/functions/' . $data['functionId'], array_merge([ + $function = $this->client->call(Client::METHOD_GET, '/functions/'.$data['functionId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -311,7 +311,7 @@ class FunctionsCustomServerTest extends Scope /** * Test for SUCCESS */ - $response1 = $this->client->call(Client::METHOD_PUT, '/functions/' . $data['functionId'], array_merge([ + $response1 = $this->client->call(Client::METHOD_PUT, '/functions/'.$data['functionId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -354,10 +354,10 @@ class FunctionsCustomServerTest extends Scope * Test for SUCCESS */ $folder = 'php'; - $code = realpath(__DIR__ . '/../../../resources/functions') . "/$folder/code.tar.gz"; + $code = realpath(__DIR__.'/../../../resources/functions')."/$folder/code.tar.gz"; $this->packageCode($folder); - $deployment = $this->client->call(Client::METHOD_POST, '/functions/' . $data['functionId'] . '/deployments', array_merge([ + $deployment = $this->client->call(Client::METHOD_POST, '/functions/'.$data['functionId'].'/deployments', array_merge([ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -387,28 +387,27 @@ class FunctionsCustomServerTest extends Scope /** * Test for Large Code File SUCCESS */ - $folder = 'php-large'; - $code = realpath(__DIR__ . '/../../../resources/functions') . "/$folder/code.tar.gz"; + $code = realpath(__DIR__.'/../../../resources/functions')."/$folder/code.tar.gz"; $this->packageCode($folder); $chunkSize = 5 * 1024 * 1024; - $handle = @fopen($code, "rb"); + $handle = @fopen($code, 'rb'); $mimeType = 'application/x-gzip'; $counter = 0; $size = filesize($code); $headers = [ 'content-type' => 'multipart/form-data', - 'x-appwrite-project' => $this->getProject()['$id'] + 'x-appwrite-project' => $this->getProject()['$id'], ]; $id = ''; - while (!feof($handle)) { - $curlFile = new \CURLFile('data://' . $mimeType . ';base64,' . base64_encode(@fread($handle, $chunkSize)), $mimeType, 'php-large-fx.tar.gz'); - $headers['content-range'] = 'bytes ' . ($counter * $chunkSize) . '-' . min(((($counter * $chunkSize) + $chunkSize) - 1), $size) . '/' . $size; - if (!empty($id)) { + while (! feof($handle)) { + $curlFile = new \CURLFile('data://'.$mimeType.';base64,'.base64_encode(@fread($handle, $chunkSize)), $mimeType, 'php-large-fx.tar.gz'); + $headers['content-range'] = 'bytes '.($counter * $chunkSize).'-'.min(((($counter * $chunkSize) + $chunkSize) - 1), $size).'/'.$size; + if (! empty($id)) { $headers['x-appwrite-id'] = $id; } - $largeTag = $this->client->call(Client::METHOD_POST, '/functions/' . $data['functionId'] . '/deployments', array_merge($headers, $this->getHeaders()), [ + $largeTag = $this->client->call(Client::METHOD_POST, '/functions/'.$data['functionId'].'/deployments', array_merge($headers, $this->getHeaders()), [ 'entrypoint' => 'index.php', 'code' => $curlFile, ]); @@ -435,7 +434,7 @@ class FunctionsCustomServerTest extends Scope /** * Test for SUCCESS */ - $response = $this->client->call(Client::METHOD_PATCH, '/functions/' . $data['functionId'] . '/deployments/' . $data['deploymentId'], array_merge([ + $response = $this->client->call(Client::METHOD_PATCH, '/functions/'.$data['functionId'].'/deployments/'.$data['deploymentId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -462,7 +461,7 @@ class FunctionsCustomServerTest extends Scope /** * Test for SUCCESS */ - $function = $this->client->call(Client::METHOD_GET, '/functions/' . $data['functionId'] . '/deployments', array_merge([ + $function = $this->client->call(Client::METHOD_GET, '/functions/'.$data['functionId'].'/deployments', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -475,11 +474,11 @@ class FunctionsCustomServerTest extends Scope /** * Test search queries */ - $function = $this->client->call(Client::METHOD_GET, '/functions/' . $data['functionId'] . '/deployments', array_merge([ + $function = $this->client->call(Client::METHOD_GET, '/functions/'.$data['functionId'].'/deployments', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders(), [ - 'search' => $data['functionId'] + 'search' => $data['functionId'], ])); $this->assertEquals($function['headers']['status-code'], 200); @@ -488,51 +487,51 @@ class FunctionsCustomServerTest extends Scope $this->assertCount(2, $function['body']['deployments']); $this->assertEquals($function['body']['deployments'][0]['$id'], $data['deploymentId']); - $function = $this->client->call(Client::METHOD_GET, '/functions/' . $data['functionId'] . '/deployments', array_merge([ + $function = $this->client->call(Client::METHOD_GET, '/functions/'.$data['functionId'].'/deployments', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'limit(1)' ] + 'queries' => ['limit(1)'], ]); $this->assertEquals($function['headers']['status-code'], 200); $this->assertCount(1, $function['body']['deployments']); - $function = $this->client->call(Client::METHOD_GET, '/functions/' . $data['functionId'] . '/deployments', array_merge([ + $function = $this->client->call(Client::METHOD_GET, '/functions/'.$data['functionId'].'/deployments', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'offset(1)' ] + 'queries' => ['offset(1)'], ]); $this->assertEquals($function['headers']['status-code'], 200); $this->assertCount(1, $function['body']['deployments']); - $function = $this->client->call(Client::METHOD_GET, '/functions/' . $data['functionId'] . '/deployments', array_merge([ + $function = $this->client->call(Client::METHOD_GET, '/functions/'.$data['functionId'].'/deployments', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'equal("entrypoint", "index.php")' ] + 'queries' => ['equal("entrypoint", "index.php")'], ]); $this->assertEquals($function['headers']['status-code'], 200); $this->assertCount(2, $function['body']['deployments']); - $function = $this->client->call(Client::METHOD_GET, '/functions/' . $data['functionId'] . '/deployments', array_merge([ + $function = $this->client->call(Client::METHOD_GET, '/functions/'.$data['functionId'].'/deployments', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'equal("entrypoint", "index.js")' ] + 'queries' => ['equal("entrypoint", "index.js")'], ]); $this->assertEquals($function['headers']['status-code'], 200); $this->assertCount(0, $function['body']['deployments']); - $function = $this->client->call(Client::METHOD_GET, '/functions/' . $data['functionId'] . '/deployments', array_merge([ + $function = $this->client->call(Client::METHOD_GET, '/functions/'.$data['functionId'].'/deployments', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders(), [ - 'search' => 'Test' + 'search' => 'Test', ])); $this->assertEquals($function['headers']['status-code'], 200); @@ -541,11 +540,11 @@ class FunctionsCustomServerTest extends Scope $this->assertCount(2, $function['body']['deployments']); $this->assertEquals($function['body']['deployments'][0]['$id'], $data['deploymentId']); - $function = $this->client->call(Client::METHOD_GET, '/functions/' . $data['functionId'] . '/deployments', array_merge([ + $function = $this->client->call(Client::METHOD_GET, '/functions/'.$data['functionId'].'/deployments', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders(), [ - 'search' => 'php-8.0' + 'search' => 'php-8.0', ])); $this->assertEquals($function['headers']['status-code'], 200); @@ -565,7 +564,7 @@ class FunctionsCustomServerTest extends Scope /** * Test for SUCCESS */ - $function = $this->client->call(Client::METHOD_GET, '/functions/' . $data['functionId'] . '/deployments/' . $data['deploymentId'], array_merge([ + $function = $this->client->call(Client::METHOD_GET, '/functions/'.$data['functionId'].'/deployments/'.$data['deploymentId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -579,7 +578,7 @@ class FunctionsCustomServerTest extends Scope /** * Test for FAILURE */ - $function = $this->client->call(Client::METHOD_GET, '/functions/' . $data['functionId'] . '/deployments/x', array_merge([ + $function = $this->client->call(Client::METHOD_GET, '/functions/'.$data['functionId'].'/deployments/x', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -597,7 +596,7 @@ class FunctionsCustomServerTest extends Scope /** * Test for SUCCESS */ - $execution = $this->client->call(Client::METHOD_POST, '/functions/' . $data['functionId'] . '/executions', array_merge([ + $execution = $this->client->call(Client::METHOD_POST, '/functions/'.$data['functionId'].'/executions', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -620,7 +619,7 @@ class FunctionsCustomServerTest extends Scope sleep(10); - $execution = $this->client->call(Client::METHOD_GET, '/functions/' . $data['functionId'] . '/executions/' . $executionId, array_merge([ + $execution = $this->client->call(Client::METHOD_GET, '/functions/'.$data['functionId'].'/executions/'.$executionId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -644,7 +643,6 @@ class FunctionsCustomServerTest extends Scope /** * Test for FAILURE */ - sleep(20); return array_merge($data, ['executionId' => $executionId]); @@ -658,7 +656,7 @@ class FunctionsCustomServerTest extends Scope /** * Test for SUCCESS */ - $function = $this->client->call(Client::METHOD_GET, '/functions/' . $data['functionId'] . '/executions', array_merge([ + $function = $this->client->call(Client::METHOD_GET, '/functions/'.$data['functionId'].'/executions', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -669,31 +667,31 @@ class FunctionsCustomServerTest extends Scope $this->assertCount(1, $function['body']['executions']); $this->assertEquals($function['body']['executions'][0]['$id'], $data['executionId']); - $response = $this->client->call(Client::METHOD_GET, '/functions/' . $data['functionId'] . '/executions', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/functions/'.$data['functionId'].'/executions', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'limit(0)' ] + 'queries' => ['limit(0)'], ]); $this->assertEquals(200, $response['headers']['status-code']); $this->assertCount(0, $response['body']['executions']); - $response = $this->client->call(Client::METHOD_GET, '/functions/' . $data['functionId'] . '/executions', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/functions/'.$data['functionId'].'/executions', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'offset(1)' ] + 'queries' => ['offset(1)'], ]); $this->assertEquals(200, $response['headers']['status-code']); $this->assertCount(0, $response['body']['executions']); - $response = $this->client->call(Client::METHOD_GET, '/functions/' . $data['functionId'] . '/executions', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/functions/'.$data['functionId'].'/executions', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'equal("trigger", "http")' ] + 'queries' => ['equal("trigger", "http")'], ]); $this->assertEquals(200, $response['headers']['status-code']); @@ -702,8 +700,7 @@ class FunctionsCustomServerTest extends Scope /** * Test search queries */ - - $response = $this->client->call(Client::METHOD_GET, '/functions/' . $data['functionId'] . '/executions', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/functions/'.$data['functionId'].'/executions', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -716,7 +713,7 @@ class FunctionsCustomServerTest extends Scope $this->assertCount(1, $response['body']['executions']); $this->assertEquals($data['functionId'], $response['body']['executions'][0]['functionId']); - $response = $this->client->call(Client::METHOD_GET, '/functions/' . $data['functionId'] . '/executions', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/functions/'.$data['functionId'].'/executions', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -741,8 +738,7 @@ class FunctionsCustomServerTest extends Scope /** * Test for SUCCESS */ - - $execution = $this->client->call(Client::METHOD_POST, '/functions/' . $data['functionId'] . '/executions', array_merge([ + $execution = $this->client->call(Client::METHOD_POST, '/functions/'.$data['functionId'].'/executions', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -771,7 +767,7 @@ class FunctionsCustomServerTest extends Scope /** * Test for SUCCESS */ - $function = $this->client->call(Client::METHOD_GET, '/functions/' . $data['functionId'] . '/executions/' . $data['executionId'], array_merge([ + $function = $this->client->call(Client::METHOD_GET, '/functions/'.$data['functionId'].'/executions/'.$data['executionId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -782,7 +778,7 @@ class FunctionsCustomServerTest extends Scope /** * Test for FAILURE */ - $function = $this->client->call(Client::METHOD_GET, '/functions/' . $data['functionId'] . '/executions/x', array_merge([ + $function = $this->client->call(Client::METHOD_GET, '/functions/'.$data['functionId'].'/executions/x', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -800,7 +796,7 @@ class FunctionsCustomServerTest extends Scope /** * Test for SUCCESS */ - $function = $this->client->call(Client::METHOD_DELETE, '/functions/' . $data['functionId'] . '/deployments/' . $data['deploymentId'], array_merge([ + $function = $this->client->call(Client::METHOD_DELETE, '/functions/'.$data['functionId'].'/deployments/'.$data['deploymentId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -808,7 +804,7 @@ class FunctionsCustomServerTest extends Scope $this->assertEquals(204, $function['headers']['status-code']); $this->assertEmpty($function['body']); - $function = $this->client->call(Client::METHOD_GET, '/functions/' . $data['functionId'] . '/deployments/' . $data['deploymentId'], array_merge([ + $function = $this->client->call(Client::METHOD_GET, '/functions/'.$data['functionId'].'/deployments/'.$data['deploymentId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -830,7 +826,7 @@ class FunctionsCustomServerTest extends Scope /** * Test for SUCCESS */ - $function = $this->client->call(Client::METHOD_DELETE, '/functions/' . $data['functionId'], array_merge([ + $function = $this->client->call(Client::METHOD_DELETE, '/functions/'.$data['functionId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -838,7 +834,7 @@ class FunctionsCustomServerTest extends Scope $this->assertEquals(204, $function['headers']['status-code']); $this->assertEmpty($function['body']); - $function = $this->client->call(Client::METHOD_GET, '/functions/' . $data['functionId'], array_merge([ + $function = $this->client->call(Client::METHOD_GET, '/functions/'.$data['functionId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -858,7 +854,7 @@ class FunctionsCustomServerTest extends Scope $entrypoint = 'index.php'; $timeout = 2; $folder = 'timeout'; - $code = realpath(__DIR__ . '/../../../resources/functions') . "/$folder/code.tar.gz"; + $code = realpath(__DIR__.'/../../../resources/functions')."/$folder/code.tar.gz"; $this->packageCode($folder); $function = $this->client->call(Client::METHOD_POST, '/functions', array_merge([ @@ -866,7 +862,7 @@ class FunctionsCustomServerTest extends Scope 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'functionId' => ID::unique(), - 'name' => 'Test ' . $name, + 'name' => 'Test '.$name, 'runtime' => $name, 'events' => [], 'schedule' => '', @@ -877,7 +873,7 @@ class FunctionsCustomServerTest extends Scope $this->assertEquals(201, $function['headers']['status-code']); - $deployment = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/deployments', array_merge([ + $deployment = $this->client->call(Client::METHOD_POST, '/functions/'.$functionId.'/deployments', array_merge([ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -891,7 +887,7 @@ class FunctionsCustomServerTest extends Scope // Allow build step to run sleep(40); - $execution = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/executions', array_merge([ + $execution = $this->client->call(Client::METHOD_POST, '/functions/'.$functionId.'/executions', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -904,7 +900,7 @@ class FunctionsCustomServerTest extends Scope sleep(20); - $executions = $this->client->call(Client::METHOD_GET, '/functions/' . $functionId . '/executions', array_merge([ + $executions = $this->client->call(Client::METHOD_GET, '/functions/'.$functionId.'/executions', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -924,7 +920,7 @@ class FunctionsCustomServerTest extends Scope $this->assertEquals($executions['body']['executions'][0]['stderr'], 'An internal curl error has occurred within the executor! Error Msg: Operation timed out'); // Cleanup : Delete function - $response = $this->client->call(Client::METHOD_DELETE, '/functions/' . $functionId, [ + $response = $this->client->call(Client::METHOD_DELETE, '/functions/'.$functionId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], 'x-appwrite-key' => $this->getProject()['apiKey'], @@ -942,7 +938,7 @@ class FunctionsCustomServerTest extends Scope $entrypoint = 'index.php'; $timeout = 2; $folder = 'php-fn'; - $code = realpath(__DIR__ . '/../../../resources/functions') . "/$folder/code.tar.gz"; + $code = realpath(__DIR__.'/../../../resources/functions')."/$folder/code.tar.gz"; $this->packageCode($folder); $function = $this->client->call(Client::METHOD_POST, '/functions', array_merge([ @@ -950,7 +946,7 @@ class FunctionsCustomServerTest extends Scope 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'functionId' => ID::unique(), - 'name' => 'Test ' . $name, + 'name' => 'Test '.$name, 'runtime' => $name, 'events' => [], 'schedule' => '', @@ -961,7 +957,7 @@ class FunctionsCustomServerTest extends Scope $this->assertEquals(201, $function['headers']['status-code']); - $deployment = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/deployments', array_merge([ + $deployment = $this->client->call(Client::METHOD_POST, '/functions/'.$functionId.'/deployments', array_merge([ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -975,19 +971,19 @@ class FunctionsCustomServerTest extends Scope // Allow build step to run sleep(20); - $deployment = $this->client->call(Client::METHOD_PATCH, '/functions/' . $functionId . '/deployments/' . $deploymentId, array_merge([ + $deployment = $this->client->call(Client::METHOD_PATCH, '/functions/'.$functionId.'/deployments/'.$deploymentId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); $this->assertEquals(200, $deployment['headers']['status-code']); - $execution = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/executions', array_merge([ + $execution = $this->client->call(Client::METHOD_POST, '/functions/'.$functionId.'/executions', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'data' => 'foobar', - 'async' => true + 'async' => true, ]); $executionId = $execution['body']['$id'] ?? ''; @@ -998,7 +994,7 @@ class FunctionsCustomServerTest extends Scope sleep(20); - $executions = $this->client->call(Client::METHOD_GET, '/functions/' . $functionId . '/executions/' . $executionId, array_merge([ + $executions = $this->client->call(Client::METHOD_GET, '/functions/'.$functionId.'/executions/'.$executionId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -1008,7 +1004,7 @@ class FunctionsCustomServerTest extends Scope $this->assertEquals(200, $executions['headers']['status-code']); $this->assertEquals('completed', $executions['body']['status']); $this->assertEquals($functionId, $output['APPWRITE_FUNCTION_ID']); - $this->assertEquals('Test ' . $name, $output['APPWRITE_FUNCTION_NAME']); + $this->assertEquals('Test '.$name, $output['APPWRITE_FUNCTION_NAME']); $this->assertEquals($deploymentId, $output['APPWRITE_FUNCTION_DEPLOYMENT']); $this->assertEquals('http', $output['APPWRITE_FUNCTION_TRIGGER']); $this->assertEquals('PHP', $output['APPWRITE_FUNCTION_RUNTIME_NAME']); @@ -1021,7 +1017,7 @@ class FunctionsCustomServerTest extends Scope $this->assertEquals($this->getProject()['$id'], $output['APPWRITE_FUNCTION_PROJECT_ID']); $this->assertStringContainsString('Amazing Function Log', $executions['body']['stdout']); - $executions = $this->client->call(Client::METHOD_GET, '/functions/' . $functionId . '/executions', array_merge([ + $executions = $this->client->call(Client::METHOD_GET, '/functions/'.$functionId.'/executions', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -1035,7 +1031,7 @@ class FunctionsCustomServerTest extends Scope $this->assertStringContainsString('foobar', $executions['body']['executions'][0]['response']); // Cleanup : Delete function - $response = $this->client->call(Client::METHOD_DELETE, '/functions/' . $functionId, [ + $response = $this->client->call(Client::METHOD_DELETE, '/functions/'.$functionId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], 'x-appwrite-key' => $this->getProject()['apiKey'], @@ -1044,12 +1040,11 @@ class FunctionsCustomServerTest extends Scope $this->assertEquals(204, $response['headers']['status-code']); } - public function testCreateCustomNodeExecution() { $name = 'node-18.0'; $folder = 'node'; - $code = realpath(__DIR__ . '/../../../resources/functions') . "/$folder/code.tar.gz"; + $code = realpath(__DIR__.'/../../../resources/functions')."/$folder/code.tar.gz"; $this->packageCode($folder); $entrypoint = 'index.js'; @@ -1060,7 +1055,7 @@ class FunctionsCustomServerTest extends Scope 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'functionId' => ID::unique(), - 'name' => 'Test ' . $name, + 'name' => 'Test '.$name, 'runtime' => $name, 'events' => [], 'schedule' => '', @@ -1072,7 +1067,7 @@ class FunctionsCustomServerTest extends Scope $this->assertEquals(201, $function['headers']['status-code']); // Create variable - $variable = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/variables', array_merge([ + $variable = $this->client->call(Client::METHOD_POST, '/functions/'.$functionId.'/variables', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1082,7 +1077,7 @@ class FunctionsCustomServerTest extends Scope $this->assertEquals(201, $variable['headers']['status-code']); - $deployment = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/deployments', array_merge([ + $deployment = $this->client->call(Client::METHOD_POST, '/functions/'.$functionId.'/deployments', array_merge([ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1097,12 +1092,12 @@ class FunctionsCustomServerTest extends Scope // Allow build step to run sleep(20); - $execution = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/executions', array_merge([ + $execution = $this->client->call(Client::METHOD_POST, '/functions/'.$functionId.'/executions', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'data' => 'foobar', - 'async' => true + 'async' => true, ]); $executionId = $execution['body']['$id'] ?? ''; @@ -1113,7 +1108,7 @@ class FunctionsCustomServerTest extends Scope sleep(20); - $executions = $this->client->call(Client::METHOD_GET, '/functions/' . $functionId . '/executions/' . $executionId, array_merge([ + $executions = $this->client->call(Client::METHOD_GET, '/functions/'.$functionId.'/executions/'.$executionId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -1123,7 +1118,7 @@ class FunctionsCustomServerTest extends Scope $this->assertEquals(200, $executions['headers']['status-code']); $this->assertEquals('completed', $executions['body']['status']); $this->assertEquals($functionId, $output['APPWRITE_FUNCTION_ID']); - $this->assertEquals('Test ' . $name, $output['APPWRITE_FUNCTION_NAME']); + $this->assertEquals('Test '.$name, $output['APPWRITE_FUNCTION_NAME']); $this->assertEquals($deploymentId, $output['APPWRITE_FUNCTION_DEPLOYMENT']); $this->assertEquals('http', $output['APPWRITE_FUNCTION_TRIGGER']); $this->assertEquals('Node.js', $output['APPWRITE_FUNCTION_RUNTIME_NAME']); @@ -1135,7 +1130,7 @@ class FunctionsCustomServerTest extends Scope $this->assertEmpty($output['APPWRITE_FUNCTION_JWT']); $this->assertEquals($this->getProject()['$id'], $output['APPWRITE_FUNCTION_PROJECT_ID']); - $executions = $this->client->call(Client::METHOD_GET, '/functions/' . $functionId . '/executions', array_merge([ + $executions = $this->client->call(Client::METHOD_GET, '/functions/'.$functionId.'/executions', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -1149,7 +1144,7 @@ class FunctionsCustomServerTest extends Scope $this->assertStringContainsString('foobar', $executions['body']['executions'][0]['response']); // Cleanup : Delete function - $response = $this->client->call(Client::METHOD_DELETE, '/functions/' . $functionId, [ + $response = $this->client->call(Client::METHOD_DELETE, '/functions/'.$functionId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], 'x-appwrite-key' => $this->getProject()['apiKey'], @@ -1162,7 +1157,7 @@ class FunctionsCustomServerTest extends Scope { $name = 'python-3.9'; $folder = 'python'; - $code = realpath(__DIR__ . '/../../../resources/functions') . "/$folder/code.tar.gz"; + $code = realpath(__DIR__.'/../../../resources/functions')."/$folder/code.tar.gz"; $this->packageCode($folder); $entrypoint = 'main.py'; @@ -1173,7 +1168,7 @@ class FunctionsCustomServerTest extends Scope 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'functionId' => ID::unique(), - 'name' => 'Test ' . $name, + 'name' => 'Test '.$name, 'runtime' => $name, 'events' => [], 'schedule' => '', @@ -1185,7 +1180,7 @@ class FunctionsCustomServerTest extends Scope $this->assertEquals(201, $function['headers']['status-code']); /** Create Variables */ - $variable = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/variables', array_merge([ + $variable = $this->client->call(Client::METHOD_POST, '/functions/'.$functionId.'/variables', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1195,7 +1190,7 @@ class FunctionsCustomServerTest extends Scope $this->assertEquals(201, $variable['headers']['status-code']); - $deployment = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/deployments', array_merge([ + $deployment = $this->client->call(Client::METHOD_POST, '/functions/'.$functionId.'/deployments', array_merge([ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1210,12 +1205,12 @@ class FunctionsCustomServerTest extends Scope // Allow build step to run sleep(60); - $execution = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/executions', array_merge([ + $execution = $this->client->call(Client::METHOD_POST, '/functions/'.$functionId.'/executions', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'data' => 'foobar', - 'async' => true + 'async' => true, ]); $executionId = $execution['body']['$id'] ?? ''; @@ -1226,7 +1221,7 @@ class FunctionsCustomServerTest extends Scope sleep(60); - $executions = $this->client->call(Client::METHOD_GET, '/functions/' . $functionId . '/executions/' . $executionId, array_merge([ + $executions = $this->client->call(Client::METHOD_GET, '/functions/'.$functionId.'/executions/'.$executionId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -1236,7 +1231,7 @@ class FunctionsCustomServerTest extends Scope $this->assertEquals(200, $executions['headers']['status-code']); $this->assertEquals('completed', $executions['body']['status']); $this->assertEquals($functionId, $output['APPWRITE_FUNCTION_ID']); - $this->assertEquals('Test ' . $name, $output['APPWRITE_FUNCTION_NAME']); + $this->assertEquals('Test '.$name, $output['APPWRITE_FUNCTION_NAME']); $this->assertEquals($deploymentId, $output['APPWRITE_FUNCTION_DEPLOYMENT']); $this->assertEquals('http', $output['APPWRITE_FUNCTION_TRIGGER']); $this->assertEquals('Python', $output['APPWRITE_FUNCTION_RUNTIME_NAME']); @@ -1249,7 +1244,7 @@ class FunctionsCustomServerTest extends Scope $this->assertEmpty($output['APPWRITE_FUNCTION_JWT']); $this->assertEquals($this->getProject()['$id'], $output['APPWRITE_FUNCTION_PROJECT_ID']); - $executions = $this->client->call(Client::METHOD_GET, '/functions/' . $functionId . '/executions', array_merge([ + $executions = $this->client->call(Client::METHOD_GET, '/functions/'.$functionId.'/executions', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -1263,7 +1258,7 @@ class FunctionsCustomServerTest extends Scope $this->assertStringContainsString('foobar', $executions['body']['executions'][0]['response']); // Cleanup : Delete function - $response = $this->client->call(Client::METHOD_DELETE, '/functions/' . $functionId, [ + $response = $this->client->call(Client::METHOD_DELETE, '/functions/'.$functionId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], 'x-appwrite-key' => $this->getProject()['apiKey'], @@ -1276,7 +1271,7 @@ class FunctionsCustomServerTest extends Scope { $name = 'dart-2.15'; $folder = 'dart'; - $code = realpath(__DIR__ . '/../../../resources/functions') . "/$folder/code.tar.gz"; + $code = realpath(__DIR__.'/../../../resources/functions')."/$folder/code.tar.gz"; $this->packageCode($folder); $entrypoint = 'main.dart'; @@ -1287,7 +1282,7 @@ class FunctionsCustomServerTest extends Scope 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'functionId' => ID::unique(), - 'name' => 'Test ' . $name, + 'name' => 'Test '.$name, 'runtime' => $name, 'events' => [], 'schedule' => '', @@ -1299,7 +1294,7 @@ class FunctionsCustomServerTest extends Scope $this->assertEquals(201, $function['headers']['status-code']); /** Create Variables */ - $variable = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/variables', array_merge([ + $variable = $this->client->call(Client::METHOD_POST, '/functions/'.$functionId.'/variables', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1309,7 +1304,7 @@ class FunctionsCustomServerTest extends Scope $this->assertEquals(201, $variable['headers']['status-code']); - $deployment = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/deployments', array_merge([ + $deployment = $this->client->call(Client::METHOD_POST, '/functions/'.$functionId.'/deployments', array_merge([ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1324,12 +1319,12 @@ class FunctionsCustomServerTest extends Scope // Allow build step to run sleep(80); - $execution = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/executions', array_merge([ + $execution = $this->client->call(Client::METHOD_POST, '/functions/'.$functionId.'/executions', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'data' => 'foobar', - 'async' => true + 'async' => true, ]); $executionId = $execution['body']['$id'] ?? ''; @@ -1340,7 +1335,7 @@ class FunctionsCustomServerTest extends Scope sleep(20); - $executions = $this->client->call(Client::METHOD_GET, '/functions/' . $functionId . '/executions/' . $executionId, array_merge([ + $executions = $this->client->call(Client::METHOD_GET, '/functions/'.$functionId.'/executions/'.$executionId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -1350,7 +1345,7 @@ class FunctionsCustomServerTest extends Scope $this->assertEquals(200, $executions['headers']['status-code']); $this->assertEquals('completed', $executions['body']['status']); $this->assertEquals($functionId, $output['APPWRITE_FUNCTION_ID']); - $this->assertEquals('Test ' . $name, $output['APPWRITE_FUNCTION_NAME']); + $this->assertEquals('Test '.$name, $output['APPWRITE_FUNCTION_NAME']); $this->assertEquals($deploymentId, $output['APPWRITE_FUNCTION_DEPLOYMENT']); $this->assertEquals('http', $output['APPWRITE_FUNCTION_TRIGGER']); $this->assertEquals('Dart', $output['APPWRITE_FUNCTION_RUNTIME_NAME']); @@ -1362,7 +1357,7 @@ class FunctionsCustomServerTest extends Scope $this->assertEmpty($output['APPWRITE_FUNCTION_JWT']); $this->assertEquals($this->getProject()['$id'], $output['APPWRITE_FUNCTION_PROJECT_ID']); - $executions = $this->client->call(Client::METHOD_GET, '/functions/' . $functionId . '/executions', array_merge([ + $executions = $this->client->call(Client::METHOD_GET, '/functions/'.$functionId.'/executions', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -1376,7 +1371,7 @@ class FunctionsCustomServerTest extends Scope $this->assertStringContainsString('foobar', $executions['body']['executions'][0]['response']); // Cleanup : Delete function - $response = $this->client->call(Client::METHOD_DELETE, '/functions/' . $functionId, [ + $response = $this->client->call(Client::METHOD_DELETE, '/functions/'.$functionId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], 'x-appwrite-key' => $this->getProject()['apiKey'], @@ -1390,7 +1385,7 @@ class FunctionsCustomServerTest extends Scope { $name = 'ruby-3.1'; $folder = 'ruby'; - $code = realpath(__DIR__ . '/../../../resources/functions') . "/$folder/code.tar.gz"; + $code = realpath(__DIR__.'/../../../resources/functions')."/$folder/code.tar.gz"; $this->packageCode($folder); $entrypoint = 'main.rb'; @@ -1401,7 +1396,7 @@ class FunctionsCustomServerTest extends Scope 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'functionId' => ID::unique(), - 'name' => 'Test ' . $name, + 'name' => 'Test '.$name, 'runtime' => $name, 'events' => [], 'schedule' => '', @@ -1413,7 +1408,7 @@ class FunctionsCustomServerTest extends Scope $this->assertEquals(201, $function['headers']['status-code']); /** Create Variables */ - $variable = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/variables', array_merge([ + $variable = $this->client->call(Client::METHOD_POST, '/functions/'.$functionId.'/variables', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1423,7 +1418,7 @@ class FunctionsCustomServerTest extends Scope $this->assertEquals(201, $variable['headers']['status-code']); - $deployment = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/deployments', array_merge([ + $deployment = $this->client->call(Client::METHOD_POST, '/functions/'.$functionId.'/deployments', array_merge([ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1438,12 +1433,12 @@ class FunctionsCustomServerTest extends Scope // Allow build step to run sleep(60); - $execution = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/executions', array_merge([ + $execution = $this->client->call(Client::METHOD_POST, '/functions/'.$functionId.'/executions', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'data' => 'foobar', - 'async' => true + 'async' => true, ]); $executionId = $execution['body']['$id'] ?? ''; @@ -1454,7 +1449,7 @@ class FunctionsCustomServerTest extends Scope sleep(20); - $executions = $this->client->call(Client::METHOD_GET, '/functions/' . $functionId . '/executions/' . $executionId, array_merge([ + $executions = $this->client->call(Client::METHOD_GET, '/functions/'.$functionId.'/executions/'.$executionId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -1464,7 +1459,7 @@ class FunctionsCustomServerTest extends Scope $this->assertEquals(200, $executions['headers']['status-code']); $this->assertEquals('completed', $executions['body']['status']); $this->assertEquals($functionId, $output['APPWRITE_FUNCTION_ID']); - $this->assertEquals('Test ' . $name, $output['APPWRITE_FUNCTION_NAME']); + $this->assertEquals('Test '.$name, $output['APPWRITE_FUNCTION_NAME']); $this->assertEquals($deploymentId, $output['APPWRITE_FUNCTION_DEPLOYMENT']); $this->assertEquals('http', $output['APPWRITE_FUNCTION_TRIGGER']); $this->assertEquals('Ruby', $output['APPWRITE_FUNCTION_RUNTIME_NAME']); @@ -1476,7 +1471,7 @@ class FunctionsCustomServerTest extends Scope $this->assertEmpty($output['APPWRITE_FUNCTION_JWT']); $this->assertEquals($this->getProject()['$id'], $output['APPWRITE_FUNCTION_PROJECT_ID']); - $executions = $this->client->call(Client::METHOD_GET, '/functions/' . $functionId . '/executions', array_merge([ + $executions = $this->client->call(Client::METHOD_GET, '/functions/'.$functionId.'/executions', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -1490,7 +1485,7 @@ class FunctionsCustomServerTest extends Scope $this->assertStringContainsString('foobar', $executions['body']['executions'][0]['response']); // Cleanup : Delete function - $response = $this->client->call(Client::METHOD_DELETE, '/functions/' . $functionId, [ + $response = $this->client->call(Client::METHOD_DELETE, '/functions/'.$functionId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], 'x-appwrite-key' => $this->getProject()['apiKey'], diff --git a/tests/e2e/Services/GraphQL/AbuseTest.php b/tests/e2e/Services/GraphQL/AbuseTest.php index 48ee64d141..163f695811 100644 --- a/tests/e2e/Services/GraphQL/AbuseTest.php +++ b/tests/e2e/Services/GraphQL/AbuseTest.php @@ -92,7 +92,7 @@ class AbuseTest extends Scope $max = App::getEnv('_APP_GRAPHQL_MAX_QUERY_COMPLEXITY', 250); - $this->assertEquals('Max query complexity should be ' . $max . ' but got 259.', $response['body']['errors'][0]['message']); + $this->assertEquals('Max query complexity should be '.$max.' but got 259.', $response['body']['errors'][0]['message']); } public function testTooManyQueriesBlocked() @@ -122,7 +122,7 @@ class AbuseTest extends Scope 'variables' => [ 'databaseId' => 'actors', 'name' => 'AbuseDatabase', - ] + ], ]; $response = $this->client->call(Client::METHOD_POST, '/graphql', [ @@ -145,7 +145,7 @@ class AbuseTest extends Scope Permission::read(Role::any()), Permission::write(Role::any()), ], - ] + ], ]; $response = $this->client->call(Client::METHOD_POST, '/graphql', [ @@ -165,7 +165,7 @@ class AbuseTest extends Scope 'key' => 'name', 'size' => 256, 'required' => true, - ] + ], ]; $this->client->call(Client::METHOD_POST, '/graphql', [ diff --git a/tests/e2e/Services/GraphQL/AccountTest.php b/tests/e2e/Services/GraphQL/AccountTest.php index 7fd70b5015..c77773cba9 100644 --- a/tests/e2e/Services/GraphQL/AccountTest.php +++ b/tests/e2e/Services/GraphQL/AccountTest.php @@ -18,7 +18,7 @@ class AccountTest extends Scope { $projectId = $this->getProject()['$id']; $query = $this->getQuery(self::$CREATE_ACCOUNT); - $email = 'test' . \rand() . '@test.com'; + $email = 'test'.\rand().'@test.com'; $graphQLPayload = [ 'query' => $query, 'variables' => [ @@ -51,7 +51,7 @@ class AccountTest extends Scope 'variables' => [ 'email' => $this->getUser()['email'], 'password' => 'password', - ] + ], ]; $session = $this->client->call(Client::METHOD_POST, '/graphql', [ @@ -63,7 +63,7 @@ class AccountTest extends Scope $this->assertIsArray($session['body']['data']); $this->assertIsArray($session['body']['data']['accountCreateEmailSession']); - $cookie = $this->client->parseCookie((string)$session['headers']['set-cookie'])['a_session_' . $this->getProject()['$id']]; + $cookie = $this->client->parseCookie((string) $session['headers']['set-cookie'])['a_session_'.$this->getProject()['$id']]; $this->assertNotEmpty($cookie); } @@ -71,13 +71,13 @@ class AccountTest extends Scope { $projectId = $this->getProject()['$id']; $query = $this->getQuery(self::$CREATE_MAGIC_URL); - $email = 'test' . \rand() . '@test.com'; + $email = 'test'.\rand().'@test.com'; $graphQLPayload = [ 'query' => $query, 'variables' => [ 'userId' => ID::unique(), 'email' => $email, - ] + ], ]; $session = $this->client->call(Client::METHOD_POST, '/graphql', [ @@ -99,7 +99,7 @@ class AccountTest extends Scope $graphQLPayload = [ 'query' => $query, 'variables' => [ - 'url' => 'http://localhost/verification' + 'url' => 'http://localhost/verification', ], ]; @@ -117,7 +117,9 @@ class AccountTest extends Scope /** * @depends testUpdateAccountPhone + * * @return array + * * @throws \Exception */ public function testCreatePhoneVerification(): array @@ -274,7 +276,7 @@ class AccountTest extends Scope 'query' => $query, 'variables' => [ 'sessionId' => 'current', - ] + ], ]; $session = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -317,8 +319,8 @@ class AccountTest extends Scope $graphQLPayload = [ 'query' => $query, 'variables' => [ - 'name' => 'Tester Updated' - ] + 'name' => 'Tester Updated', + ], ]; $account = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -343,7 +345,7 @@ class AccountTest extends Scope 'variables' => [ 'email' => 'newemail@appwrite.io', 'password' => 'password', - ] + ], ]; $account = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -368,7 +370,7 @@ class AccountTest extends Scope 'variables' => [ 'oldPassword' => 'password', 'password' => 'password', - ] + ], ]; $account = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -392,7 +394,7 @@ class AccountTest extends Scope 'variables' => [ 'phone' => '+123456789', 'password' => 'password', - ] + ], ]; $account = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -440,9 +442,9 @@ class AccountTest extends Scope 'query' => $query, 'variables' => [ 'prefs' => [ - 'key' => 'value' - ] - ] + 'key' => 'value', + ], + ], ]; $account = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -463,7 +465,7 @@ class AccountTest extends Scope $projectId = $this->getProject()['$id']; $query = $this->getQuery(self::$DELETE_ACCOUNT_SESSIONS); $graphQLPayload = [ - 'query' => $query + 'query' => $query, ]; $account = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -488,7 +490,7 @@ class AccountTest extends Scope 'query' => $query, 'variables' => [ 'sessionId' => 'current', - ] + ], ]; $account = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ diff --git a/tests/e2e/Services/GraphQL/AuthTest.php b/tests/e2e/Services/GraphQL/AuthTest.php index c331fb8437..63177ee3bc 100644 --- a/tests/e2e/Services/GraphQL/AuthTest.php +++ b/tests/e2e/Services/GraphQL/AuthTest.php @@ -7,8 +7,8 @@ use Tests\E2E\Scopes\ProjectCustom; use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\SideClient; use Utopia\Database\Helpers\ID; -use Utopia\Database\Helpers\Role; use Utopia\Database\Helpers\Permission; +use Utopia\Database\Helpers\Role; class AuthTest extends Scope { @@ -17,12 +17,15 @@ class AuthTest extends Scope use Base; private array $account1; + private array $account2; private string $token1; + private string $token2; private array $database; + private array $collection; public function setUp(): void @@ -32,8 +35,8 @@ class AuthTest extends Scope $projectId = $this->getProject()['$id']; $query = $this->getQuery(self::$CREATE_ACCOUNT); - $email1 = 'test' . \rand() . '@test.com'; - $email2 = 'test' . \rand() . '@test.com'; + $email1 = 'test'.\rand().'@test.com'; + $email2 = 'test'.\rand().'@test.com'; // Create account 1 $graphQLPayload = [ @@ -66,7 +69,7 @@ class AuthTest extends Scope 'variables' => [ 'email' => $email1, 'password' => 'password', - ] + ], ]; $session1 = $this->client->call(Client::METHOD_POST, '/graphql', [ 'content-type' => 'application/json', @@ -74,8 +77,8 @@ class AuthTest extends Scope ], $graphQLPayload); $this->token1 = $this->client->parseCookie( - (string)$session1['headers']['set-cookie'] - )['a_session_' . $projectId]; + (string) $session1['headers']['set-cookie'] + )['a_session_'.$projectId]; // Create session 2 $graphQLPayload['variables']['email'] = $email2; @@ -86,8 +89,8 @@ class AuthTest extends Scope ], $graphQLPayload); $this->token2 = $this->client->parseCookie( - (string)$session2['headers']['set-cookie'] - )['a_session_' . $projectId]; + (string) $session2['headers']['set-cookie'] + )['a_session_'.$projectId]; // Create database $query = $this->getQuery(self::$CREATE_DATABASE); @@ -96,7 +99,7 @@ class AuthTest extends Scope 'variables' => [ 'databaseId' => ID::unique(), 'name' => 'Actors', - ] + ], ]; $this->database = $this->client->call(Client::METHOD_POST, '/graphql', [ 'content-type' => 'application/json', @@ -115,9 +118,9 @@ class AuthTest extends Scope 'name' => 'Actors', 'documentSecurity' => true, 'permissions' => [ - Permission::create(Role::user($userId)) - ] - ] + Permission::create(Role::user($userId)), + ], + ], ]; $this->collection = $this->client->call(Client::METHOD_POST, '/graphql', [ 'content-type' => 'application/json', @@ -135,7 +138,7 @@ class AuthTest extends Scope 'key' => 'name', 'size' => 256, 'required' => true, - ] + ], ]; $this->client->call(Client::METHOD_POST, '/graphql', [ 'content-type' => 'application/json', @@ -166,13 +169,13 @@ class AuthTest extends Scope Permission::read(Role::user($userId)), Permission::update(Role::user($userId)), Permission::delete(Role::user($userId)), - ] - ] + ], + ], ]; $document = $this->client->call(Client::METHOD_POST, '/graphql', [ 'content-type' => 'application/json', 'x-appwrite-project' => $projectId, - 'cookie' => 'a_session_' . $projectId . '=' . $this->token1, + 'cookie' => 'a_session_'.$projectId.'='.$this->token1, ], $gqlPayload); // Try to read as account 1 @@ -183,12 +186,12 @@ class AuthTest extends Scope 'databaseId' => $this->database['body']['data']['databasesCreate']['_id'], 'collectionId' => $this->collection['body']['data']['databasesCreateCollection']['_id'], 'documentId' => $document['body']['data']['databasesCreateDocument']['_id'], - ] + ], ]; $document = $this->client->call(Client::METHOD_POST, '/graphql', [ 'content-type' => 'application/json', 'x-appwrite-project' => $projectId, - 'cookie' => 'a_session_' . $projectId . '=' . $this->token1, + 'cookie' => 'a_session_'.$projectId.'='.$this->token1, ], $gqlPayload); $this->assertIsArray($document['body']['data']['databasesGetDocument']); @@ -198,7 +201,7 @@ class AuthTest extends Scope $document = $this->client->call(Client::METHOD_POST, '/graphql', [ 'content-type' => 'application/json', 'x-appwrite-project' => $projectId, - 'cookie' => 'a_session_' . $projectId . '=' . $this->token2, + 'cookie' => 'a_session_'.$projectId.'='.$this->token2, ], $gqlPayload); $this->assertArrayHasKey('errors', $document['body']); @@ -226,12 +229,12 @@ class AuthTest extends Scope Permission::update(Role::user($userId)), Permission::delete(Role::user($userId)), ], - ] + ], ]; $document = $this->client->call(Client::METHOD_POST, '/graphql', [ 'content-type' => 'application/json', 'x-appwrite-project' => $projectId, - 'cookie' => 'a_session_' . $projectId . '=' . $this->token1, + 'cookie' => 'a_session_'.$projectId.'='.$this->token1, ], $gqlPayload); // Try to delete as account 1 @@ -242,12 +245,12 @@ class AuthTest extends Scope 'databaseId' => $this->database['body']['data']['databasesCreate']['_id'], 'collectionId' => $this->collection['body']['data']['databasesCreateCollection']['_id'], 'documentId' => $document['body']['data']['databasesCreateDocument']['_id'], - ] + ], ]; $document = $this->client->call(Client::METHOD_POST, '/graphql', [ 'content-type' => 'application/json', 'x-appwrite-project' => $projectId, - 'cookie' => 'a_session_' . $projectId . '=' . $this->token1, + 'cookie' => 'a_session_'.$projectId.'='.$this->token1, ], $gqlPayload); $this->assertIsNotArray($document['body']); diff --git a/tests/e2e/Services/GraphQL/Base.php b/tests/e2e/Services/GraphQL/Base.php index ef474f1059..03a88e9f53 100644 --- a/tests/e2e/Services/GraphQL/Base.php +++ b/tests/e2e/Services/GraphQL/Base.php @@ -6,179 +6,316 @@ trait Base { // Databases public static string $CREATE_DATABASE = 'create_database'; + public static string $GET_DATABASES = 'get_databases'; + public static string $GET_DATABASE = 'get_database'; + public static string $UPDATE_DATABASE = 'update_database'; + public static string $DELETE_DATABASE = 'delete_database'; + // Collections public static string $CREATE_COLLECTION = 'create_collection'; + public static string $GET_COLLECTION = 'get_collection'; + public static string $GET_COLLECTIONS = 'list_collections'; + public static string $UPDATE_COLLECTION = 'update_collection'; + public static string $DELETE_COLLECTION = 'delete_collection'; + // Attributes public static string $CREATE_STRING_ATTRIBUTE = 'create_string_attribute'; + public static string $CREATE_INTEGER_ATTRIBUTE = 'create_integer_attribute'; + public static string $CREATE_FLOAT_ATTRIBUTE = 'create_float_attribute'; + public static string $CREATE_BOOLEAN_ATTRIBUTE = 'create_boolean_attribute'; + public static string $CREATE_URL_ATTRIBUTE = 'create_url_attribute'; + public static string $CREATE_EMAIL_ATTRIBUTE = 'create_email_attribute'; + public static string $CREATE_IP_ATTRIBUTE = 'create_ip_attribute'; + public static string $CREATE_ENUM_ATTRIBUTE = 'create_enum_attribute'; + public static string $CREATE_DATETIME_ATTRIBUTE = 'create_datetime_attribute'; + public static string $GET_ATTRIBUTES = 'get_attributes'; + public static string $GET_ATTRIBUTE = 'get_attribute'; + public static string $DELETE_ATTRIBUTE = 'delete_attribute'; + // Indexes public static string $CREATE_INDEX = 'create_index'; + public static string $GET_INDEXES = 'get_indexes'; + public static string $GET_INDEX = 'get_index'; + public static string $DELETE_INDEX = 'delete_index'; + // Documents public static string $CREATE_DOCUMENT = 'create_document_rest'; + public static string $GET_DOCUMENTS = 'list_documents'; + public static string $GET_DOCUMENT = 'get_document'; + public static string $UPDATE_DOCUMENT = 'update_document'; + public static string $DELETE_DOCUMENT = 'delete_document'; // Custom Entities public static string $CREATE_CUSTOM_ENTITY = 'create_custom_entity'; + public static string $GET_CUSTOM_ENTITIES = 'get_custom_entities'; + public static string $GET_CUSTOM_ENTITY = 'get_custom_entity'; + public static string $UPDATE_CUSTOM_ENTITY = 'update_custom_entity'; + public static string $DELETE_CUSTOM_ENTITY = 'delete_custom_entity'; // Account public static string $CREATE_ACCOUNT = 'create_account'; + public static string $CREATE_ACCOUNT_SESSION = 'create_account_session'; + public static string $CREATE_ANONYMOUS_SESSION = 'create_anonymous_session'; + public static string $CREATE_ACCOUNT_JWT = 'create_account_jwt'; + public static string $CREATE_MAGIC_URL = 'create_magic_url'; + public static string $CREATE_PASSWORD_RECOVERY = 'create_password_recovery'; + public static string $CREATE_EMAIL_VERIFICATION = 'create_email_verification'; + public static string $CREATE_PHONE_VERIFICATION = 'create_phone_verification'; + public static string $GET_ACCOUNT = 'get_account'; + public static string $GET_ACCOUNT_SESSION = 'get_account_session'; + public static string $GET_ACCOUNT_SESSIONS = 'get_account_sessions'; + public static string $GET_ACCOUNT_PREFS = 'get_account_preferences'; + public static string $GET_ACCOUNT_LOGS = 'get_account_logs'; + public static string $UPDATE_ACCOUNT_NAME = 'update_account_name'; + public static string $UPDATE_ACCOUNT_EMAIL = 'update_account_email'; + public static string $UPDATE_ACCOUNT_PASSWORD = 'update_account_password'; + public static string $UPDATE_ACCOUNT_PREFS = 'update_account_prefs'; + public static string $UPDATE_ACCOUNT_PHONE = 'update_account_phone'; + public static string $UPDATE_ACCOUNT_STATUS = 'update_account_status'; + public static string $UPDATE_MAGIC_URL = 'confirm_magic_url'; + public static string $UPDATE_PASSWORD_RECOVERY = 'confirm_password_recovery'; + public static string $UPDATE_EMAIL_VERIFICATION = 'confirm_email_verification'; + public static string $UPDATE_PHONE_VERIFICATION = 'confirm_phone_verification'; + public static string $DELETE_ACCOUNT_SESSION = 'delete_account_session'; + public static string $DELETE_ACCOUNT_SESSIONS = 'delete_account_sessions'; // Users public static string $CREATE_USER = 'create_user'; + public static string $GET_USER = 'get_user'; + public static string $GET_USERS = 'list_user'; + public static string $GET_USER_PREFERENCES = 'get_user_preferences'; + public static string $GET_USER_SESSIONS = 'get_user_sessions'; + public static string $GET_USER_MEMBERSHIPS = 'get_user_memberships'; + public static string $GET_USER_LOGS = 'get_user_logs'; + public static string $UPDATE_USER_STATUS = 'update_user_status'; + public static string $UPDATE_USER_NAME = 'update_user_name'; + public static string $UPDATE_USER_EMAIL = 'update_user_email'; + public static string $UPDATE_USER_EMAIL_VERIFICATION = 'update_email_verification'; + public static string $UPDATE_USER_PHONE_VERIFICATION = 'update_phone_verification'; + public static string $UPDATE_USER_PASSWORD = 'update_user_password'; + public static string $UPDATE_USER_PHONE = 'update_user_phone'; + public static string $UPDATE_USER_PREFS = 'update_user_prefs'; + public static string $DELETE_USER_SESSIONS = 'delete_user_sessions'; + public static string $DELETE_USER_SESSION = 'delete_user_session'; + public static string $DELETE_USER = 'delete_user'; // Teams public static string $GET_TEAM = 'get_team'; + public static string $GET_TEAMS = 'list_teams'; + public static string $CREATE_TEAM = 'create_team'; + public static string $UPDATE_TEAM = 'update_team'; + public static string $DELETE_TEAM = 'delete_team'; + public static string $GET_TEAM_MEMBERSHIP = 'get_team_membership'; + public static string $GET_TEAM_MEMBERSHIPS = 'list_team_memberships'; + public static string $CREATE_TEAM_MEMBERSHIP = 'create_team_membership'; + public static string $UPDATE_TEAM_MEMBERSHIP_ROLES = 'update_team_membership_roles'; + public static string $UPDATE_TEAM_MEMBERSHIP_STATUS = 'update_membership_status'; + public static string $DELETE_TEAM_MEMBERSHIP = 'delete_team_membership'; // Functions public static string $CREATE_FUNCTION = 'create_function'; + public static string $GET_FUNCTIONS = 'list_functions'; + public static string $GET_FUNCTION = 'get_function'; + public static string $GET_RUNTIMES = 'list_runtimes'; + public static string $UPDATE_FUNCTION = 'update_function'; + public static string $DELETE_FUNCTION = 'delete_function'; + // Variables public static string $CREATE_VARIABLE = 'create_variable'; + public static string $GET_VARIABLES = 'list_variables'; + public static string $GET_VARIABLE = 'get_variable'; + public static string $UPDATE_VARIABLE = 'update_variable'; + public static string $DELETE_VARIABLE = 'delete_variable'; //Deployments public static string $CREATE_DEPLOYMENT = 'create_deployment'; + public static string $GET_DEPLOYMENTS = 'list_deployments'; + public static string $GET_DEPLOYMENT = 'get_deployment'; + public static string $UPDATE_DEPLOYMENT = 'update_deployment'; + public static string $DELETE_DEPLOYMENT = 'delete_deployment'; + // Executions public static string $GET_EXECUTIONS = 'list_executions'; + public static string $GET_EXECUTION = 'get_execution'; + public static string $CREATE_EXECUTION = 'create_execution'; + public static string $DELETE_EXECUTION = 'delete_execution'; + public static string $RETRY_BUILD = 'retry_build'; // Buckets public static string $CREATE_BUCKET = 'create_bucket'; + public static string $GET_BUCKETS = 'list_buckets'; + public static string $GET_BUCKET = 'get_bucket'; + public static string $UPDATE_BUCKET = 'update_bucket'; + public static string $DELETE_BUCKET = 'delete_bucket'; + // Files public static string $CREATE_FILE = 'create_file'; + public static string $GET_FILES = 'list_files'; + public static string $GET_FILE = 'get_file'; + public static string $GET_FILE_PREVIEW = 'get_file_preview'; + public static string $GET_FILE_DOWNLOAD = 'get_file_download'; + public static string $GET_FILE_VIEW = 'get_file_view'; + public static string $UPDATE_FILE = 'update_file'; + public static string $DELETE_FILE = 'delete_file'; // Health public static string $GET_HTTP_HEALTH = 'get_http_health'; + public static string $GET_DB_HEALTH = 'get_db_health'; + public static string $GET_CACHE_HEALTH = 'get_cache_health'; + public static string $GET_TIME_HEALTH = 'get_time_health'; + public static string $GET_WEBHOOKS_QUEUE_HEALTH = 'get_webhooks_queue_health'; + public static string $GET_LOGS_QUEUE_HEALTH = 'get_logs_queue_health'; + public static string $GET_CERTIFICATES_QUEUE_HEALTH = 'get_certificates_queue_health'; + public static string $GET_FUNCTION_QUEUE_HEALTH = 'get_functions_queue_health'; + public static string $GET_LOCAL_STORAGE_HEALTH = 'get_local_storage_health'; + public static string $GET_ANITVIRUS_HEALTH = 'get_antivirus_health'; // Localization public static string $GET_LOCALE = 'get_locale'; + public static string $LIST_COUNTRIES = 'list_countries'; + public static string $LIST_EU_COUNTRIES = 'list_eu_countries'; + public static string $LIST_COUNTRY_PHONE_CODES = 'list_country_phone_codes'; + public static string $LIST_CONTINENTS = 'list_continents'; + public static string $LIST_CURRENCIES = 'list_currencies'; + public static string $LIST_LANGUAGES = 'list_languages'; // Avatars public static string $GET_CREDIT_CARD_ICON = 'get_credit_card_icon'; + public static string $GET_BROWSER_ICON = 'get_browser_icon'; + public static string $GET_COUNTRY_FLAG = 'get_country_flag'; + public static string $GET_IMAGE_FROM_URL = 'get_image_from_url'; + public static string $GET_FAVICON = 'get_favicon'; + public static string $GET_QRCODE = 'get_qrcode'; + public static string $GET_USER_INITIALS = 'get_user_initials'; // Complex queries @@ -492,13 +629,13 @@ trait Base ...attributeProperties } } - }' . PHP_EOL . self::$FRAGMENT_ATTRIBUTES; + }'.PHP_EOL.self::$FRAGMENT_ATTRIBUTES; case self::$GET_ATTRIBUTE: return 'query getAttribute($databaseId: String!, $collectionId: String!, $key: String!) { databasesGetAttribute(databaseId: $databaseId, collectionId: $collectionId, key: $key) { ...attributeProperties } - }' . PHP_EOL . self::$FRAGMENT_ATTRIBUTES; + }'.PHP_EOL.self::$FRAGMENT_ATTRIBUTES; case self::$DELETE_ATTRIBUTE: return 'mutation deleteAttribute($databaseId: String!, $collectionId: String!, $key: String!) { databasesDeleteAttribute(databaseId: $databaseId, collectionId: $collectionId, key: $key) { @@ -622,7 +759,7 @@ trait Base ...options } } - }' . PHP_EOL . self::$FRAGMENT_HASH_OPTIONS; + }'.PHP_EOL.self::$FRAGMENT_HASH_OPTIONS; case self::$GET_USER_PREFERENCES: return 'query getUserPreferences($userId : String!) { usersGetPrefs(userId : $userId) { @@ -1805,7 +1942,7 @@ trait Base data } } - }' . PHP_EOL . self::$FRAGMENT_ATTRIBUTES; + }'.PHP_EOL.self::$FRAGMENT_ATTRIBUTES; } throw new \InvalidArgumentException('Invalid query type'); diff --git a/tests/e2e/Services/GraphQL/BatchTest.php b/tests/e2e/Services/GraphQL/BatchTest.php index 7082d23677..a6f1da2908 100644 --- a/tests/e2e/Services/GraphQL/BatchTest.php +++ b/tests/e2e/Services/GraphQL/BatchTest.php @@ -63,7 +63,7 @@ class BatchTest extends Scope public function testArrayBatchedMutations() { $projectId = $this->getProject()['$id']; - $email = 'tester' . \uniqid() . '@example.com'; + $email = 'tester'.\uniqid().'@example.com'; $graphQLPayload = [[ 'query' => 'mutation CreateAccount($userId: String!, $email: String!, $password: String!, $name: String) { accountCreate(userId: $userId, email: $email, password: $password, name: $name) { @@ -77,17 +77,17 @@ class BatchTest extends Scope 'name' => 'Tester 1', ], ], - [ - 'query' => 'mutation CreateTeam($teamId: String! $name: String!) { + [ + 'query' => 'mutation CreateTeam($teamId: String! $name: String!) { teamsCreate(teamId: $teamId, name: $name) { name } }', - 'variables' => [ - 'teamId' => ID::unique(), - 'name' => 'Team 1', - ], - ]]; + 'variables' => [ + 'teamId' => ID::unique(), + 'name' => 'Team 1', + ], + ], ]; $response = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ 'content-type' => 'application/json', @@ -107,8 +107,8 @@ class BatchTest extends Scope public function testArrayBatchedMutationsOfSameType() { $projectId = $this->getProject()['$id']; - $email1 = 'tester' . \uniqid() . '@example.com'; - $email2 = 'tester' . \uniqid() . '@example.com'; + $email1 = 'tester'.\uniqid().'@example.com'; + $email2 = 'tester'.\uniqid().'@example.com'; $query = 'mutation CreateAccount($userId: String!, $email: String!, $password: String!, $name: String) { accountCreate(userId: $userId, email: $email, password: $password, name: $name) { _id @@ -152,7 +152,7 @@ class BatchTest extends Scope public function testArrayBatchedMixed() { $projectId = $this->getProject()['$id']; - $email = 'tester' . \uniqid() . '@example.com'; + $email = 'tester'.\uniqid().'@example.com'; $graphQLPayload = [ ['query' => 'query { localeListCountries { total countries { code } } }'], ['query' => 'query { localeListContinents { total continents { code } } }'], @@ -167,7 +167,7 @@ class BatchTest extends Scope 'email' => $email, 'password' => 'password', 'name' => 'Tester 1', - ] + ], ], ]; $response = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -192,7 +192,7 @@ class BatchTest extends Scope public function testArrayBatchedMixedOfSameType() { $projectId = $this->getProject()['$id']; - $email = 'tester' . \uniqid() . '@example.com'; + $email = 'tester'.\uniqid().'@example.com'; $query = 'query { localeListCountries { total countries { code } } }'; $graphQLPayload = [ ['query' => $query], @@ -208,7 +208,7 @@ class BatchTest extends Scope 'email' => $email, 'password' => 'password', 'name' => 'Tester 1', - ] + ], ], ]; $response = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -281,7 +281,7 @@ class BatchTest extends Scope public function testQueryBatchedMutations() { $projectId = $this->getProject()['$id']; - $email = 'tester' . \uniqid() . '@example.com'; + $email = 'tester'.\uniqid().'@example.com'; $graphQLPayload = [ 'query' => 'mutation CreateAndLogin($userId: String!, $email: String!, $password: String!, $name: String) { accountCreate(userId: $userId, email: $email, password: $password, name: $name) { @@ -304,7 +304,6 @@ class BatchTest extends Scope 'x-appwrite-project' => $projectId, ], $this->getHeaders()), $graphQLPayload); - $this->assertIsArray($response['body']['data']); $this->assertArrayNotHasKey('errors', $response['body']); $this->assertArrayHasKey('accountCreate', $response['body']['data']); @@ -315,8 +314,8 @@ class BatchTest extends Scope public function testQueryBatchedMutationsOfSameType() { $projectId = $this->getProject()['$id']; - $email1 = 'tester' . \uniqid() . '@example.com'; - $email2 = 'tester' . \uniqid() . '@example.com'; + $email1 = 'tester'.\uniqid().'@example.com'; + $email2 = 'tester'.\uniqid().'@example.com'; $graphQLPayload = [ 'query' => 'mutation CreateAndLogin($email1: String!, $email2: String!, $password: String!, $name1: String, $name2: String) { accountCreate(userId: "unique()", email: $email1, password: $password, name: $name1) { @@ -347,8 +346,8 @@ class BatchTest extends Scope public function testQueryBatchedMutationsOfSameTypeWithAlias() { $projectId = $this->getProject()['$id']; - $email1 = 'tester' . \uniqid() . '@example.com'; - $email2 = 'tester' . \uniqid() . '@example.com'; + $email1 = 'tester'.\uniqid().'@example.com'; + $email2 = 'tester'.\uniqid().'@example.com'; $graphQLPayload = [ 'query' => 'mutation CreateAndLogin($email1: String!, $email2: String!, $password: String!, $name1: String, $name2: String) { account1: accountCreate(userId: "unique()", email: $email1, password: $password, name: $name1) { diff --git a/tests/e2e/Services/GraphQL/ContentTypeTest.php b/tests/e2e/Services/GraphQL/ContentTypeTest.php index da885a2a83..5ab950d893 100644 --- a/tests/e2e/Services/GraphQL/ContentTypeTest.php +++ b/tests/e2e/Services/GraphQL/ContentTypeTest.php @@ -115,7 +115,7 @@ class ContentTypeTest extends Scope Permission::update(Role::any()), Permission::delete(Role::any()), ], - ] + ], ]; $bucket = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ 'content-type' => 'application/json', @@ -138,12 +138,12 @@ class ContentTypeTest extends Scope Permission::update(Role::any()), Permission::delete(Role::any()), ], - ] + ], ]), 'map' => \json_encode([ - 'file' => ["variables.file"] + 'file' => ['variables.file'], ]), - 'file' => new CURLFile(realpath(__DIR__ . '/../../../resources/logo.png'), 'image/png', 'logo.png'), + 'file' => new CURLFile(realpath(__DIR__.'/../../../resources/logo.png'), 'image/png', 'logo.png'), ]; $file = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ diff --git a/tests/e2e/Services/GraphQL/DatabaseClientTest.php b/tests/e2e/Services/GraphQL/DatabaseClientTest.php index 3853a3fc17..ae3b908330 100644 --- a/tests/e2e/Services/GraphQL/DatabaseClientTest.php +++ b/tests/e2e/Services/GraphQL/DatabaseClientTest.php @@ -25,7 +25,7 @@ class DatabaseClientTest extends Scope 'variables' => [ 'databaseId' => ID::unique(), 'name' => 'Actors', - ] + ], ]; $database = $this->client->call(Client::METHOD_POST, '/graphql', [ @@ -62,7 +62,7 @@ class DatabaseClientTest extends Scope Permission::update(Role::users()), Permission::delete(Role::users()), ], - ] + ], ]; $collection = $this->client->call(Client::METHOD_POST, '/graphql', [ @@ -97,7 +97,7 @@ class DatabaseClientTest extends Scope 'key' => 'name', 'size' => 256, 'required' => true, - ] + ], ]; $attribute = $this->client->call(Client::METHOD_POST, '/graphql', [ @@ -129,7 +129,7 @@ class DatabaseClientTest extends Scope 'min' => 18, 'max' => 150, 'required' => true, - ] + ], ]; $attribute = $this->client->call(Client::METHOD_POST, '/graphql', [ @@ -170,7 +170,7 @@ class DatabaseClientTest extends Scope Permission::update(Role::any()), Permission::delete(Role::any()), ], - ] + ], ]; $document = $this->client->call(Client::METHOD_POST, '/graphql', array_merge([ @@ -193,6 +193,7 @@ class DatabaseClientTest extends Scope /** * @depends testCreateCollection + * * @throws \Exception */ public function testGetDocuments($data): void @@ -204,7 +205,7 @@ class DatabaseClientTest extends Scope 'variables' => [ 'databaseId' => $data['database']['_id'], 'collectionId' => $data['collection']['_id'], - ] + ], ]; $documents = $this->client->call(Client::METHOD_POST, '/graphql', array_merge([ @@ -219,6 +220,7 @@ class DatabaseClientTest extends Scope /** * @depends testCreateDocument + * * @throws \Exception */ public function testGetDocument($data): void @@ -231,7 +233,7 @@ class DatabaseClientTest extends Scope 'databaseId' => $data['database']['_id'], 'collectionId' => $data['collection']['_id'], 'documentId' => $data['document']['_id'], - ] + ], ]; $document = $this->client->call(Client::METHOD_POST, '/graphql', array_merge([ @@ -246,6 +248,7 @@ class DatabaseClientTest extends Scope /** * @depends testCreateDocument + * * @throws \Exception */ public function testUpdateDocument($data): void @@ -261,7 +264,7 @@ class DatabaseClientTest extends Scope 'data' => [ 'name' => 'New Document Name', ], - ] + ], ]; $document = $this->client->call(Client::METHOD_POST, '/graphql', array_merge([ @@ -279,6 +282,7 @@ class DatabaseClientTest extends Scope /** * @depends testCreateDocument + * * @throws \Exception */ public function testDeleteDocument($data): void @@ -291,7 +295,7 @@ class DatabaseClientTest extends Scope 'databaseId' => $data['database']['_id'], 'collectionId' => $data['collection']['_id'], 'documentId' => $data['document']['_id'], - ] + ], ]; $document = $this->client->call(Client::METHOD_POST, '/graphql', array_merge([ diff --git a/tests/e2e/Services/GraphQL/DatabaseServerTest.php b/tests/e2e/Services/GraphQL/DatabaseServerTest.php index bc5bca60ca..ff317a19db 100644 --- a/tests/e2e/Services/GraphQL/DatabaseServerTest.php +++ b/tests/e2e/Services/GraphQL/DatabaseServerTest.php @@ -26,7 +26,7 @@ class DatabaseServerTest extends Scope 'variables' => [ 'databaseId' => 'actors', 'name' => 'Actors', - ] + ], ]; $database = $this->client->call(Client::METHOD_POST, '/graphql', array_merge([ @@ -62,7 +62,7 @@ class DatabaseServerTest extends Scope Permission::update(Role::users()), Permission::delete(Role::users()), ], - ] + ], ]; $collection = $this->client->call(Client::METHOD_POST, '/graphql', array_merge([ @@ -83,6 +83,7 @@ class DatabaseServerTest extends Scope /** * @depends testCreateCollection + * * @throws Exception */ public function testCreateStringAttribute($data): array @@ -97,7 +98,7 @@ class DatabaseServerTest extends Scope 'key' => 'name', 'size' => 256, 'required' => true, - ] + ], ]; $attribute = $this->client->call(Client::METHOD_POST, '/graphql', array_merge([ @@ -114,6 +115,7 @@ class DatabaseServerTest extends Scope /** * @depends testCreateCollection + * * @throws Exception */ public function testCreateIntegerAttribute($data): array @@ -129,7 +131,7 @@ class DatabaseServerTest extends Scope 'min' => 18, 'max' => 150, 'required' => true, - ] + ], ]; $attribute = $this->client->call(Client::METHOD_POST, '/graphql', array_merge([ @@ -146,6 +148,7 @@ class DatabaseServerTest extends Scope /** * @depends testCreateCollection + * * @throws Exception */ public function testCreateBooleanAttribute($data): array @@ -159,7 +162,7 @@ class DatabaseServerTest extends Scope 'collectionId' => $data['collection']['_id'], 'key' => 'alive', 'required' => true, - ] + ], ]; $attribute = $this->client->call(Client::METHOD_POST, '/graphql', array_merge([ @@ -176,6 +179,7 @@ class DatabaseServerTest extends Scope /** * @depends testCreateCollection + * * @throws Exception */ public function testCreateFloatAttribute($data): array @@ -192,7 +196,7 @@ class DatabaseServerTest extends Scope 'max' => 999999.99, 'default' => 1000.0, 'required' => false, - ] + ], ]; $attribute = $this->client->call(Client::METHOD_POST, '/graphql', array_merge([ @@ -209,6 +213,7 @@ class DatabaseServerTest extends Scope /** * @depends testCreateCollection + * * @throws Exception */ public function testCreateEmailAttribute($data): array @@ -222,7 +227,7 @@ class DatabaseServerTest extends Scope 'collectionId' => $data['collection']['_id'], 'key' => 'email', 'required' => true, - ] + ], ]; $attribute = $this->client->call(Client::METHOD_POST, '/graphql', array_merge([ @@ -239,6 +244,7 @@ class DatabaseServerTest extends Scope /** * @depends testCreateCollection + * * @throws Exception */ public function testCreateEnumAttribute($data): array @@ -257,7 +263,7 @@ class DatabaseServerTest extends Scope 'guest', ], 'required' => true, - ] + ], ]; $attribute = $this->client->call(Client::METHOD_POST, '/graphql', array_merge([ @@ -274,6 +280,7 @@ class DatabaseServerTest extends Scope /** * @depends testCreateCollection + * * @throws Exception */ public function testCreateDatetimeAttribute($data): array @@ -287,7 +294,7 @@ class DatabaseServerTest extends Scope 'collectionId' => $data['collection']['_id'], 'key' => 'dob', 'required' => true, - ] + ], ]; $attribute = $this->client->call(Client::METHOD_POST, '/graphql', array_merge([ @@ -304,6 +311,7 @@ class DatabaseServerTest extends Scope /** * @depends testCreateCollection + * * @throws Exception */ public function testCreateIPAttribute($data): array @@ -318,7 +326,7 @@ class DatabaseServerTest extends Scope 'key' => 'ip', 'required' => false, 'default' => '::1', - ] + ], ]; $attribute = $this->client->call(Client::METHOD_POST, '/graphql', array_merge([ @@ -335,6 +343,7 @@ class DatabaseServerTest extends Scope /** * @depends testCreateCollection + * * @throws Exception */ public function testCreateURLAttribute($data): array @@ -349,7 +358,7 @@ class DatabaseServerTest extends Scope 'key' => 'url', 'required' => false, 'default' => 'https://appwrite.io', - ] + ], ]; $attribute = $this->client->call(Client::METHOD_POST, '/graphql', array_merge([ @@ -367,6 +376,7 @@ class DatabaseServerTest extends Scope /** * @depends testCreateStringAttribute * @depends testCreateIntegerAttribute + * * @throws Exception */ public function testCreateIndex($data): array @@ -387,7 +397,7 @@ class DatabaseServerTest extends Scope 'name', 'age', ], - ] + ], ]; $index = $this->client->call(Client::METHOD_POST, '/graphql', array_merge([ @@ -411,6 +421,7 @@ class DatabaseServerTest extends Scope * @depends testCreateIntegerAttribute * @depends testCreateBooleanAttribute * @depends testCreateEnumAttribute + * * @throws Exception */ public function testCreateDocument($data): array @@ -437,7 +448,7 @@ class DatabaseServerTest extends Scope Permission::update(Role::any()), Permission::delete(Role::any()), ], - ] + ], ]; $document = $this->client->call(Client::METHOD_POST, '/graphql', array_merge([ @@ -518,6 +529,7 @@ class DatabaseServerTest extends Scope /** * @depends testCreateDatabase + * * @throws Exception */ public function testGetDatabase($database): void @@ -528,7 +540,7 @@ class DatabaseServerTest extends Scope 'query' => $query, 'variables' => [ 'databaseId' => $database['_id'], - ] + ], ]; $database = $this->client->call(Client::METHOD_POST, '/graphql', array_merge([ @@ -543,6 +555,7 @@ class DatabaseServerTest extends Scope /** * @depends testCreateCollection + * * @throws Exception */ public function testGetCollections($data): void @@ -553,7 +566,7 @@ class DatabaseServerTest extends Scope 'query' => $query, 'variables' => [ 'databaseId' => $data['database']['_id'], - ] + ], ]; $collections = $this->client->call(Client::METHOD_POST, '/graphql', array_merge([ @@ -568,6 +581,7 @@ class DatabaseServerTest extends Scope /** * @depends testCreateCollection + * * @throws Exception */ public function testGetCollection($data): void @@ -579,7 +593,7 @@ class DatabaseServerTest extends Scope 'variables' => [ 'databaseId' => $data['database']['_id'], 'collectionId' => $data['collection']['_id'], - ] + ], ]; $collection = $this->client->call(Client::METHOD_POST, '/graphql', array_merge([ @@ -595,6 +609,7 @@ class DatabaseServerTest extends Scope /** * @depends testCreateStringAttribute * @depends testCreateIntegerAttribute + * * @throws Exception */ public function testGetAttributes($data): void @@ -606,7 +621,7 @@ class DatabaseServerTest extends Scope 'variables' => [ 'databaseId' => $data['database']['_id'], 'collectionId' => $data['collection']['_id'], - ] + ], ]; $attributes = $this->client->call(Client::METHOD_POST, '/graphql', array_merge([ @@ -621,6 +636,7 @@ class DatabaseServerTest extends Scope /** * @depends testCreateCollection + * * @throws Exception */ public function testGetAttribute($data): void @@ -633,7 +649,7 @@ class DatabaseServerTest extends Scope 'databaseId' => $data['database']['_id'], 'collectionId' => $data['collection']['_id'], 'key' => 'name', - ] + ], ]; $attribute = $this->client->call(Client::METHOD_POST, '/graphql', array_merge([ @@ -648,6 +664,7 @@ class DatabaseServerTest extends Scope /** * @depends testCreateIndex + * * @throws Exception */ public function testGetIndexes($data): void @@ -659,7 +676,7 @@ class DatabaseServerTest extends Scope 'variables' => [ 'databaseId' => $data['database']['_id'], 'collectionId' => $data['collection']['_id'], - ] + ], ]; $indices = $this->client->call(Client::METHOD_POST, '/graphql', array_merge([ @@ -674,6 +691,7 @@ class DatabaseServerTest extends Scope /** * @depends testCreateIndex + * * @throws Exception */ public function testGetIndex($data): void @@ -686,7 +704,7 @@ class DatabaseServerTest extends Scope 'databaseId' => $data['database']['_id'], 'collectionId' => $data['collection']['_id'], 'key' => $data['index']['key'], - ] + ], ]; $index = $this->client->call(Client::METHOD_POST, '/graphql', array_merge([ @@ -701,6 +719,7 @@ class DatabaseServerTest extends Scope /** * @depends testCreateCollection + * * @throws Exception */ public function testGetDocuments($data): void @@ -712,7 +731,7 @@ class DatabaseServerTest extends Scope 'variables' => [ 'databaseId' => $data['database']['_id'], 'collectionId' => $data['collection']['_id'], - ] + ], ]; $documents = $this->client->call(Client::METHOD_POST, '/graphql', array_merge([ @@ -727,6 +746,7 @@ class DatabaseServerTest extends Scope /** * @depends testCreateDocument + * * @throws Exception */ public function testGetDocument($data): void @@ -739,7 +759,7 @@ class DatabaseServerTest extends Scope 'databaseId' => $data['database']['_id'], 'collectionId' => $data['collection']['_id'], 'documentId' => $data['document']['_id'], - ] + ], ]; $document = $this->client->call(Client::METHOD_POST, '/graphql', array_merge([ @@ -801,6 +821,7 @@ class DatabaseServerTest extends Scope /** * @depends testCreateDatabase + * * @throws Exception */ public function testUpdateDatabase($database) @@ -812,7 +833,7 @@ class DatabaseServerTest extends Scope 'variables' => [ 'databaseId' => $database['_id'], 'name' => 'New Database Name', - ] + ], ]; $database = $this->client->call(Client::METHOD_POST, '/graphql', array_merge([ @@ -827,6 +848,7 @@ class DatabaseServerTest extends Scope /** * @depends testCreateCollection + * * @throws Exception */ public function testUpdateCollection($data) @@ -840,7 +862,7 @@ class DatabaseServerTest extends Scope 'collectionId' => $data['collection']['_id'], 'name' => 'New Collection Name', 'documentSecurity' => false, - ] + ], ]; $collection = $this->client->call(Client::METHOD_POST, '/graphql', array_merge([ @@ -855,6 +877,7 @@ class DatabaseServerTest extends Scope /** * @depends testCreateDocument + * * @throws Exception */ public function testUpdateDocument($data): void @@ -870,7 +893,7 @@ class DatabaseServerTest extends Scope 'data' => [ 'name' => 'New Document Name', ], - ] + ], ]; $document = $this->client->call(Client::METHOD_POST, '/graphql', array_merge([ @@ -915,6 +938,7 @@ class DatabaseServerTest extends Scope /** * @depends testCreateDocument + * * @throws Exception */ public function testDeleteDocument($data): void @@ -927,7 +951,7 @@ class DatabaseServerTest extends Scope 'databaseId' => $data['database']['_id'], 'collectionId' => $data['collection']['_id'], 'documentId' => $data['document']['_id'], - ] + ], ]; $document = $this->client->call(Client::METHOD_POST, '/graphql', array_merge([ @@ -965,6 +989,7 @@ class DatabaseServerTest extends Scope /** * @depends testCreateStringAttribute + * * @throws Exception */ public function testDeleteAttribute($data): void @@ -977,7 +1002,7 @@ class DatabaseServerTest extends Scope 'databaseId' => $data['database']['_id'], 'collectionId' => $data['collection']['_id'], 'key' => 'name', - ] + ], ]; $attribute = $this->client->call(Client::METHOD_POST, '/graphql', array_merge([ @@ -991,6 +1016,7 @@ class DatabaseServerTest extends Scope /** * @depends testCreateCollection + * * @throws Exception */ public function testDeleteCollection($data) @@ -1002,7 +1028,7 @@ class DatabaseServerTest extends Scope 'variables' => [ 'databaseId' => $data['database']['_id'], 'collectionId' => $data['collection']['_id'], - ] + ], ]; $collection = $this->client->call(Client::METHOD_POST, '/graphql', array_merge([ @@ -1016,6 +1042,7 @@ class DatabaseServerTest extends Scope /** * @depends testCreateDatabase + * * @throws Exception */ public function testDeleteDatabase($database) @@ -1026,7 +1053,7 @@ class DatabaseServerTest extends Scope 'query' => $query, 'variables' => [ 'databaseId' => $database['_id'], - ] + ], ]; $database = $this->client->call(Client::METHOD_POST, '/graphql', array_merge([ diff --git a/tests/e2e/Services/GraphQL/FunctionsClientTest.php b/tests/e2e/Services/GraphQL/FunctionsClientTest.php index d5b50250d4..97cbfa9206 100644 --- a/tests/e2e/Services/GraphQL/FunctionsClientTest.php +++ b/tests/e2e/Services/GraphQL/FunctionsClientTest.php @@ -27,7 +27,7 @@ class FunctionsClientTest extends Scope 'name' => 'Test Function', 'runtime' => 'php-8.0', 'execute' => [Role::any()->toString()], - ] + ], ]; $function = $this->client->call(Client::METHOD_POST, '/graphql', [ @@ -36,7 +36,6 @@ class FunctionsClientTest extends Scope 'x-appwrite-key' => $this->getProject()['apiKey'], ], $gqlPayload); - $this->assertIsArray($function['body']['data']); $this->assertArrayNotHasKey('errors', $function['body']); @@ -57,7 +56,7 @@ class FunctionsClientTest extends Scope 'query' => $query, 'variables' => [ 'functionId' => $functionId, - ] + ], ]; $variables = $this->client->call(Client::METHOD_POST, '/graphql', [ @@ -74,15 +73,17 @@ class FunctionsClientTest extends Scope /** * @depends testCreateFunction + * * @param $function * @return array + * * @throws \Exception */ public function testCreateDeployment($function): array { $projectId = $this->getProject()['$id']; $query = $this->getQuery(self::$CREATE_DEPLOYMENT); - $code = realpath(__DIR__ . '/../../../resources/functions') . "/php/code.tar.gz"; + $code = realpath(__DIR__.'/../../../resources/functions').'/php/code.tar.gz'; $gqlPayload = [ 'operations' => \json_encode([ 'query' => $query, @@ -91,10 +92,10 @@ class FunctionsClientTest extends Scope 'entrypoint' => 'index.php', 'activate' => true, 'code' => null, - ] + ], ]), 'map' => \json_encode([ - 'code' => ["variables.code"] + 'code' => ['variables.code'], ]), 'code' => new CURLFile($code, 'application/gzip', 'code.tar.gz'), ]; @@ -116,9 +117,11 @@ class FunctionsClientTest extends Scope /** * @depends testCreateFunction * @depends testCreateDeployment + * * @param $function * @param $deployment * @return array + * * @throws \Exception */ public function testCreateExecution($function, $deployment): array @@ -129,7 +132,7 @@ class FunctionsClientTest extends Scope 'query' => $query, 'variables' => [ 'functionId' => $function['_id'], - ] + ], ]; $execution = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -139,13 +142,16 @@ class FunctionsClientTest extends Scope $this->assertIsArray($execution['body']['data']); $this->assertArrayNotHasKey('errors', $execution['body']); + return $execution['body']['data']['functionsCreateExecution']; } /** * @depends testCreateFunction + * * @param $function * @return array + * * @throws \Exception */ public function testGetExecutions($function): array @@ -156,7 +162,7 @@ class FunctionsClientTest extends Scope 'query' => $query, 'variables' => [ 'functionId' => $function['_id'], - ] + ], ]; $executions = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -175,9 +181,11 @@ class FunctionsClientTest extends Scope /** * @depends testCreateFunction * @depends testCreateExecution + * * @param $function * @param $execution * @return array + * * @throws \Exception */ public function testGetExecution($function, $execution): array @@ -189,7 +197,7 @@ class FunctionsClientTest extends Scope 'variables' => [ 'functionId' => $function['_id'], 'executionId' => $execution['_id'], - ] + ], ]; $execution = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ diff --git a/tests/e2e/Services/GraphQL/FunctionsServerTest.php b/tests/e2e/Services/GraphQL/FunctionsServerTest.php index 75aa0d5d04..2771505ba7 100644 --- a/tests/e2e/Services/GraphQL/FunctionsServerTest.php +++ b/tests/e2e/Services/GraphQL/FunctionsServerTest.php @@ -27,7 +27,7 @@ class FunctionsServerTest extends Scope 'name' => 'Test Function', 'runtime' => 'php-8.0', 'execute' => [Role::any()->toString()], - ] + ], ]; $function = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -55,7 +55,7 @@ class FunctionsServerTest extends Scope 'query' => $query, 'variables' => [ 'functionId' => $functionId, - ] + ], ]; $variables = $this->client->call(Client::METHOD_POST, '/graphql', [ @@ -72,15 +72,17 @@ class FunctionsServerTest extends Scope /** * @depends testCreateFunction + * * @param $function * @return array + * * @throws \Exception */ public function testCreateDeployment($function): array { $projectId = $this->getProject()['$id']; $query = $this->getQuery(self::$CREATE_DEPLOYMENT); - $code = realpath(__DIR__ . '/../../../resources/functions') . "/php/code.tar.gz"; + $code = realpath(__DIR__.'/../../../resources/functions').'/php/code.tar.gz'; $gqlPayload = [ 'operations' => \json_encode([ 'query' => $query, @@ -89,10 +91,10 @@ class FunctionsServerTest extends Scope 'entrypoint' => 'index.php', 'activate' => true, 'code' => null, - ] + ], ]), 'map' => \json_encode([ - 'code' => ["variables.code"] + 'code' => ['variables.code'], ]), 'code' => new CURLFile($code, 'application/gzip', 'code.tar.gz'), ]; @@ -113,8 +115,10 @@ class FunctionsServerTest extends Scope /** * * @depends testCreateFunction * @depends testCreateDeployment + * * @param $function * @return array + * * @throws \Exception */ public function testCreateExecution($function): array @@ -125,7 +129,7 @@ class FunctionsServerTest extends Scope 'query' => $query, 'variables' => [ 'functionId' => $function['_id'], - ] + ], ]; $execution = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -142,9 +146,11 @@ class FunctionsServerTest extends Scope /** * @depends testCreateFunction * @depends testGetDeployment + * * @param $function * @param $deployment * @return array + * * @throws \Exception */ public function testCreateRetryBuild($function, $deployment): void @@ -157,7 +163,7 @@ class FunctionsServerTest extends Scope 'functionId' => $function['_id'], 'deploymentId' => $deployment['_id'], 'buildId' => $deployment['buildId'], - ] + ], ]; $retryBuild = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -166,7 +172,7 @@ class FunctionsServerTest extends Scope ], $this->getHeaders()), $gqlPayload); $this->assertIsArray($retryBuild['body']['errors']); - $this->assertEquals("Build not failed", $retryBuild['body']['errors'][0]['message']); + $this->assertEquals('Build not failed', $retryBuild['body']['errors'][0]['message']); } public function testGetFunctions(): array @@ -192,8 +198,10 @@ class FunctionsServerTest extends Scope /** * @depends testCreateFunction + * * @param $function * @return array + * * @throws \Exception */ public function testGetFunction($function): array @@ -204,7 +212,7 @@ class FunctionsServerTest extends Scope 'query' => $query, 'variables' => [ 'functionId' => $function['_id'], - ] + ], ]; $function = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -243,8 +251,10 @@ class FunctionsServerTest extends Scope /** * @depends testCreateFunction + * * @param $function * @return array + * * @throws \Exception */ public function testGetDeployments($function) @@ -255,7 +265,7 @@ class FunctionsServerTest extends Scope 'query' => $query, 'variables' => [ 'functionId' => $function['_id'], - ] + ], ]; $deployments = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -274,8 +284,10 @@ class FunctionsServerTest extends Scope /** * @depends testCreateFunction * @depends testCreateDeployment + * * @param $function * @return array + * * @throws \Exception */ public function testGetDeployment($function, $deployment) @@ -287,7 +299,7 @@ class FunctionsServerTest extends Scope 'variables' => [ 'functionId' => $function['_id'], 'deploymentId' => $deployment['_id'], - ] + ], ]; $deployment = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -305,8 +317,10 @@ class FunctionsServerTest extends Scope /** * @depends testCreateFunction + * * @param $function * @return array + * * @throws \Exception */ public function testGetExecutions($function): array @@ -317,7 +331,7 @@ class FunctionsServerTest extends Scope 'query' => $query, 'variables' => [ 'functionId' => $function['_id'], - ] + ], ]; $executions = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -336,9 +350,11 @@ class FunctionsServerTest extends Scope /** * @depends testCreateFunction * @depends testCreateExecution + * * @param $function * @param $execution * @return array + * * @throws \Exception */ public function testGetExecution($function, $execution): array @@ -350,7 +366,7 @@ class FunctionsServerTest extends Scope 'variables' => [ 'functionId' => $function['_id'], 'executionId' => $execution['_id'], - ] + ], ]; $execution = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -368,8 +384,10 @@ class FunctionsServerTest extends Scope /** * @depends testCreateFunction + * * @param $function * @return array + * * @throws \Exception */ public function testUpdateFunction($function): array @@ -386,7 +404,7 @@ class FunctionsServerTest extends Scope 'name' => 'John Doe', 'age' => 42, ], - ] + ], ]; $function = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -405,8 +423,10 @@ class FunctionsServerTest extends Scope /** * @depends testCreateFunction * @depends testCreateDeployment + * * @param $function * @param $deployment + * * @throws \Exception */ public function testDeleteDeployment($function, $deployment): void @@ -418,7 +438,7 @@ class FunctionsServerTest extends Scope 'variables' => [ 'functionId' => $function['_id'], 'deploymentId' => $deployment['_id'], - ] + ], ]; $response = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -433,7 +453,9 @@ class FunctionsServerTest extends Scope /** * @depends testCreateFunction * @depends testDeleteDeployment + * * @param $function + * * @throws \Exception */ public function testDeleteFunction($function): void @@ -444,7 +466,7 @@ class FunctionsServerTest extends Scope 'query' => $query, 'variables' => [ 'functionId' => $function['_id'], - ] + ], ]; $response = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ diff --git a/tests/e2e/Services/GraphQL/LocalizationTest.php b/tests/e2e/Services/GraphQL/LocalizationTest.php index 38200911c8..2fe76a6f06 100644 --- a/tests/e2e/Services/GraphQL/LocalizationTest.php +++ b/tests/e2e/Services/GraphQL/LocalizationTest.php @@ -18,7 +18,7 @@ class LocalizationTest extends Scope $projectId = $this->getProject()['$id']; $query = \urlencode($this->getQuery(self::$GET_LOCALE)); - $locale = $this->client->call(Client::METHOD_GET, '/graphql?query=' . $query, \array_merge([ + $locale = $this->client->call(Client::METHOD_GET, '/graphql?query='.$query, \array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $projectId, ], $this->getHeaders())); diff --git a/tests/e2e/Services/GraphQL/ScopeTest.php b/tests/e2e/Services/GraphQL/ScopeTest.php index a8b5b7cea4..44122887da 100644 --- a/tests/e2e/Services/GraphQL/ScopeTest.php +++ b/tests/e2e/Services/GraphQL/ScopeTest.php @@ -5,7 +5,6 @@ namespace Tests\E2E\Services\GraphQL; use Tests\E2E\Client; use Tests\E2E\Scopes\ProjectCustom; use Tests\E2E\Scopes\Scope; -use Tests\E2E\Scopes\SideClient; use Tests\E2E\Scopes\SideServer; use Utopia\Database\Helpers\ID; @@ -25,7 +24,7 @@ class ScopeTest extends Scope 'variables' => [ 'databaseId' => ID::unique(), 'name' => 'Actors', - ] + ], ]; $database = $this->client->call(Client::METHOD_POST, '/graphql', [ @@ -49,7 +48,7 @@ class ScopeTest extends Scope 'variables' => [ 'databaseId' => ID::unique(), 'name' => 'Actors', - ] + ], ]; $database = $this->client->call(Client::METHOD_POST, '/graphql', [ diff --git a/tests/e2e/Services/GraphQL/StorageClientTest.php b/tests/e2e/Services/GraphQL/StorageClientTest.php index 9896598c2d..90cfaef7d5 100644 --- a/tests/e2e/Services/GraphQL/StorageClientTest.php +++ b/tests/e2e/Services/GraphQL/StorageClientTest.php @@ -33,7 +33,7 @@ class StorageClientTest extends Scope Permission::update(Role::any()), Permission::delete(Role::any()), ], - ] + ], ]; $bucket = $this->client->call(Client::METHOD_POST, '/graphql', [ @@ -70,12 +70,12 @@ class StorageClientTest extends Scope Permission::update(Role::any()), Permission::delete(Role::any()), ], - ] + ], ]), 'map' => \json_encode([ - '0' => ["variables.file"] + '0' => ['variables.file'], ]), - '0' => new CURLFile(realpath(__DIR__ . '/../../../resources/logo.png'), 'image/png', 'logo.png'), + '0' => new CURLFile(realpath(__DIR__.'/../../../resources/logo.png'), 'image/png', 'logo.png'), ]; $file = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -91,8 +91,10 @@ class StorageClientTest extends Scope /** * @depends testCreateBucket + * * @param $bucket * @return array + * * @throws \Exception */ public function testGetFiles($bucket): array @@ -103,7 +105,7 @@ class StorageClientTest extends Scope 'query' => $query, 'variables' => [ 'bucketId' => $bucket['_id'], - ] + ], ]; $files = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -122,9 +124,11 @@ class StorageClientTest extends Scope /** * @depends testCreateBucket * @depends testCreateFile + * * @param $bucket * @param $file * @return array + * * @throws \Exception */ public function testGetFile($bucket, $file) @@ -136,7 +140,7 @@ class StorageClientTest extends Scope 'variables' => [ 'bucketId' => $bucket['_id'], 'fileId' => $file['_id'], - ] + ], ]; $file = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -152,8 +156,10 @@ class StorageClientTest extends Scope /** * @depends testCreateFile + * * @param $file * @return array + * * @throws \Exception */ public function testGetFilePreview($file) @@ -167,7 +173,7 @@ class StorageClientTest extends Scope 'fileId' => $file['_id'], 'width' => 100, 'height' => 100, - ] + ], ]; $file = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -182,8 +188,10 @@ class StorageClientTest extends Scope /** * @depends testCreateFile + * * @param $file * @return array + * * @throws \Exception */ public function testGetFileDownload($file) @@ -195,7 +203,7 @@ class StorageClientTest extends Scope 'variables' => [ 'bucketId' => $file['bucketId'], 'fileId' => $file['_id'], - ] + ], ]; $file = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -208,8 +216,10 @@ class StorageClientTest extends Scope /** * @depends testCreateFile + * * @param $file * @return array + * * @throws \Exception */ public function testGetFileView($file): void @@ -221,7 +231,7 @@ class StorageClientTest extends Scope 'variables' => [ 'bucketId' => $file['bucketId'], 'fileId' => $file['_id'], - ] + ], ]; $file = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -234,8 +244,10 @@ class StorageClientTest extends Scope /** * @depends testCreateFile + * * @param $file * @return array + * * @throws \Exception */ public function testUpdateFile($file): array @@ -252,7 +264,7 @@ class StorageClientTest extends Scope Permission::update(Role::any()), Permission::delete(Role::any()), ], - ] + ], ]; $file = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -270,7 +282,9 @@ class StorageClientTest extends Scope /** * @depends testCreateFile + * * @param $file + * * @throws \Exception */ public function testDeleteFile($file): void @@ -282,7 +296,7 @@ class StorageClientTest extends Scope 'variables' => [ 'bucketId' => $file['bucketId'], 'fileId' => $file['_id'], - ] + ], ]; $file = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ diff --git a/tests/e2e/Services/GraphQL/StorageServerTest.php b/tests/e2e/Services/GraphQL/StorageServerTest.php index afaef08321..29f7fad033 100644 --- a/tests/e2e/Services/GraphQL/StorageServerTest.php +++ b/tests/e2e/Services/GraphQL/StorageServerTest.php @@ -33,7 +33,7 @@ class StorageServerTest extends Scope Permission::update(Role::any()), Permission::delete(Role::any()), ], - ] + ], ]; $bucket = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -69,12 +69,12 @@ class StorageServerTest extends Scope Permission::update(Role::any()), Permission::delete(Role::any()), ], - ] + ], ]), 'map' => \json_encode([ - 'file' => ["variables.file"] + 'file' => ['variables.file'], ]), - 'file' => new CURLFile(realpath(__DIR__ . '/../../../resources/logo.png'), 'image/png', 'logo.png'), + 'file' => new CURLFile(realpath(__DIR__.'/../../../resources/logo.png'), 'image/png', 'logo.png'), ]; $file = $this->client->call(Client::METHOD_POST, '/graphql/upload', \array_merge([ @@ -84,6 +84,7 @@ class StorageServerTest extends Scope $this->assertIsArray($file['body']['data']); $this->assertArrayNotHasKey('errors', $file['body']); + return $file['body']['data']['storageCreateFile']; } @@ -110,8 +111,10 @@ class StorageServerTest extends Scope /** * @depends testCreateBucket + * * @param $bucket * @return array + * * @throws \Exception */ public function testGetBucket($bucket): array @@ -122,7 +125,7 @@ class StorageServerTest extends Scope 'query' => $query, 'variables' => [ 'bucketId' => $bucket['_id'], - ] + ], ]; $bucket = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -140,8 +143,10 @@ class StorageServerTest extends Scope /** * @depends testCreateBucket + * * @param $bucket * @return array + * * @throws \Exception */ public function testGetFiles($bucket): array @@ -152,7 +157,7 @@ class StorageServerTest extends Scope 'query' => $query, 'variables' => [ 'bucketId' => $bucket['_id'], - ] + ], ]; $files = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -171,9 +176,11 @@ class StorageServerTest extends Scope /** * @depends testCreateBucket * @depends testCreateFile + * * @param $bucket * @param $file * @return array + * * @throws \Exception */ public function testGetFile($bucket, $file) @@ -185,7 +192,7 @@ class StorageServerTest extends Scope 'variables' => [ 'bucketId' => $bucket['_id'], 'fileId' => $file['_id'], - ] + ], ]; $file = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -201,8 +208,10 @@ class StorageServerTest extends Scope /** * @depends testCreateFile + * * @param $file * @return array + * * @throws \Exception */ public function testGetFilePreview($file) @@ -216,7 +225,7 @@ class StorageServerTest extends Scope 'fileId' => $file['_id'], 'width' => 100, 'height' => 100, - ] + ], ]; $file = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -231,8 +240,10 @@ class StorageServerTest extends Scope /** * @depends testCreateFile + * * @param $file * @return array + * * @throws \Exception */ public function testGetFileDownload($file) @@ -244,7 +255,7 @@ class StorageServerTest extends Scope 'variables' => [ 'bucketId' => $file['bucketId'], 'fileId' => $file['_id'], - ] + ], ]; $file = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -257,8 +268,10 @@ class StorageServerTest extends Scope /** * @depends testCreateFile + * * @param $file * @return array + * * @throws \Exception */ public function testGetFileView($file): void @@ -270,7 +283,7 @@ class StorageServerTest extends Scope 'variables' => [ 'bucketId' => $file['bucketId'], 'fileId' => $file['_id'], - ] + ], ]; $file = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -283,8 +296,10 @@ class StorageServerTest extends Scope /** * @depends testCreateBucket + * * @param $bucket * @return array + * * @throws \Exception */ public function testUpdateBucket($bucket): array @@ -297,7 +312,7 @@ class StorageServerTest extends Scope 'bucketId' => $bucket['_id'], 'name' => 'Actors Updated', 'fileSecurity' => false, - ] + ], ]; $bucket = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -315,8 +330,10 @@ class StorageServerTest extends Scope /** * @depends testCreateFile + * * @param $file * @return array + * * @throws \Exception */ public function testUpdateFile($file): array @@ -333,7 +350,7 @@ class StorageServerTest extends Scope Permission::update(Role::any()), Permission::delete(Role::any()), ], - ] + ], ]; $file = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -351,7 +368,9 @@ class StorageServerTest extends Scope /** * @depends testCreateFile + * * @param $file + * * @throws \Exception */ public function testDeleteFile($file): void @@ -363,7 +382,7 @@ class StorageServerTest extends Scope 'variables' => [ 'bucketId' => $file['bucketId'], 'fileId' => $file['_id'], - ] + ], ]; $file = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -377,8 +396,10 @@ class StorageServerTest extends Scope /** * @depends testCreateBucket + * * @param $bucket * @return array + * * @throws \Exception */ public function testDeleteBucket($bucket): void @@ -389,7 +410,7 @@ class StorageServerTest extends Scope 'query' => $query, 'variables' => [ 'bucketId' => $bucket['_id'], - ] + ], ]; $bucket = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ diff --git a/tests/e2e/Services/GraphQL/UsersTest.php b/tests/e2e/Services/GraphQL/UsersTest.php index 9bd503df0f..e965fc5899 100644 --- a/tests/e2e/Services/GraphQL/UsersTest.php +++ b/tests/e2e/Services/GraphQL/UsersTest.php @@ -7,7 +7,6 @@ use Tests\E2E\Scopes\ProjectCustom; use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\SideServer; use Utopia\Database\Helpers\ID; -use Utopia\Database\Query; class UsersTest extends Scope { @@ -27,7 +26,7 @@ class UsersTest extends Scope 'email' => $email, 'password' => 'password', 'name' => 'Project User', - ] + ], ]; $user = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -56,7 +55,7 @@ class UsersTest extends Scope 'limit(100)', 'offset(0)', ], - ] + ], ]; $users = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -78,7 +77,7 @@ class UsersTest extends Scope 'query' => $query, 'variables' => [ 'userId' => $this->getUser()['$id'], - ] + ], ]; $user = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -100,7 +99,7 @@ class UsersTest extends Scope 'query' => $query, 'variables' => [ 'userId' => $this->getUser()['$id'], - ] + ], ]; $user = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -121,7 +120,7 @@ class UsersTest extends Scope 'query' => $query, 'variables' => [ 'userId' => $this->getUser()['$id'], - ] + ], ]; $user = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -142,7 +141,7 @@ class UsersTest extends Scope 'query' => $query, 'variables' => [ 'userId' => $this->getUser()['$id'], - ] + ], ]; $user = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -163,7 +162,7 @@ class UsersTest extends Scope 'query' => $query, 'variables' => [ 'userId' => $this->getUser()['$id'], - ] + ], ]; $user = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -185,7 +184,7 @@ class UsersTest extends Scope 'variables' => [ 'userId' => $this->getUser()['$id'], 'status' => true, - ] + ], ]; $user = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -208,7 +207,7 @@ class UsersTest extends Scope 'variables' => [ 'userId' => $this->getUser()['$id'], 'emailVerification' => true, - ] + ], ]; $user = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -230,7 +229,7 @@ class UsersTest extends Scope 'variables' => [ 'userId' => $this->getUser()['$id'], 'phoneVerification' => true, - ] + ], ]; $user = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -253,7 +252,7 @@ class UsersTest extends Scope 'variables' => [ 'userId' => $this->getUser()['$id'], 'name' => 'Updated Name', - ] + ], ]; $user = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -275,7 +274,7 @@ class UsersTest extends Scope 'query' => $query, 'variables' => [ 'userId' => $this->getUser()['$id'], - 'email' => 'newemail@appwrite.io' + 'email' => 'newemail@appwrite.io', ], ]; @@ -298,7 +297,7 @@ class UsersTest extends Scope 'query' => $query, 'variables' => [ 'userId' => $this->getUser()['$id'], - 'password' => 'newpassword' + 'password' => 'newpassword', ], ]; @@ -320,7 +319,7 @@ class UsersTest extends Scope 'query' => $query, 'variables' => [ 'userId' => $this->getUser()['$id'], - 'number' => '+123456789' + 'number' => '+123456789', ], ]; @@ -344,8 +343,8 @@ class UsersTest extends Scope 'variables' => [ 'userId' => $this->getUser()['$id'], 'prefs' => [ - 'key' => 'value' - ] + 'key' => 'value', + ], ], ]; @@ -368,7 +367,7 @@ class UsersTest extends Scope 'query' => $query, 'variables' => [ 'userId' => $this->getUser()['$id'], - ] + ], ]; $user = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -392,7 +391,7 @@ class UsersTest extends Scope 'variables' => [ 'userId' => $this->getUser()['$id'], 'sessionId' => $this->getUser()['sessionId'], - ] + ], ]; $user = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ @@ -415,7 +414,7 @@ class UsersTest extends Scope 'query' => $query, 'variables' => [ 'userId' => $this->getUser()['$id'], - ] + ], ]; $user = $this->client->call(Client::METHOD_POST, '/graphql', \array_merge([ diff --git a/tests/e2e/Services/Health/HealthBase.php b/tests/e2e/Services/Health/HealthBase.php index cbd0f97668..545cbc893f 100644 --- a/tests/e2e/Services/Health/HealthBase.php +++ b/tests/e2e/Services/Health/HealthBase.php @@ -2,8 +2,6 @@ namespace Tests\E2E\Services\Health; -use Tests\E2E\Client; - trait HealthBase { } diff --git a/tests/e2e/Services/Health/HealthCustomServerTest.php b/tests/e2e/Services/Health/HealthCustomServerTest.php index 47a2268e21..d4bfa7975c 100644 --- a/tests/e2e/Services/Health/HealthCustomServerTest.php +++ b/tests/e2e/Services/Health/HealthCustomServerTest.php @@ -3,9 +3,8 @@ namespace Tests\E2E\Services\Health; use Tests\E2E\Client; -use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\ProjectCustom; -use Tests\E2E\Scopes\SideClient; +use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\SideServer; class HealthCustomServerTest extends Scope diff --git a/tests/e2e/Services/Locale/LocaleBase.php b/tests/e2e/Services/Locale/LocaleBase.php index 64b5e5f43e..a10234c5f9 100644 --- a/tests/e2e/Services/Locale/LocaleBase.php +++ b/tests/e2e/Services/Locale/LocaleBase.php @@ -100,7 +100,6 @@ trait LocaleBase $this->assertEquals($response['body']['countries'][0]['name'], 'Alemania'); $this->assertEquals($response['body']['countries'][0]['code'], 'DE'); - /** * Test for FAILURE */ @@ -162,7 +161,6 @@ trait LocaleBase $this->assertEquals($response['body']['continents'][0]['code'], 'NA'); $this->assertEquals($response['body']['continents'][0]['name'], 'América del Norte'); - /** * Test for FAILURE */ @@ -227,9 +225,9 @@ trait LocaleBase /** * Test for SUCCESS */ - $languages = require('app/config/locale/codes.php'); - $defaultCountries = require('app/config/locale/countries.php'); - $defaultContinents = require('app/config/locale/continents.php'); + $languages = require 'app/config/locale/codes.php'; + $defaultCountries = require 'app/config/locale/countries.php'; + $defaultContinents = require 'app/config/locale/continents.php'; foreach ($languages as $lang) { $response = $this->client->call(Client::METHOD_GET, '/locale/countries', [ @@ -238,12 +236,12 @@ trait LocaleBase 'x-appwrite-locale' => $lang, ]); - if (!\is_array($response['body']['countries'])) { - throw new Exception('Failed to iterate locale: ' . $lang); + if (! \is_array($response['body']['countries'])) { + throw new Exception('Failed to iterate locale: '.$lang); } foreach ($response['body']['countries'] as $i => $code) { - $this->assertContains($code['code'], $defaultCountries, $code['code'] . ' country should be removed from ' . $lang); + $this->assertContains($code['code'], $defaultCountries, $code['code'].' country should be removed from '.$lang); } // foreach (array_keys($defaultCountries) as $i => $code) { @@ -260,7 +258,7 @@ trait LocaleBase ]); foreach ($response['body']['continents'] as $i => $code) { - $this->assertContains($code['code'], $defaultContinents, $code['code'] . ' continent should be removed from ' . $lang); + $this->assertContains($code['code'], $defaultContinents, $code['code'].' continent should be removed from '.$lang); } // foreach (array_keys($defaultContinents) as $i => $code) { diff --git a/tests/e2e/Services/Locale/LocaleConsoleClientTest.php b/tests/e2e/Services/Locale/LocaleConsoleClientTest.php index 29b3150fed..c72e554df7 100644 --- a/tests/e2e/Services/Locale/LocaleConsoleClientTest.php +++ b/tests/e2e/Services/Locale/LocaleConsoleClientTest.php @@ -2,8 +2,8 @@ namespace Tests\E2E\Services\Locale; -use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\ProjectConsole; +use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\SideClient; class LocaleConsoleClientTest extends Scope diff --git a/tests/e2e/Services/Locale/LocaleCustomClientTest.php b/tests/e2e/Services/Locale/LocaleCustomClientTest.php index b28584280e..6d6108dec1 100644 --- a/tests/e2e/Services/Locale/LocaleCustomClientTest.php +++ b/tests/e2e/Services/Locale/LocaleCustomClientTest.php @@ -2,8 +2,8 @@ namespace Tests\E2E\Services\Locale; -use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\ProjectCustom; +use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\SideClient; class LocaleCustomClientTest extends Scope diff --git a/tests/e2e/Services/Locale/LocaleCustomServerTest.php b/tests/e2e/Services/Locale/LocaleCustomServerTest.php index 62d4e76802..1513f9b342 100644 --- a/tests/e2e/Services/Locale/LocaleCustomServerTest.php +++ b/tests/e2e/Services/Locale/LocaleCustomServerTest.php @@ -2,7 +2,6 @@ namespace Tests\E2E\Services\Locale; -use Tests\E2E\Client; use Tests\E2E\Scopes\ProjectCustom; use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\SideServer; diff --git a/tests/e2e/Services/Projects/ProjectsBase.php b/tests/e2e/Services/Projects/ProjectsBase.php index a9ccd73900..53d9626252 100644 --- a/tests/e2e/Services/Projects/ProjectsBase.php +++ b/tests/e2e/Services/Projects/ProjectsBase.php @@ -2,8 +2,6 @@ namespace Tests\E2E\Services\Projects; -use Tests\E2E\Client; - trait ProjectsBase { } diff --git a/tests/e2e/Services/Projects/ProjectsConsoleClientTest.php b/tests/e2e/Services/Projects/ProjectsConsoleClientTest.php index 29282fbc2b..834f13768b 100644 --- a/tests/e2e/Services/Projects/ProjectsConsoleClientTest.php +++ b/tests/e2e/Services/Projects/ProjectsConsoleClientTest.php @@ -3,12 +3,10 @@ namespace Tests\E2E\Services\Projects; use Appwrite\Auth\Auth; -use Tests\E2E\Scopes\Scope; -use Tests\E2E\Scopes\ProjectConsole; -use Tests\E2E\Scopes\SideClient; -use Tests\E2E\Services\Projects\ProjectsBase; use Tests\E2E\Client; -use Utopia\Database\Database; +use Tests\E2E\Scopes\ProjectConsole; +use Tests\E2E\Scopes\Scope; +use Tests\E2E\Scopes\SideClient; use Utopia\Database\DateTime; use Utopia\Database\Helpers\ID; @@ -82,7 +80,7 @@ class ProjectsConsoleClientTest extends Scope 'projectId' => ID::unique(), 'name' => '', 'teamId' => $team['body']['$id'], - 'region' => 'default' + 'region' => 'default', ]); $this->assertEquals(400, $response['headers']['status-code']); @@ -93,7 +91,7 @@ class ProjectsConsoleClientTest extends Scope ], $this->getHeaders()), [ 'projectId' => ID::unique(), 'name' => 'Project Test', - 'region' => 'default' + 'region' => 'default', ]); $this->assertEquals(400, $response['headers']['status-code']); @@ -111,7 +109,6 @@ class ProjectsConsoleClientTest extends Scope /** * Test for SUCCESS */ - $response = $this->client->call(Client::METHOD_GET, '/projects', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], @@ -129,7 +126,7 @@ class ProjectsConsoleClientTest extends Scope 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders(), [ - 'search' => $id + 'search' => $id, ])); $this->assertEquals($response['headers']['status-code'], 200); @@ -142,7 +139,7 @@ class ProjectsConsoleClientTest extends Scope 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders(), [ - 'search' => 'Project Test' + 'search' => 'Project Test', ])); $this->assertEquals($response['headers']['status-code'], 200); @@ -173,7 +170,7 @@ class ProjectsConsoleClientTest extends Scope 'projectId' => ID::unique(), 'name' => 'Project Test 2', 'teamId' => $team['body']['$id'], - 'region' => 'default' + 'region' => 'default', ]); $this->assertEquals(201, $response['headers']['status-code']); @@ -188,7 +185,7 @@ class ProjectsConsoleClientTest extends Scope 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'equal("teamId", "' . $team['body']['$id'] . '")' ], + 'queries' => ['equal("teamId", "'.$team['body']['$id'].'")'], ]); $this->assertEquals(200, $response['headers']['status-code']); @@ -200,7 +197,7 @@ class ProjectsConsoleClientTest extends Scope 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'limit(1)' ], + 'queries' => ['limit(1)'], ]); $this->assertEquals(200, $response['headers']['status-code']); @@ -212,7 +209,7 @@ class ProjectsConsoleClientTest extends Scope 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'offset(2)' ], + 'queries' => ['offset(2)'], ]); $this->assertEquals(200, $response['headers']['status-code']); @@ -224,7 +221,7 @@ class ProjectsConsoleClientTest extends Scope 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'equal("name", "Project Test 2")' ], + 'queries' => ['equal("name", "Project Test 2")'], ]); $this->assertEquals(200, $response['headers']['status-code']); @@ -236,7 +233,7 @@ class ProjectsConsoleClientTest extends Scope 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'orderDesc("")' ], + 'queries' => ['orderDesc("")'], ]); $this->assertEquals(200, $response['headers']['status-code']); @@ -260,7 +257,7 @@ class ProjectsConsoleClientTest extends Scope 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'cursorAfter("' . $response['body']['projects'][0]['$id'] . '")' ], + 'queries' => ['cursorAfter("'.$response['body']['projects'][0]['$id'].'")'], ]); $this->assertEquals(200, $response['headers']['status-code']); @@ -272,7 +269,7 @@ class ProjectsConsoleClientTest extends Scope 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'cursorBefore("' . $response['body']['projects'][0]['$id'] . '")' ], + 'queries' => ['cursorBefore("'.$response['body']['projects'][0]['$id'].'")'], ]); $this->assertEquals(200, $response['headers']['status-code']); @@ -287,7 +284,7 @@ class ProjectsConsoleClientTest extends Scope 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'cursorAfter("unknown")' ], + 'queries' => ['cursorAfter("unknown")'], ]); $this->assertEquals(400, $response['headers']['status-code']); @@ -305,7 +302,7 @@ class ProjectsConsoleClientTest extends Scope /** * Test for SUCCESS */ - $response = $this->client->call(Client::METHOD_GET, '/projects/' . $id, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/projects/'.$id, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -318,7 +315,6 @@ class ProjectsConsoleClientTest extends Scope /** * Test for FAILURE */ - $response = $this->client->call(Client::METHOD_GET, '/projects/empty', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], @@ -346,7 +342,7 @@ class ProjectsConsoleClientTest extends Scope /** * Test for SUCCESS */ - $response = $this->client->call(Client::METHOD_GET, '/projects/' . $id . '/usage', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/projects/'.$id.'/usage', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -367,7 +363,6 @@ class ProjectsConsoleClientTest extends Scope /** * Test for FAILURE */ - $response = $this->client->call(Client::METHOD_GET, '/projects/empty', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], @@ -395,7 +390,7 @@ class ProjectsConsoleClientTest extends Scope /** * Test for SUCCESS */ - $response = $this->client->call(Client::METHOD_PATCH, '/projects/' . $id, array_merge([ + $response = $this->client->call(Client::METHOD_PATCH, '/projects/'.$id, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -415,7 +410,6 @@ class ProjectsConsoleClientTest extends Scope /** * Test for FAILURE */ - $response = $this->client->call(Client::METHOD_POST, '/projects', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], @@ -435,7 +429,7 @@ class ProjectsConsoleClientTest extends Scope $id = $data['projectId']; // Check defaults - $response = $this->client->call(Client::METHOD_GET, '/projects/' . $id, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/projects/'.$id, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => 'console', ], $this->getHeaders())); @@ -446,8 +440,7 @@ class ProjectsConsoleClientTest extends Scope /** * Test for SUCCESS */ - - $response = $this->client->call(Client::METHOD_PATCH, '/projects/' . $id . '/auth/duration', array_merge([ + $response = $this->client->call(Client::METHOD_PATCH, '/projects/'.$id.'/auth/duration', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -470,7 +463,7 @@ class ProjectsConsoleClientTest extends Scope 'x-appwrite-project' => $projectId, ], $this->getHeaders()), [ 'userId' => 'unique()', - 'email' => 'test' . rand(0, 9999) . '@example.com', + 'email' => 'test'.rand(0, 9999).'@example.com', 'password' => 'password', 'name' => 'Test User', ]); @@ -527,7 +520,7 @@ class ProjectsConsoleClientTest extends Scope $this->assertEquals(401, $response['headers']['status-code']); // Return project back to normal - $response = $this->client->call(Client::METHOD_PATCH, '/projects/' . $id . '/auth/duration', array_merge([ + $response = $this->client->call(Client::METHOD_PATCH, '/projects/'.$id.'/auth/duration', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -538,7 +531,7 @@ class ProjectsConsoleClientTest extends Scope $projectId = $response['body']['$id']; // Check project is back to normal - $response = $this->client->call(Client::METHOD_GET, '/projects/' . $projectId, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/projects/'.$projectId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => 'console', ], $this->getHeaders())); @@ -555,27 +548,26 @@ class ProjectsConsoleClientTest extends Scope public function testUpdateProjectOAuth($data): array { $id = $data['projectId'] ?? ''; - $providers = require('app/config/providers.php'); + $providers = require 'app/config/providers.php'; /** * Test for SUCCESS */ - foreach ($providers as $key => $provider) { - $response = $this->client->call(Client::METHOD_PATCH, '/projects/' . $id . '/oauth2', array_merge([ + $response = $this->client->call(Client::METHOD_PATCH, '/projects/'.$id.'/oauth2', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'provider' => $key, - 'appId' => 'AppId-' . ucfirst($key), - 'secret' => 'Secret-' . ucfirst($key), + 'appId' => 'AppId-'.ucfirst($key), + 'secret' => 'Secret-'.ucfirst($key), ]); $this->assertEquals(200, $response['headers']['status-code']); $this->assertNotEmpty($response['body']['$id']); } - $response = $this->client->call(Client::METHOD_GET, '/projects/' . $id, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/projects/'.$id, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -588,8 +580,8 @@ class ProjectsConsoleClientTest extends Scope $asserted = false; foreach ($response['body']['providers'] as $responseProvider) { if ($responseProvider['name'] === ucfirst($key)) { - $this->assertEquals('AppId-' . ucfirst($key), $responseProvider['appId']); - $this->assertEquals('Secret-' . ucfirst($key), $responseProvider['secret']); + $this->assertEquals('AppId-'.ucfirst($key), $responseProvider['appId']); + $this->assertEquals('Secret-'.ucfirst($key), $responseProvider['secret']); $this->assertFalse($responseProvider['enabled']); $asserted = true; break; @@ -602,12 +594,12 @@ class ProjectsConsoleClientTest extends Scope // Enable providers $i = 0; foreach ($providers as $key => $provider) { - $response = $this->client->call(Client::METHOD_PATCH, '/projects/' . $id . '/oauth2', array_merge([ + $response = $this->client->call(Client::METHOD_PATCH, '/projects/'.$id.'/oauth2', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'provider' => $key, - 'enabled' => $i === 0 ? false : true // On first provider, test enabled=false + 'enabled' => $i === 0 ? false : true, // On first provider, test enabled=false ]); $this->assertEquals(200, $response['headers']['status-code']); @@ -616,7 +608,7 @@ class ProjectsConsoleClientTest extends Scope $i++; } - $response = $this->client->call(Client::METHOD_GET, '/projects/' . $id, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/projects/'.$id, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -645,8 +637,7 @@ class ProjectsConsoleClientTest extends Scope /** * Test for FAILURE */ - - $response = $this->client->call(Client::METHOD_PATCH, '/projects/' . $id . '/oauth2', array_merge([ + $response = $this->client->call(Client::METHOD_PATCH, '/projects/'.$id.'/oauth2', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -666,9 +657,9 @@ class ProjectsConsoleClientTest extends Scope public function testUpdateProjectAuthStatus($data): array { $id = $data['projectId'] ?? ''; - $auth = require('app/config/auth.php'); + $auth = require 'app/config/auth.php'; - $originalEmail = uniqid() . 'user@localhost.test'; + $originalEmail = uniqid().'user@localhost.test'; $originalPassword = 'password'; $originalName = 'User Name'; @@ -692,13 +683,13 @@ class ProjectsConsoleClientTest extends Scope 'password' => $originalPassword, ]); - $session = $this->client->parseCookie((string)$response['headers']['set-cookie'])['a_session_' . $id]; + $session = $this->client->parseCookie((string) $response['headers']['set-cookie'])['a_session_'.$id]; /** * Test for SUCCESS */ foreach ($auth as $index => $method) { - $response = $this->client->call(Client::METHOD_PATCH, '/projects/' . $id . '/auth/' . $index, array_merge([ + $response = $this->client->call(Client::METHOD_PATCH, '/projects/'.$id.'/auth/'.$index, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -708,17 +699,17 @@ class ProjectsConsoleClientTest extends Scope $this->assertEquals(200, $response['headers']['status-code']); $this->assertNotEmpty($response['body']['$id']); - $response = $this->client->call(Client::METHOD_GET, '/projects/' . $id, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/projects/'.$id, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); $this->assertEquals(200, $response['headers']['status-code']); $this->assertNotEmpty($response['body']['$id']); - $this->assertEquals(false, $response['body']['auth' . ucfirst($method['key'])]); + $this->assertEquals(false, $response['body']['auth'.ucfirst($method['key'])]); } - $email = uniqid() . 'user@localhost.test'; + $email = uniqid().'user@localhost.test'; $password = 'password'; $name = 'User Name'; @@ -741,25 +732,25 @@ class ProjectsConsoleClientTest extends Scope $response = $this->client->call(Client::METHOD_POST, '/teams', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $id, - 'cookie' => 'a_session_' . $id . '=' . $session, + 'cookie' => 'a_session_'.$id.'='.$session, ]), [ 'teamId' => ID::unique(), - 'name' => 'Arsenal' + 'name' => 'Arsenal', ]); $this->assertEquals(201, $response['headers']['status-code']); $teamUid = $response['body']['$id']; - $response = $this->client->call(Client::METHOD_POST, '/teams/' . $teamUid . '/memberships', array_merge([ + $response = $this->client->call(Client::METHOD_POST, '/teams/'.$teamUid.'/memberships', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $id, - 'cookie' => 'a_session_' . $id . '=' . $session, + 'cookie' => 'a_session_'.$id.'='.$session, ]), [ 'email' => $email, 'name' => 'Friend User', 'roles' => ['admin', 'editor'], - 'url' => 'http://localhost:5000/join-us#title' + 'url' => 'http://localhost:5000/join-us#title', ]); $this->assertEquals($response['headers']['status-code'], 501); @@ -767,7 +758,7 @@ class ProjectsConsoleClientTest extends Scope $response = $this->client->call(Client::METHOD_POST, '/account/jwt', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $id, - 'cookie' => 'a_session_' . $id . '=' . $session, + 'cookie' => 'a_session_'.$id.'='.$session, ])); $this->assertEquals($response['headers']['status-code'], 501); @@ -794,7 +785,7 @@ class ProjectsConsoleClientTest extends Scope // Cleanup foreach ($auth as $index => $method) { - $response = $this->client->call(Client::METHOD_PATCH, '/projects/' . $id . '/auth/' . $index, array_merge([ + $response = $this->client->call(Client::METHOD_PATCH, '/projects/'.$id.'/auth/'.$index, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -815,7 +806,7 @@ class ProjectsConsoleClientTest extends Scope /** * Test for SUCCESS */ - $response = $this->client->call(Client::METHOD_PATCH, '/projects/' . $id . '/auth/limit', array_merge([ + $response = $this->client->call(Client::METHOD_PATCH, '/projects/'.$id.'/auth/limit', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -825,7 +816,7 @@ class ProjectsConsoleClientTest extends Scope $this->assertEquals(200, $response['headers']['status-code']); $this->assertNotEmpty($response['body']['$id']); - $email = uniqid() . 'user@localhost.test'; + $email = uniqid().'user@localhost.test'; $password = 'password'; $name = 'User Name'; @@ -848,7 +839,7 @@ class ProjectsConsoleClientTest extends Scope /** * Test for FAILURE */ - $response = $this->client->call(Client::METHOD_PATCH, '/projects/' . $id . '/auth/limit', array_merge([ + $response = $this->client->call(Client::METHOD_PATCH, '/projects/'.$id.'/auth/limit', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -884,7 +875,7 @@ class ProjectsConsoleClientTest extends Scope /** * Test for failure */ - $response = $this->client->call(Client::METHOD_PATCH, '/projects/' . $id . '/auth/max-sessions', array_merge([ + $response = $this->client->call(Client::METHOD_PATCH, '/projects/'.$id.'/auth/max-sessions', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -896,7 +887,7 @@ class ProjectsConsoleClientTest extends Scope /** * Test for SUCCESS */ - $response = $this->client->call(Client::METHOD_PATCH, '/projects/' . $id . '/auth/max-sessions', array_merge([ + $response = $this->client->call(Client::METHOD_PATCH, '/projects/'.$id.'/auth/max-sessions', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -907,7 +898,7 @@ class ProjectsConsoleClientTest extends Scope $this->assertNotEmpty($response['body']['$id']); $this->assertEquals(1, $response['body']['authSessionsLimit']); - $email = uniqid() . 'user@localhost.test'; + $email = uniqid().'user@localhost.test'; $password = 'password'; $name = 'User Name'; @@ -939,7 +930,6 @@ class ProjectsConsoleClientTest extends Scope 'password' => $password, ]); - $this->assertEquals(201, $response['headers']['status-code']); $sessionId1 = $response['body']['$id']; @@ -955,7 +945,6 @@ class ProjectsConsoleClientTest extends Scope 'password' => $password, ]); - $this->assertEquals(201, $response['headers']['status-code']); $sessionCookie = $response['headers']['set-cookie']; $sessionId2 = $response['body']['$id']; @@ -982,7 +971,7 @@ class ProjectsConsoleClientTest extends Scope /** * Reset Limit */ - $response = $this->client->call(Client::METHOD_PATCH, '/projects/' . $id . '/auth/max-sessions', array_merge([ + $response = $this->client->call(Client::METHOD_PATCH, '/projects/'.$id.'/auth/max-sessions', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -997,7 +986,7 @@ class ProjectsConsoleClientTest extends Scope $team = $this->client->call(Client::METHOD_POST, '/teams', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_console=' . $this->getRoot()['session'], + 'cookie' => 'a_session_console='.$this->getRoot()['session'], ]), [ 'teamId' => ID::unique(), 'name' => 'Project Test', @@ -1008,34 +997,34 @@ class ProjectsConsoleClientTest extends Scope $project = $this->client->call(Client::METHOD_POST, '/projects', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_console=' . $this->getRoot()['session'], + 'cookie' => 'a_session_console='.$this->getRoot()['session'], ]), [ 'projectId' => ID::unique(), 'name' => 'Project Test', 'teamId' => $team['body']['$id'], - 'region' => 'default' + 'region' => 'default', ]); $this->assertEquals(201, $project['headers']['status-code']); $this->assertNotEmpty($project['body']['$id']); $id = $project['body']['$id']; - $services = require('app/config/services.php'); + $services = require 'app/config/services.php'; /** * Test for Disabled */ foreach ($services as $service) { - if (!$service['optional']) { + if (! $service['optional']) { continue; } $key = $service['key'] ?? ''; - $response = $this->client->call(Client::METHOD_PATCH, '/projects/' . $id . '/service', array_merge([ + $response = $this->client->call(Client::METHOD_PATCH, '/projects/'.$id.'/service', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_console=' . $this->getRoot()['session'], + 'cookie' => 'a_session_console='.$this->getRoot()['session'], ]), [ 'service' => $key, 'status' => false, @@ -1044,40 +1033,39 @@ class ProjectsConsoleClientTest extends Scope $this->assertEquals(200, $response['headers']['status-code']); $this->assertNotEmpty($response['body']['$id']); - $response = $this->client->call(Client::METHOD_GET, '/projects/' . $id, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/projects/'.$id, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_console=' . $this->getRoot()['session'], + 'cookie' => 'a_session_console='.$this->getRoot()['session'], ])); $this->assertEquals(200, $response['headers']['status-code']); $this->assertNotEmpty($response['body']['$id']); - $this->assertEquals(false, $response['body']['serviceStatusFor' . ucfirst($key)]); + $this->assertEquals(false, $response['body']['serviceStatusFor'.ucfirst($key)]); } /** * Admin request must succeed */ - $response = $this->client->call(Client::METHOD_GET, '/functions', array_merge([ 'origin' => 'http://localhost', 'content-type' => 'application/json', // 'x-appwrite-project' => $this->getProject()['$id'], 'x-appwrite-project' => $id, - 'cookie' => 'a_session_console=' . $this->getRoot()['session'], - 'x-appwrite-mode' => 'admin' + 'cookie' => 'a_session_console='.$this->getRoot()['session'], + 'x-appwrite-mode' => 'admin', ])); $this->assertEquals(200, $response['headers']['status-code']); foreach ($services as $service) { - if (!$service['optional']) { + if (! $service['optional']) { continue; } $key = $service['key'] ?? ''; - $response = $this->client->call(Client::METHOD_PATCH, '/projects/' . $id . '/service/', array_merge([ + $response = $this->client->call(Client::METHOD_PATCH, '/projects/'.$id.'/service/', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1094,22 +1082,22 @@ class ProjectsConsoleClientTest extends Scope { $id = $data['projectId']; - $services = require('app/config/services.php'); + $services = require 'app/config/services.php'; /** * Test for Disabled */ foreach ($services as $service) { - if (!$service['optional']) { + if (! $service['optional']) { continue; } $key = $service['key'] ?? ''; - $response = $this->client->call(Client::METHOD_PATCH, '/projects/' . $id . '/service', array_merge([ + $response = $this->client->call(Client::METHOD_PATCH, '/projects/'.$id.'/service', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_console=' . $this->getRoot()['session'], + 'cookie' => 'a_session_console='.$this->getRoot()['session'], ]), [ 'service' => $key, 'status' => false, @@ -1118,15 +1106,15 @@ class ProjectsConsoleClientTest extends Scope $this->assertEquals(200, $response['headers']['status-code']); $this->assertNotEmpty($response['body']['$id']); - $response = $this->client->call(Client::METHOD_GET, '/projects/' . $id, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/projects/'.$id, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_console=' . $this->getRoot()['session'], + 'cookie' => 'a_session_console='.$this->getRoot()['session'], ])); $this->assertEquals(200, $response['headers']['status-code']); $this->assertNotEmpty($response['body']['$id']); - $this->assertEquals(false, $response['body']['serviceStatusFor' . ucfirst($key)]); + $this->assertEquals(false, $response['body']['serviceStatusFor'.ucfirst($key)]); } /** @@ -1145,7 +1133,7 @@ class ProjectsConsoleClientTest extends Scope 'x-appwrite-project' => $id, ]), [ 'teamId' => ID::unique(), - 'name' => 'Arsenal' + 'name' => 'Arsenal', ]); $this->assertEquals(503, $response['headers']['status-code']); @@ -1153,7 +1141,7 @@ class ProjectsConsoleClientTest extends Scope // Cleanup foreach ($services as $service) { - $response = $this->client->call(Client::METHOD_PATCH, '/projects/' . $id . '/service/', array_merge([ + $response = $this->client->call(Client::METHOD_PATCH, '/projects/'.$id.'/service/', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1168,22 +1156,22 @@ class ProjectsConsoleClientTest extends Scope { $id = $data['projectId']; - $services = require('app/config/services.php'); + $services = require 'app/config/services.php'; /** * Test for Disabled */ foreach ($services as $service) { - if (!$service['optional']) { + if (! $service['optional']) { continue; } $key = $service['key'] ?? ''; - $response = $this->client->call(Client::METHOD_PATCH, '/projects/' . $id . '/service', array_merge([ + $response = $this->client->call(Client::METHOD_PATCH, '/projects/'.$id.'/service', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_console=' . $this->getRoot()['session'], + 'cookie' => 'a_session_console='.$this->getRoot()['session'], ]), [ 'service' => $key, 'status' => false, @@ -1192,22 +1180,22 @@ class ProjectsConsoleClientTest extends Scope $this->assertEquals(200, $response['headers']['status-code']); $this->assertNotEmpty($response['body']['$id']); - $response = $this->client->call(Client::METHOD_GET, '/projects/' . $id, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/projects/'.$id, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_console=' . $this->getRoot()['session'], + 'cookie' => 'a_session_console='.$this->getRoot()['session'], ])); $this->assertEquals(200, $response['headers']['status-code']); $this->assertNotEmpty($response['body']['$id']); - $this->assertEquals(false, $response['body']['serviceStatusFor' . ucfirst($key)]); + $this->assertEquals(false, $response['body']['serviceStatusFor'.ucfirst($key)]); } // Create API Key - $response = $this->client->call(Client::METHOD_POST, '/projects/' . $id . '/keys', array_merge([ + $response = $this->client->call(Client::METHOD_POST, '/projects/'.$id.'/keys', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_console=' . $this->getRoot()['session'], + 'cookie' => 'a_session_console='.$this->getRoot()['session'], ]), [ 'name' => 'Key Test', 'scopes' => ['functions.read', 'teams.write'], @@ -1225,7 +1213,7 @@ class ProjectsConsoleClientTest extends Scope 'content-type' => 'application/json', 'x-appwrite-project' => $id, 'x-appwrite-key' => $keySecret, - 'x-sdk-name' => 'python' + 'x-sdk-name' => 'python', ])); $this->assertEquals(200, $response['headers']['status-code']); @@ -1234,19 +1222,19 @@ class ProjectsConsoleClientTest extends Scope 'content-type' => 'application/json', 'x-appwrite-project' => $id, 'x-appwrite-key' => $keySecret, - 'x-sdk-name' => 'php' + 'x-sdk-name' => 'php', ]), [ 'teamId' => ID::unique(), - 'name' => 'Arsenal' + 'name' => 'Arsenal', ]); $this->assertEquals(201, $response['headers']['status-code']); /** Check that the API key has been updated */ - $response = $this->client->call(Client::METHOD_GET, '/projects/' . $id . '/keys/' . $keyId, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/projects/'.$id.'/keys/'.$keyId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_console=' . $this->getRoot()['session'], + 'cookie' => 'a_session_console='.$this->getRoot()['session'], ]), []); $this->assertEquals(200, $response['headers']['status-code']); @@ -1259,16 +1247,16 @@ class ProjectsConsoleClientTest extends Scope // Cleanup - $response = $this->client->call(Client::METHOD_DELETE, '/projects/' . $id . '/keys/' . $keyId, array_merge([ + $response = $this->client->call(Client::METHOD_DELETE, '/projects/'.$id.'/keys/'.$keyId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_console=' . $this->getRoot()['session'], + 'cookie' => 'a_session_console='.$this->getRoot()['session'], ]), []); $this->assertEquals(204, $response['headers']['status-code']); foreach ($services as $service) { - $response = $this->client->call(Client::METHOD_PATCH, '/projects/' . $id . '/service/', array_merge([ + $response = $this->client->call(Client::METHOD_PATCH, '/projects/'.$id.'/service/', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1285,7 +1273,7 @@ class ProjectsConsoleClientTest extends Scope { $id = $data['projectId'] ?? ''; - $response = $this->client->call(Client::METHOD_POST, '/projects/' . $id . '/webhooks', array_merge([ + $response = $this->client->call(Client::METHOD_POST, '/projects/'.$id.'/webhooks', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1312,7 +1300,7 @@ class ProjectsConsoleClientTest extends Scope /** * Test for FAILURE */ - $response = $this->client->call(Client::METHOD_POST, '/projects/' . $id . '/webhooks', array_merge([ + $response = $this->client->call(Client::METHOD_POST, '/projects/'.$id.'/webhooks', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1326,7 +1314,7 @@ class ProjectsConsoleClientTest extends Scope $this->assertEquals(400, $response['headers']['status-code']); - $response = $this->client->call(Client::METHOD_POST, '/projects/' . $id . '/webhooks', array_merge([ + $response = $this->client->call(Client::METHOD_POST, '/projects/'.$id.'/webhooks', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1347,7 +1335,7 @@ class ProjectsConsoleClientTest extends Scope { $id = $data['projectId'] ?? ''; - $response = $this->client->call(Client::METHOD_GET, '/projects/' . $id . '/webhooks', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/projects/'.$id.'/webhooks', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -1370,7 +1358,7 @@ class ProjectsConsoleClientTest extends Scope $id = $data['projectId'] ?? ''; $webhookId = $data['webhookId'] ?? ''; - $response = $this->client->call(Client::METHOD_GET, '/projects/' . $id . '/webhooks/' . $webhookId, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/projects/'.$id.'/webhooks/'.$webhookId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -1388,7 +1376,7 @@ class ProjectsConsoleClientTest extends Scope /** * Test for FAILURE */ - $response = $this->client->call(Client::METHOD_GET, '/projects/' . $id . '/webhooks/error', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/projects/'.$id.'/webhooks/error', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -1406,7 +1394,7 @@ class ProjectsConsoleClientTest extends Scope $id = $data['projectId'] ?? ''; $webhookId = $data['webhookId'] ?? ''; - $response = $this->client->call(Client::METHOD_PUT, '/projects/' . $id . '/webhooks/' . $webhookId, array_merge([ + $response = $this->client->call(Client::METHOD_PUT, '/projects/'.$id.'/webhooks/'.$webhookId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1415,7 +1403,7 @@ class ProjectsConsoleClientTest extends Scope 'url' => 'https://appwrite.io/new', 'security' => false, 'httpUser' => '', - 'httpPass' => '' + 'httpPass' => '', ]); $this->assertEquals(200, $response['headers']['status-code']); @@ -1432,7 +1420,7 @@ class ProjectsConsoleClientTest extends Scope $this->assertEquals('', $response['body']['httpUser']); $this->assertEquals('', $response['body']['httpPass']); - $response = $this->client->call(Client::METHOD_GET, '/projects/' . $id . '/webhooks/' . $webhookId, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/projects/'.$id.'/webhooks/'.$webhookId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -1454,7 +1442,7 @@ class ProjectsConsoleClientTest extends Scope /** * Test for FAILURE */ - $response = $this->client->call(Client::METHOD_PUT, '/projects/' . $id . '/webhooks/' . $webhookId, array_merge([ + $response = $this->client->call(Client::METHOD_PUT, '/projects/'.$id.'/webhooks/'.$webhookId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1468,7 +1456,7 @@ class ProjectsConsoleClientTest extends Scope $this->assertEquals(400, $response['headers']['status-code']); - $response = $this->client->call(Client::METHOD_PUT, '/projects/' . $id . '/webhooks/' . $webhookId, array_merge([ + $response = $this->client->call(Client::METHOD_PUT, '/projects/'.$id.'/webhooks/'.$webhookId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1482,7 +1470,7 @@ class ProjectsConsoleClientTest extends Scope $this->assertEquals(400, $response['headers']['status-code']); - $response = $this->client->call(Client::METHOD_PUT, '/projects/' . $id . '/webhooks/' . $webhookId, array_merge([ + $response = $this->client->call(Client::METHOD_PUT, '/projects/'.$id.'/webhooks/'.$webhookId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1505,7 +1493,7 @@ class ProjectsConsoleClientTest extends Scope $webhookId = $data['webhookId'] ?? ''; $signatureKey = $data['signatureKey'] ?? ''; - $response = $this->client->call(Client::METHOD_PATCH, '/projects/' . $id . '/webhooks/' . $webhookId . '/signature', array_merge([ + $response = $this->client->call(Client::METHOD_PATCH, '/projects/'.$id.'/webhooks/'.$webhookId.'/signature', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -1523,7 +1511,7 @@ class ProjectsConsoleClientTest extends Scope $id = $data['projectId'] ?? ''; $webhookId = $data['webhookId'] ?? ''; - $response = $this->client->call(Client::METHOD_DELETE, '/projects/' . $id . '/webhooks/' . $webhookId, array_merge([ + $response = $this->client->call(Client::METHOD_DELETE, '/projects/'.$id.'/webhooks/'.$webhookId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -1531,7 +1519,7 @@ class ProjectsConsoleClientTest extends Scope $this->assertEquals(204, $response['headers']['status-code']); $this->assertEmpty($response['body']); - $response = $this->client->call(Client::METHOD_GET, '/projects/' . $id . '/webhooks/' . $webhookId, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/projects/'.$id.'/webhooks/'.$webhookId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -1541,7 +1529,7 @@ class ProjectsConsoleClientTest extends Scope /** * Test for FAILURE */ - $response = $this->client->call(Client::METHOD_DELETE, '/projects/' . $id . '/webhooks/error', array_merge([ + $response = $this->client->call(Client::METHOD_DELETE, '/projects/'.$id.'/webhooks/error', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -1560,7 +1548,7 @@ class ProjectsConsoleClientTest extends Scope { $id = $data['projectId'] ?? ''; - $response = $this->client->call(Client::METHOD_POST, '/projects/' . $id . '/keys', array_merge([ + $response = $this->client->call(Client::METHOD_POST, '/projects/'.$id.'/keys', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1581,13 +1569,13 @@ class ProjectsConsoleClientTest extends Scope $data = array_merge($data, [ 'keyId' => $response['body']['$id'], - 'secret' => $response['body']['secret'] + 'secret' => $response['body']['secret'], ]); /** * Test for FAILURE */ - $response = $this->client->call(Client::METHOD_POST, '/projects/' . $id . '/keys', array_merge([ + $response = $this->client->call(Client::METHOD_POST, '/projects/'.$id.'/keys', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1600,7 +1588,6 @@ class ProjectsConsoleClientTest extends Scope return $data; } - /** * @depends testCreateProjectKey */ @@ -1608,12 +1595,11 @@ class ProjectsConsoleClientTest extends Scope { $id = $data['projectId'] ?? ''; - $response = $this->client->call(Client::METHOD_GET, '/projects/' . $id . '/keys', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/projects/'.$id.'/keys', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); - $this->assertEquals(200, $response['headers']['status-code']); $this->assertEquals(1, $response['body']['total']); @@ -1624,7 +1610,6 @@ class ProjectsConsoleClientTest extends Scope return $data; } - /** * @depends testCreateProjectKey */ @@ -1633,10 +1618,10 @@ class ProjectsConsoleClientTest extends Scope $id = $data['projectId'] ?? ''; $keyId = $data['keyId'] ?? ''; - $response = $this->client->call(Client::METHOD_GET, '/projects/' . $id . '/keys/' . $keyId, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/projects/'.$id.'/keys/'.$keyId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $keyId + 'x-appwrite-key' => $keyId, ], $this->getHeaders()), []); $this->assertEquals(200, $response['headers']['status-code']); @@ -1655,7 +1640,7 @@ class ProjectsConsoleClientTest extends Scope /** * Test for FAILURE */ - $response = $this->client->call(Client::METHOD_GET, '/projects/' . $id . '/keys/error', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/projects/'.$id.'/keys/error', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -1675,7 +1660,7 @@ class ProjectsConsoleClientTest extends Scope /** * Test for SUCCESS */ - $response = $this->client->call(Client::METHOD_POST, '/projects/' . $id . '/keys', array_merge([ + $response = $this->client->call(Client::METHOD_POST, '/projects/'.$id.'/keys', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1687,7 +1672,7 @@ class ProjectsConsoleClientTest extends Scope $response = $this->client->call(Client::METHOD_GET, '/health', [ 'content-type' => 'application/json', 'x-appwrite-project' => $id, - 'x-appwrite-key' => $response['body']['secret'] + 'x-appwrite-key' => $response['body']['secret'], ], []); $this->assertEquals(200, $response['headers']['status-code']); @@ -1695,7 +1680,7 @@ class ProjectsConsoleClientTest extends Scope /** * Test for SUCCESS */ - $response = $this->client->call(Client::METHOD_POST, '/projects/' . $id . '/keys', array_merge([ + $response = $this->client->call(Client::METHOD_POST, '/projects/'.$id.'/keys', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1707,7 +1692,7 @@ class ProjectsConsoleClientTest extends Scope $response = $this->client->call(Client::METHOD_GET, '/health', [ 'content-type' => 'application/json', 'x-appwrite-project' => $id, - 'x-appwrite-key' => $response['body']['secret'] + 'x-appwrite-key' => $response['body']['secret'], ], []); $this->assertEquals(200, $response['headers']['status-code']); @@ -1715,7 +1700,7 @@ class ProjectsConsoleClientTest extends Scope /** * Test for FAILURE */ - $response = $this->client->call(Client::METHOD_POST, '/projects/' . $id . '/keys', array_merge([ + $response = $this->client->call(Client::METHOD_POST, '/projects/'.$id.'/keys', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1727,13 +1712,12 @@ class ProjectsConsoleClientTest extends Scope $response = $this->client->call(Client::METHOD_GET, '/health', [ 'content-type' => 'application/json', 'x-appwrite-project' => $id, - 'x-appwrite-key' => $response['body']['secret'] + 'x-appwrite-key' => $response['body']['secret'], ], []); $this->assertEquals(401, $response['headers']['status-code']); } - /** * @depends testCreateProjectKey */ @@ -1742,7 +1726,7 @@ class ProjectsConsoleClientTest extends Scope $id = $data['projectId'] ?? ''; $keyId = $data['keyId'] ?? ''; - $response = $this->client->call(Client::METHOD_PUT, '/projects/' . $id . '/keys/' . $keyId, array_merge([ + $response = $this->client->call(Client::METHOD_PUT, '/projects/'.$id.'/keys/'.$keyId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1764,7 +1748,7 @@ class ProjectsConsoleClientTest extends Scope $this->assertArrayHasKey('accessedAt', $response['body']); $this->assertEmpty($response['body']['accessedAt']); - $response = $this->client->call(Client::METHOD_GET, '/projects/' . $id . '/keys/' . $keyId, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/projects/'.$id.'/keys/'.$keyId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -1785,7 +1769,7 @@ class ProjectsConsoleClientTest extends Scope /** * Test for FAILURE */ - $response = $this->client->call(Client::METHOD_PUT, '/projects/' . $id . '/keys/' . $keyId, array_merge([ + $response = $this->client->call(Client::METHOD_PUT, '/projects/'.$id.'/keys/'.$keyId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1806,7 +1790,7 @@ class ProjectsConsoleClientTest extends Scope $id = $data['projectId'] ?? ''; $keyId = $data['keyId'] ?? ''; - $response = $this->client->call(Client::METHOD_DELETE, '/projects/' . $id . '/keys/' . $keyId, array_merge([ + $response = $this->client->call(Client::METHOD_DELETE, '/projects/'.$id.'/keys/'.$keyId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -1814,7 +1798,7 @@ class ProjectsConsoleClientTest extends Scope $this->assertEquals(204, $response['headers']['status-code']); $this->assertEmpty($response['body']); - $response = $this->client->call(Client::METHOD_GET, '/projects/' . $id . '/keys/' . $keyId, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/projects/'.$id.'/keys/'.$keyId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -1824,7 +1808,7 @@ class ProjectsConsoleClientTest extends Scope /** * Test for FAILURE */ - $response = $this->client->call(Client::METHOD_DELETE, '/projects/' . $id . '/keys/error', array_merge([ + $response = $this->client->call(Client::METHOD_DELETE, '/projects/'.$id.'/keys/error', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -1843,7 +1827,7 @@ class ProjectsConsoleClientTest extends Scope { $id = $data['projectId'] ?? ''; - $response = $this->client->call(Client::METHOD_POST, '/projects/' . $id . '/platforms', array_merge([ + $response = $this->client->call(Client::METHOD_POST, '/projects/'.$id.'/platforms', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1864,7 +1848,7 @@ class ProjectsConsoleClientTest extends Scope $data = array_merge($data, ['platformWebId' => $response['body']['$id']]); - $response = $this->client->call(Client::METHOD_POST, '/projects/' . $id . '/platforms', array_merge([ + $response = $this->client->call(Client::METHOD_POST, '/projects/'.$id.'/platforms', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1885,7 +1869,7 @@ class ProjectsConsoleClientTest extends Scope $data = array_merge($data, ['platformFultteriOSId' => $response['body']['$id']]); - $response = $this->client->call(Client::METHOD_POST, '/projects/' . $id . '/platforms', array_merge([ + $response = $this->client->call(Client::METHOD_POST, '/projects/'.$id.'/platforms', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1906,7 +1890,7 @@ class ProjectsConsoleClientTest extends Scope $data = array_merge($data, ['platformFultterAndroidId' => $response['body']['$id']]); - $response = $this->client->call(Client::METHOD_POST, '/projects/' . $id . '/platforms', array_merge([ + $response = $this->client->call(Client::METHOD_POST, '/projects/'.$id.'/platforms', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1927,7 +1911,7 @@ class ProjectsConsoleClientTest extends Scope $data = array_merge($data, ['platformFultterWebId' => $response['body']['$id']]); - $response = $this->client->call(Client::METHOD_POST, '/projects/' . $id . '/platforms', array_merge([ + $response = $this->client->call(Client::METHOD_POST, '/projects/'.$id.'/platforms', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1948,7 +1932,7 @@ class ProjectsConsoleClientTest extends Scope $data = array_merge($data, ['platformAppleIosId' => $response['body']['$id']]); - $response = $this->client->call(Client::METHOD_POST, '/projects/' . $id . '/platforms', array_merge([ + $response = $this->client->call(Client::METHOD_POST, '/projects/'.$id.'/platforms', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1969,7 +1953,7 @@ class ProjectsConsoleClientTest extends Scope $data = array_merge($data, ['platformAppleMacOsId' => $response['body']['$id']]); - $response = $this->client->call(Client::METHOD_POST, '/projects/' . $id . '/platforms', array_merge([ + $response = $this->client->call(Client::METHOD_POST, '/projects/'.$id.'/platforms', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1990,7 +1974,7 @@ class ProjectsConsoleClientTest extends Scope $data = array_merge($data, ['platformAppleWatchOsId' => $response['body']['$id']]); - $response = $this->client->call(Client::METHOD_POST, '/projects/' . $id . '/platforms', array_merge([ + $response = $this->client->call(Client::METHOD_POST, '/projects/'.$id.'/platforms', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -2014,7 +1998,7 @@ class ProjectsConsoleClientTest extends Scope /** * Test for FAILURE */ - $response = $this->client->call(Client::METHOD_POST, '/projects/' . $id . '/platforms', array_merge([ + $response = $this->client->call(Client::METHOD_POST, '/projects/'.$id.'/platforms', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -2039,7 +2023,7 @@ class ProjectsConsoleClientTest extends Scope sleep(1); - $response = $this->client->call(Client::METHOD_GET, '/projects/' . $id . '/platforms', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/projects/'.$id.'/platforms', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -2063,7 +2047,7 @@ class ProjectsConsoleClientTest extends Scope $platformWebId = $data['platformWebId'] ?? ''; - $response = $this->client->call(Client::METHOD_GET, '/projects/' . $id . '/platforms/' . $platformWebId, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/projects/'.$id.'/platforms/'.$platformWebId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -2079,7 +2063,7 @@ class ProjectsConsoleClientTest extends Scope $platformFultteriOSId = $data['platformFultteriOSId'] ?? ''; - $response = $this->client->call(Client::METHOD_GET, '/projects/' . $id . '/platforms/' . $platformFultteriOSId, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/projects/'.$id.'/platforms/'.$platformFultteriOSId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -2095,7 +2079,7 @@ class ProjectsConsoleClientTest extends Scope $platformFultterAndroidId = $data['platformFultterAndroidId'] ?? ''; - $response = $this->client->call(Client::METHOD_GET, '/projects/' . $id . '/platforms/' . $platformFultterAndroidId, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/projects/'.$id.'/platforms/'.$platformFultterAndroidId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -2111,7 +2095,7 @@ class ProjectsConsoleClientTest extends Scope $platformFultterWebId = $data['platformFultterWebId'] ?? ''; - $response = $this->client->call(Client::METHOD_GET, '/projects/' . $id . '/platforms/' . $platformFultterWebId, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/projects/'.$id.'/platforms/'.$platformFultterWebId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -2127,7 +2111,7 @@ class ProjectsConsoleClientTest extends Scope $platformAppleIosId = $data['platformAppleIosId'] ?? ''; - $response = $this->client->call(Client::METHOD_GET, '/projects/' . $id . '/platforms/' . $platformAppleIosId, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/projects/'.$id.'/platforms/'.$platformAppleIosId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -2143,7 +2127,7 @@ class ProjectsConsoleClientTest extends Scope $platformAppleMacOsId = $data['platformAppleMacOsId'] ?? ''; - $response = $this->client->call(Client::METHOD_GET, '/projects/' . $id . '/platforms/' . $platformAppleMacOsId, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/projects/'.$id.'/platforms/'.$platformAppleMacOsId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -2159,7 +2143,7 @@ class ProjectsConsoleClientTest extends Scope $platformAppleWatchOsId = $data['platformAppleWatchOsId'] ?? ''; - $response = $this->client->call(Client::METHOD_GET, '/projects/' . $id . '/platforms/' . $platformAppleWatchOsId, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/projects/'.$id.'/platforms/'.$platformAppleWatchOsId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -2175,7 +2159,7 @@ class ProjectsConsoleClientTest extends Scope $platformAppleTvOsId = $data['platformAppleTvOsId'] ?? ''; - $response = $this->client->call(Client::METHOD_GET, '/projects/' . $id . '/platforms/' . $platformAppleTvOsId, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/projects/'.$id.'/platforms/'.$platformAppleTvOsId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -2192,7 +2176,7 @@ class ProjectsConsoleClientTest extends Scope /** * Test for FAILURE */ - $response = $this->client->call(Client::METHOD_GET, '/projects/' . $id . '/platforms/error', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/projects/'.$id.'/platforms/error', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -2211,7 +2195,7 @@ class ProjectsConsoleClientTest extends Scope $platformWebId = $data['platformWebId'] ?? ''; - $response = $this->client->call(Client::METHOD_PUT, '/projects/' . $id . '/platforms/' . $platformWebId, array_merge([ + $response = $this->client->call(Client::METHOD_PUT, '/projects/'.$id.'/platforms/'.$platformWebId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -2232,7 +2216,7 @@ class ProjectsConsoleClientTest extends Scope $platformFultteriOSId = $data['platformFultteriOSId'] ?? ''; - $response = $this->client->call(Client::METHOD_PUT, '/projects/' . $id . '/platforms/' . $platformFultteriOSId, array_merge([ + $response = $this->client->call(Client::METHOD_PUT, '/projects/'.$id.'/platforms/'.$platformFultteriOSId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -2253,7 +2237,7 @@ class ProjectsConsoleClientTest extends Scope $platformFultterAndroidId = $data['platformFultterAndroidId'] ?? ''; - $response = $this->client->call(Client::METHOD_PUT, '/projects/' . $id . '/platforms/' . $platformFultterAndroidId, array_merge([ + $response = $this->client->call(Client::METHOD_PUT, '/projects/'.$id.'/platforms/'.$platformFultterAndroidId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -2274,7 +2258,7 @@ class ProjectsConsoleClientTest extends Scope $platformFultterWebId = $data['platformFultterWebId'] ?? ''; - $response = $this->client->call(Client::METHOD_PUT, '/projects/' . $id . '/platforms/' . $platformFultterWebId, array_merge([ + $response = $this->client->call(Client::METHOD_PUT, '/projects/'.$id.'/platforms/'.$platformFultterWebId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -2295,7 +2279,7 @@ class ProjectsConsoleClientTest extends Scope $platformAppleIosId = $data['platformAppleIosId'] ?? ''; - $response = $this->client->call(Client::METHOD_PUT, '/projects/' . $id . '/platforms/' . $platformAppleIosId, array_merge([ + $response = $this->client->call(Client::METHOD_PUT, '/projects/'.$id.'/platforms/'.$platformAppleIosId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -2316,7 +2300,7 @@ class ProjectsConsoleClientTest extends Scope $platformAppleMacOsId = $data['platformAppleMacOsId'] ?? ''; - $response = $this->client->call(Client::METHOD_PUT, '/projects/' . $id . '/platforms/' . $platformAppleMacOsId, array_merge([ + $response = $this->client->call(Client::METHOD_PUT, '/projects/'.$id.'/platforms/'.$platformAppleMacOsId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -2337,7 +2321,7 @@ class ProjectsConsoleClientTest extends Scope $platformAppleWatchOsId = $data['platformAppleWatchOsId'] ?? ''; - $response = $this->client->call(Client::METHOD_PUT, '/projects/' . $id . '/platforms/' . $platformAppleWatchOsId, array_merge([ + $response = $this->client->call(Client::METHOD_PUT, '/projects/'.$id.'/platforms/'.$platformAppleWatchOsId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -2358,7 +2342,7 @@ class ProjectsConsoleClientTest extends Scope $platformAppleTvOsId = $data['platformAppleTvOsId'] ?? ''; - $response = $this->client->call(Client::METHOD_PUT, '/projects/' . $id . '/platforms/' . $platformAppleTvOsId, array_merge([ + $response = $this->client->call(Client::METHOD_PUT, '/projects/'.$id.'/platforms/'.$platformAppleTvOsId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -2380,7 +2364,7 @@ class ProjectsConsoleClientTest extends Scope /** * Test for FAILURE */ - $response = $this->client->call(Client::METHOD_PUT, '/projects/' . $id . '/platforms/error', array_merge([ + $response = $this->client->call(Client::METHOD_PUT, '/projects/'.$id.'/platforms/error', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -2404,7 +2388,7 @@ class ProjectsConsoleClientTest extends Scope $platformWebId = $data['platformWebId'] ?? ''; - $response = $this->client->call(Client::METHOD_DELETE, '/projects/' . $id . '/platforms/' . $platformWebId, array_merge([ + $response = $this->client->call(Client::METHOD_DELETE, '/projects/'.$id.'/platforms/'.$platformWebId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -2412,7 +2396,7 @@ class ProjectsConsoleClientTest extends Scope $this->assertEquals(204, $response['headers']['status-code']); $this->assertEmpty($response['body']); - $response = $this->client->call(Client::METHOD_GET, '/projects/' . $id . '/platforms/' . $platformWebId, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/projects/'.$id.'/platforms/'.$platformWebId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -2421,7 +2405,7 @@ class ProjectsConsoleClientTest extends Scope $platformFultteriOSId = $data['platformFultteriOSId'] ?? ''; - $response = $this->client->call(Client::METHOD_DELETE, '/projects/' . $id . '/platforms/' . $platformFultteriOSId, array_merge([ + $response = $this->client->call(Client::METHOD_DELETE, '/projects/'.$id.'/platforms/'.$platformFultteriOSId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -2429,7 +2413,7 @@ class ProjectsConsoleClientTest extends Scope $this->assertEquals(204, $response['headers']['status-code']); $this->assertEmpty($response['body']); - $response = $this->client->call(Client::METHOD_GET, '/projects/' . $id . '/platforms/' . $platformFultteriOSId, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/projects/'.$id.'/platforms/'.$platformFultteriOSId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -2438,7 +2422,7 @@ class ProjectsConsoleClientTest extends Scope $platformFultterAndroidId = $data['platformFultterAndroidId'] ?? ''; - $response = $this->client->call(Client::METHOD_DELETE, '/projects/' . $id . '/platforms/' . $platformFultterAndroidId, array_merge([ + $response = $this->client->call(Client::METHOD_DELETE, '/projects/'.$id.'/platforms/'.$platformFultterAndroidId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -2446,7 +2430,7 @@ class ProjectsConsoleClientTest extends Scope $this->assertEquals(204, $response['headers']['status-code']); $this->assertEmpty($response['body']); - $response = $this->client->call(Client::METHOD_GET, '/projects/' . $id . '/platforms/' . $platformFultterAndroidId, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/projects/'.$id.'/platforms/'.$platformFultterAndroidId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -2455,7 +2439,7 @@ class ProjectsConsoleClientTest extends Scope $platformFultterWebId = $data['platformFultterWebId'] ?? ''; - $response = $this->client->call(Client::METHOD_DELETE, '/projects/' . $id . '/platforms/' . $platformFultterWebId, array_merge([ + $response = $this->client->call(Client::METHOD_DELETE, '/projects/'.$id.'/platforms/'.$platformFultterWebId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -2463,7 +2447,7 @@ class ProjectsConsoleClientTest extends Scope $this->assertEquals(204, $response['headers']['status-code']); $this->assertEmpty($response['body']); - $response = $this->client->call(Client::METHOD_GET, '/projects/' . $id . '/platforms/' . $platformFultterWebId, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/projects/'.$id.'/platforms/'.$platformFultterWebId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -2472,7 +2456,7 @@ class ProjectsConsoleClientTest extends Scope $platformAppleIosId = $data['platformAppleIosId'] ?? ''; - $response = $this->client->call(Client::METHOD_DELETE, '/projects/' . $id . '/platforms/' . $platformAppleIosId, array_merge([ + $response = $this->client->call(Client::METHOD_DELETE, '/projects/'.$id.'/platforms/'.$platformAppleIosId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -2480,7 +2464,7 @@ class ProjectsConsoleClientTest extends Scope $this->assertEquals(204, $response['headers']['status-code']); $this->assertEmpty($response['body']); - $response = $this->client->call(Client::METHOD_GET, '/projects/' . $id . '/platforms/' . $platformAppleIosId, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/projects/'.$id.'/platforms/'.$platformAppleIosId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -2489,7 +2473,7 @@ class ProjectsConsoleClientTest extends Scope $platformAppleMacOsId = $data['platformAppleMacOsId'] ?? ''; - $response = $this->client->call(Client::METHOD_DELETE, '/projects/' . $id . '/platforms/' . $platformAppleMacOsId, array_merge([ + $response = $this->client->call(Client::METHOD_DELETE, '/projects/'.$id.'/platforms/'.$platformAppleMacOsId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -2497,7 +2481,7 @@ class ProjectsConsoleClientTest extends Scope $this->assertEquals(204, $response['headers']['status-code']); $this->assertEmpty($response['body']); - $response = $this->client->call(Client::METHOD_GET, '/projects/' . $id . '/platforms/' . $platformAppleMacOsId, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/projects/'.$id.'/platforms/'.$platformAppleMacOsId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -2506,7 +2490,7 @@ class ProjectsConsoleClientTest extends Scope $platformAppleWatchOsId = $data['platformAppleWatchOsId'] ?? ''; - $response = $this->client->call(Client::METHOD_DELETE, '/projects/' . $id . '/platforms/' . $platformAppleWatchOsId, array_merge([ + $response = $this->client->call(Client::METHOD_DELETE, '/projects/'.$id.'/platforms/'.$platformAppleWatchOsId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -2514,7 +2498,7 @@ class ProjectsConsoleClientTest extends Scope $this->assertEquals(204, $response['headers']['status-code']); $this->assertEmpty($response['body']); - $response = $this->client->call(Client::METHOD_GET, '/projects/' . $id . '/platforms/' . $platformAppleWatchOsId, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/projects/'.$id.'/platforms/'.$platformAppleWatchOsId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -2523,7 +2507,7 @@ class ProjectsConsoleClientTest extends Scope $platformAppleTvOsId = $data['platformAppleTvOsId'] ?? ''; - $response = $this->client->call(Client::METHOD_DELETE, '/projects/' . $id . '/platforms/' . $platformAppleTvOsId, array_merge([ + $response = $this->client->call(Client::METHOD_DELETE, '/projects/'.$id.'/platforms/'.$platformAppleTvOsId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -2531,7 +2515,7 @@ class ProjectsConsoleClientTest extends Scope $this->assertEquals(204, $response['headers']['status-code']); $this->assertEmpty($response['body']); - $response = $this->client->call(Client::METHOD_GET, '/projects/' . $id . '/platforms/' . $platformAppleTvOsId, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/projects/'.$id.'/platforms/'.$platformAppleTvOsId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -2541,7 +2525,7 @@ class ProjectsConsoleClientTest extends Scope /** * Test for FAILURE */ - $response = $this->client->call(Client::METHOD_DELETE, '/projects/' . $id . '/webhooks/error', array_merge([ + $response = $this->client->call(Client::METHOD_DELETE, '/projects/'.$id.'/webhooks/error', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -2560,7 +2544,7 @@ class ProjectsConsoleClientTest extends Scope { $id = $data['projectId'] ?? ''; - $response = $this->client->call(Client::METHOD_POST, '/projects/' . $id . '/domains', array_merge([ + $response = $this->client->call(Client::METHOD_POST, '/projects/'.$id.'/domains', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -2580,7 +2564,7 @@ class ProjectsConsoleClientTest extends Scope /** * Test for FAILURE */ - $response = $this->client->call(Client::METHOD_POST, '/projects/' . $id . '/platforms', array_merge([ + $response = $this->client->call(Client::METHOD_POST, '/projects/'.$id.'/platforms', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -2589,7 +2573,7 @@ class ProjectsConsoleClientTest extends Scope $this->assertEquals(400, $response['headers']['status-code']); - $response = $this->client->call(Client::METHOD_POST, '/projects/' . $id . '/platforms', array_merge([ + $response = $this->client->call(Client::METHOD_POST, '/projects/'.$id.'/platforms', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -2597,7 +2581,7 @@ class ProjectsConsoleClientTest extends Scope 'name' => 'Too Long Hostname', 'key' => '', 'store' => '', - 'hostname' => \str_repeat("bestdomain", 25) . '.com' // 250 + 4 chars total (exactly above limit) + 'hostname' => \str_repeat('bestdomain', 25).'.com', // 250 + 4 chars total (exactly above limit) ]); return $data; @@ -2610,7 +2594,7 @@ class ProjectsConsoleClientTest extends Scope { $id = $data['projectId'] ?? ''; - $response = $this->client->call(Client::METHOD_GET, '/projects/' . $id . '/domains', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/projects/'.$id.'/domains', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -2633,7 +2617,7 @@ class ProjectsConsoleClientTest extends Scope $id = $data['projectId'] ?? ''; $domainId = $data['domainId'] ?? ''; - $response = $this->client->call(Client::METHOD_GET, '/projects/' . $id . '/domains/' . $domainId, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/projects/'.$id.'/domains/'.$domainId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -2650,7 +2634,7 @@ class ProjectsConsoleClientTest extends Scope /** * Test for FAILURE */ - $response = $this->client->call(Client::METHOD_GET, '/projects/' . $id . '/domains/error', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/projects/'.$id.'/domains/error', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -2668,7 +2652,7 @@ class ProjectsConsoleClientTest extends Scope $id = $data['projectId'] ?? ''; $domainId = $data['domainId'] ?? ''; - $response = $this->client->call(Client::METHOD_PATCH, '/projects/' . $id . '/domains/' . $domainId . '/verification', array_merge([ + $response = $this->client->call(Client::METHOD_PATCH, '/projects/'.$id.'/domains/'.$domainId.'/verification', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -2690,7 +2674,7 @@ class ProjectsConsoleClientTest extends Scope $id = $data['projectId'] ?? ''; $domainId = $data['domainId'] ?? ''; - $response = $this->client->call(Client::METHOD_DELETE, '/projects/' . $id . '/domains/' . $domainId, array_merge([ + $response = $this->client->call(Client::METHOD_DELETE, '/projects/'.$id.'/domains/'.$domainId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -2698,7 +2682,7 @@ class ProjectsConsoleClientTest extends Scope $this->assertEquals(204, $response['headers']['status-code']); $this->assertEmpty($response['body']); - $response = $this->client->call(Client::METHOD_GET, '/projects/' . $id . '/domains/' . $domainId, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/projects/'.$id.'/domains/'.$domainId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -2708,7 +2692,7 @@ class ProjectsConsoleClientTest extends Scope /** * Test for FAILURE */ - $response = $this->client->call(Client::METHOD_DELETE, '/projects/' . $id . '/domains/error', array_merge([ + $response = $this->client->call(Client::METHOD_DELETE, '/projects/'.$id.'/domains/error', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -2744,7 +2728,7 @@ class ProjectsConsoleClientTest extends Scope 'projectId' => ID::unique(), 'name' => 'Amazing Project', 'teamId' => $teamId, - 'region' => 'default' + 'region' => 'default', ]); $this->assertEquals(201, $project['headers']['status-code']); @@ -2755,14 +2739,14 @@ class ProjectsConsoleClientTest extends Scope $projectId = $project['body']['$id']; // Ensure I can get both team and project - $team = $this->client->call(Client::METHOD_GET, '/teams/' . $teamId, array_merge([ + $team = $this->client->call(Client::METHOD_GET, '/teams/'.$teamId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); $this->assertEquals(200, $team['headers']['status-code']); - $project = $this->client->call(Client::METHOD_GET, '/projects/' . $projectId, array_merge([ + $project = $this->client->call(Client::METHOD_GET, '/projects/'.$projectId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -2770,24 +2754,24 @@ class ProjectsConsoleClientTest extends Scope $this->assertEquals(200, $project['headers']['status-code']); // Delete team - $team = $this->client->call(Client::METHOD_DELETE, '/projects/' . $projectId, array_merge([ + $team = $this->client->call(Client::METHOD_DELETE, '/projects/'.$projectId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'password' => 'password' + 'password' => 'password', ]); $this->assertEquals(204, $team['headers']['status-code']); // Ensure I can get team but not a project - $team = $this->client->call(Client::METHOD_GET, '/teams/' . $teamId, array_merge([ + $team = $this->client->call(Client::METHOD_GET, '/teams/'.$teamId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); $this->assertEquals(200, $team['headers']['status-code']); - $project = $this->client->call(Client::METHOD_GET, '/projects/' . $projectId, array_merge([ + $project = $this->client->call(Client::METHOD_GET, '/projects/'.$projectId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); diff --git a/tests/e2e/Services/Projects/ProjectsCustomClientTest.php b/tests/e2e/Services/Projects/ProjectsCustomClientTest.php index 9dfd48ce50..25140309af 100644 --- a/tests/e2e/Services/Projects/ProjectsCustomClientTest.php +++ b/tests/e2e/Services/Projects/ProjectsCustomClientTest.php @@ -2,10 +2,9 @@ namespace Tests\E2E\Services\Projects; -use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\ProjectCustom; +use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\SideClient; -use Tests\E2E\Client; class ProjectsCustomClientTest extends Scope { diff --git a/tests/e2e/Services/Projects/ProjectsCustomServerTest.php b/tests/e2e/Services/Projects/ProjectsCustomServerTest.php index 1c5b48f146..436d1df611 100644 --- a/tests/e2e/Services/Projects/ProjectsCustomServerTest.php +++ b/tests/e2e/Services/Projects/ProjectsCustomServerTest.php @@ -5,7 +5,6 @@ namespace Tests\E2E\Services\Projects; use Tests\E2E\Scopes\ProjectCustom; use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\SideServer; -use Tests\E2E\Client; class ProjectsCustomServerTest extends Scope { diff --git a/tests/e2e/Services/Realtime/RealtimeBase.php b/tests/e2e/Services/Realtime/RealtimeBase.php index 62bb7f5d3b..baf27e78ea 100644 --- a/tests/e2e/Services/Realtime/RealtimeBase.php +++ b/tests/e2e/Services/Realtime/RealtimeBase.php @@ -2,8 +2,8 @@ namespace Tests\E2E\Services\Realtime; -use WebSocket\ConnectionException; use WebSocket\Client as WebSocketClient; +use WebSocket\ConnectionException; trait RealtimeBase { @@ -14,15 +14,15 @@ trait RealtimeBase } $headers = array_merge([ - 'Origin' => 'appwrite.test' + 'Origin' => 'appwrite.test', ], $headers); $query = [ 'project' => $projectId, - 'channels' => $channels + 'channels' => $channels, ]; - return new WebSocketClient('ws://appwrite-traefik/v1/realtime?' . http_build_query($query), [ + return new WebSocketClient('ws://appwrite-traefik/v1/realtime?'.http_build_query($query), [ 'headers' => $headers, 'timeout' => 30, ]); @@ -57,8 +57,8 @@ trait RealtimeBase { $client = new WebSocketClient('ws://appwrite-traefik/v1/realtime?project=123', [ 'headers' => [ - 'Origin' => 'appwrite.test' - ] + 'Origin' => 'appwrite.test', + ], ]); $payload = json_decode($client->receive(), true); diff --git a/tests/e2e/Services/Realtime/RealtimeConsoleClientTest.php b/tests/e2e/Services/Realtime/RealtimeConsoleClientTest.php index cd2fb6f13b..04c07cf0dd 100644 --- a/tests/e2e/Services/Realtime/RealtimeConsoleClientTest.php +++ b/tests/e2e/Services/Realtime/RealtimeConsoleClientTest.php @@ -4,8 +4,8 @@ namespace Tests\E2E\Services\Realtime; use CURLFile; use Tests\E2E\Client; -use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\ProjectCustom; +use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\SideConsole; use Tests\E2E\Services\Functions\FunctionsBase; use Utopia\Database\Helpers\ID; @@ -29,7 +29,7 @@ class RealtimeConsoleClientTest extends Scope * Test for SUCCESS */ $client = $this->getWebsocket(['account'], [ - 'origin' => 'http://localhost' + 'origin' => 'http://localhost', ]); $response = json_decode($client->receive(), true); @@ -43,8 +43,8 @@ class RealtimeConsoleClientTest extends Scope $client->send(\json_encode([ 'type' => 'authentication', 'data' => [ - 'session' => $session - ] + 'session' => $session, + ], ])); $response = json_decode($client->receive(), true); @@ -64,8 +64,8 @@ class RealtimeConsoleClientTest extends Scope $client->send(\json_encode([ 'type' => 'authentication', 'data' => [ - 'session' => 'invalid_session' - ] + 'session' => 'invalid_session', + ], ])); $response = json_decode($client->receive(), true); @@ -79,7 +79,7 @@ class RealtimeConsoleClientTest extends Scope $client->send(\json_encode([ 'type' => 'authentication', - 'data' => [] + 'data' => [], ])); $response = json_decode($client->receive(), true); @@ -94,8 +94,8 @@ class RealtimeConsoleClientTest extends Scope $client->send(\json_encode([ 'type' => 'unknown', 'data' => [ - 'session' => 'invalid_session' - ] + 'session' => 'invalid_session', + ], ])); $response = json_decode($client->receive(), true); @@ -120,7 +120,6 @@ class RealtimeConsoleClientTest extends Scope $this->assertEquals(1003, $response['data']['code']); $this->assertEquals('Message format is not valid.', $response['data']['message']); - $client->close(); } @@ -131,7 +130,7 @@ class RealtimeConsoleClientTest extends Scope $client = $this->getWebsocket(['console'], [ 'origin' => 'http://localhost', - 'cookie' => 'a_session_console=' . $this->getRoot()['session'], + 'cookie' => 'a_session_console='.$this->getRoot()['session'], ], $projectId); $response = json_decode($client->receive(), true); @@ -159,7 +158,7 @@ class RealtimeConsoleClientTest extends Scope /** * Test Attributes */ - $actors = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections', array_merge([ + $actors = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -175,7 +174,7 @@ class RealtimeConsoleClientTest extends Scope $actorsId = $actors['body']['$id']; - $name = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $actorsId . '/attributes/string', array_merge([ + $name = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$actorsId.'/attributes/string', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -207,7 +206,7 @@ class RealtimeConsoleClientTest extends Scope $this->assertContains("databases.{$databaseId}.collections.*.attributes.*", $response['data']['events']); $this->assertContains("databases.{$databaseId}.collections.*", $response['data']['events']); $this->assertContains("databases.{$databaseId}", $response['data']['events']); - $this->assertContains("databases.*", $response['data']['events']); + $this->assertContains('databases.*', $response['data']['events']); $this->assertNotEmpty($response['data']['payload']); $this->assertEquals('processing', $response['data']['payload']['status']); @@ -227,7 +226,7 @@ class RealtimeConsoleClientTest extends Scope $this->assertContains("databases.{$databaseId}.collections.*.attributes.*", $response['data']['events']); $this->assertContains("databases.{$databaseId}.collections.*", $response['data']['events']); $this->assertContains("databases.{$databaseId}", $response['data']['events']); - $this->assertContains("databases.*", $response['data']['events']); + $this->assertContains('databases.*', $response['data']['events']); $this->assertNotEmpty($response['data']['payload']); $this->assertEquals('available', $response['data']['payload']['status']); @@ -248,7 +247,7 @@ class RealtimeConsoleClientTest extends Scope $databaseId = $data['databaseId']; $client = $this->getWebsocket(['console'], [ 'origin' => 'http://localhost', - 'cookie' => 'a_session_console=' . $this->getRoot()['session'], + 'cookie' => 'a_session_console='.$this->getRoot()['session'], ], $projectId); $response = json_decode($client->receive(), true); @@ -264,7 +263,7 @@ class RealtimeConsoleClientTest extends Scope /** * Test Indexes */ - $index = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $actorsId . '/indexes', array_merge([ + $index = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$actorsId.'/indexes', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -330,7 +329,7 @@ class RealtimeConsoleClientTest extends Scope $client = $this->getWebsocket(['console'], [ 'origin' => 'http://localhost', - 'cookie' => 'a_session_console=' . $this->getRoot()['session'], + 'cookie' => 'a_session_console='.$this->getRoot()['session'], ], $projectId); $response = json_decode($client->receive(), true); @@ -346,7 +345,7 @@ class RealtimeConsoleClientTest extends Scope /** * Test Delete Index */ - $attribute = $this->client->call(Client::METHOD_DELETE, '/databases/' . $databaseId . '/collections/' . $actorsId . '/indexes/key_name', array_merge([ + $attribute = $this->client->call(Client::METHOD_DELETE, '/databases/'.$databaseId.'/collections/'.$actorsId.'/indexes/key_name', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -386,7 +385,7 @@ class RealtimeConsoleClientTest extends Scope $client = $this->getWebsocket(['console'], [ 'origin' => 'http://localhost', - 'cookie' => 'a_session_console=' . $this->getRoot()['session'], + 'cookie' => 'a_session_console='.$this->getRoot()['session'], ], $projectId); $response = json_decode($client->receive(), true); @@ -402,7 +401,7 @@ class RealtimeConsoleClientTest extends Scope /** * Test Delete Attribute */ - $attribute = $this->client->call(Client::METHOD_DELETE, '/databases/' . $databaseId . '/collections/' . $data['actorsId'] . '/attributes/name', array_merge([ + $attribute = $this->client->call(Client::METHOD_DELETE, '/databases/'.$databaseId.'/collections/'.$data['actorsId'].'/attributes/name', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -450,12 +449,11 @@ class RealtimeConsoleClientTest extends Scope $this->assertEquals(201, $response1['headers']['status-code']); - $projectId = 'console'; $client = $this->getWebsocket(['console'], [ 'origin' => 'http://localhost', - 'cookie' => 'a_session_console=' . $this->getRoot()['session'], + 'cookie' => 'a_session_console='.$this->getRoot()['session'], ], $projectId); $response = json_decode($client->receive(), true); @@ -471,12 +469,11 @@ class RealtimeConsoleClientTest extends Scope /** * Test Create Deployment */ - $folder = 'php'; - $code = realpath(__DIR__ . '/../../../resources/functions') . "/$folder/code.tar.gz"; + $code = realpath(__DIR__.'/../../../resources/functions')."/$folder/code.tar.gz"; $this->packageCode($folder); - $deployment = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/deployments', array_merge([ + $deployment = $this->client->call(Client::METHOD_POST, '/functions/'.$functionId.'/deployments', array_merge([ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ diff --git a/tests/e2e/Services/Realtime/RealtimeCustomClientTest.php b/tests/e2e/Services/Realtime/RealtimeCustomClientTest.php index 5910c9975a..8c57663824 100644 --- a/tests/e2e/Services/Realtime/RealtimeCustomClientTest.php +++ b/tests/e2e/Services/Realtime/RealtimeCustomClientTest.php @@ -4,8 +4,8 @@ namespace Tests\E2E\Services\Realtime; use CURLFile; use Tests\E2E\Client; -use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\ProjectCustom; +use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\SideClient; use Utopia\CLI\Console; use Utopia\Database\Helpers\ID; @@ -25,9 +25,9 @@ class RealtimeCustomClientTest extends Scope $userId = $user['$id'] ?? ''; $session = $user['session'] ?? ''; - $headers = [ + $headers = [ 'origin' => 'http://localhost', - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]; $client = $this->getWebsocket(['documents'], $headers); @@ -54,7 +54,7 @@ class RealtimeCustomClientTest extends Scope $this->assertNotEmpty($response['data']['user']); $this->assertCount(2, $response['data']['channels']); $this->assertContains('account', $response['data']['channels']); - $this->assertContains('account.' . $userId, $response['data']['channels']); + $this->assertContains('account.'.$userId, $response['data']['channels']); $this->assertEquals($userId, $response['data']['user']['$id']); $client->close(); @@ -70,7 +70,7 @@ class RealtimeCustomClientTest extends Scope $this->assertCount(3, $response['data']['channels']); $this->assertContains('documents', $response['data']['channels']); $this->assertContains('account', $response['data']['channels']); - $this->assertContains('account.' . $userId, $response['data']['channels']); + $this->assertContains('account.'.$userId, $response['data']['channels']); $this->assertEquals($userId, $response['data']['user']['$id']); $client->close(); @@ -96,7 +96,7 @@ class RealtimeCustomClientTest extends Scope $this->assertNotEmpty($response['data']['user']); $this->assertCount(10, $response['data']['channels']); $this->assertContains('account', $response['data']['channels']); - $this->assertContains('account.' . $userId, $response['data']['channels']); + $this->assertContains('account.'.$userId, $response['data']['channels']); $this->assertContains('files', $response['data']['channels']); $this->assertContains('files.1', $response['data']['channels']); $this->assertContains('collections', $response['data']['channels']); @@ -120,7 +120,7 @@ class RealtimeCustomClientTest extends Scope * Test for SUCCESS */ $client = $this->getWebsocket(['account'], [ - 'origin' => 'http://localhost' + 'origin' => 'http://localhost', ]); $response = json_decode($client->receive(), true); @@ -134,8 +134,8 @@ class RealtimeCustomClientTest extends Scope $client->send(\json_encode([ 'type' => 'authentication', 'data' => [ - 'session' => $session - ] + 'session' => $session, + ], ])); $response = json_decode($client->receive(), true); @@ -155,8 +155,8 @@ class RealtimeCustomClientTest extends Scope $client->send(\json_encode([ 'type' => 'authentication', 'data' => [ - 'session' => 'invalid_session' - ] + 'session' => 'invalid_session', + ], ])); $response = json_decode($client->receive(), true); @@ -170,7 +170,7 @@ class RealtimeCustomClientTest extends Scope $client->send(\json_encode([ 'type' => 'authentication', - 'data' => [] + 'data' => [], ])); $response = json_decode($client->receive(), true); @@ -185,8 +185,8 @@ class RealtimeCustomClientTest extends Scope $client->send(\json_encode([ 'type' => 'unknown', 'data' => [ - 'session' => 'invalid_session' - ] + 'session' => 'invalid_session', + ], ])); $response = json_decode($client->receive(), true); @@ -211,7 +211,6 @@ class RealtimeCustomClientTest extends Scope $this->assertEquals(1003, $response['data']['code']); $this->assertEquals('Message format is not valid.', $response['data']['message']); - $client->close(); } @@ -242,7 +241,7 @@ class RealtimeCustomClientTest extends Scope $client = $this->getWebsocket(['account'], [ 'origin' => 'http://localhost', - 'cookie' => 'a_session_' . $projectId . '=' . $session + 'cookie' => 'a_session_'.$projectId.'='.$session, ]); $response = json_decode($client->receive(), true); @@ -252,22 +251,22 @@ class RealtimeCustomClientTest extends Scope $this->assertNotEmpty($response['data']); $this->assertCount(2, $response['data']['channels']); $this->assertContains('account', $response['data']['channels']); - $this->assertContains('account.' . $userId, $response['data']['channels']); + $this->assertContains('account.'.$userId, $response['data']['channels']); $this->assertNotEmpty($response['data']['user']); $this->assertEquals($userId, $response['data']['user']['$id']); /** * Test Account Name Event */ - $name = "Torsten Dittmann"; + $name = 'Torsten Dittmann'; $this->client->call(Client::METHOD_PATCH, '/account/name', array_merge([ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $projectId, - 'cookie' => 'a_session_' . $projectId . '=' . $session, + 'cookie' => 'a_session_'.$projectId.'='.$session, ]), [ - 'name' => $name + 'name' => $name, ]); $response = json_decode($client->receive(), true); @@ -279,18 +278,17 @@ class RealtimeCustomClientTest extends Scope $this->assertCount(2, $response['data']['channels']); $this->assertArrayHasKey('timestamp', $response['data']); $this->assertContains('account', $response['data']['channels']); - $this->assertContains('account.' . $userId, $response['data']['channels']); + $this->assertContains('account.'.$userId, $response['data']['channels']); $this->assertContains("users.{$userId}.update.name", $response['data']['events']); $this->assertContains("users.{$userId}.update", $response['data']['events']); $this->assertContains("users.{$userId}", $response['data']['events']); - $this->assertContains("users.*.update.name", $response['data']['events']); - $this->assertContains("users.*.update", $response['data']['events']); - $this->assertContains("users.*", $response['data']['events']); + $this->assertContains('users.*.update.name', $response['data']['events']); + $this->assertContains('users.*.update', $response['data']['events']); + $this->assertContains('users.*', $response['data']['events']); $this->assertNotEmpty($response['data']['payload']); $this->assertEquals($name, $response['data']['payload']['name']); - /** * Test Account Password Event */ @@ -298,7 +296,7 @@ class RealtimeCustomClientTest extends Scope 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $projectId, - 'cookie' => 'a_session_' . $projectId . '=' . $session, + 'cookie' => 'a_session_'.$projectId.'='.$session, ]), [ 'password' => 'new-password', 'oldPassword' => 'password', @@ -313,13 +311,13 @@ class RealtimeCustomClientTest extends Scope $this->assertCount(2, $response['data']['channels']); $this->assertArrayHasKey('timestamp', $response['data']); $this->assertContains('account', $response['data']['channels']); - $this->assertContains('account.' . $userId, $response['data']['channels']); + $this->assertContains('account.'.$userId, $response['data']['channels']); $this->assertContains("users.{$userId}.update.password", $response['data']['events']); $this->assertContains("users.{$userId}.update", $response['data']['events']); $this->assertContains("users.{$userId}", $response['data']['events']); - $this->assertContains("users.*.update.password", $response['data']['events']); - $this->assertContains("users.*.update", $response['data']['events']); - $this->assertContains("users.*", $response['data']['events']); + $this->assertContains('users.*.update.password', $response['data']['events']); + $this->assertContains('users.*.update', $response['data']['events']); + $this->assertContains('users.*', $response['data']['events']); $this->assertNotEmpty($response['data']['payload']); $this->assertEquals($name, $response['data']['payload']['name']); @@ -331,7 +329,7 @@ class RealtimeCustomClientTest extends Scope 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $projectId, - 'cookie' => 'a_session_' . $projectId . '=' . $session, + 'cookie' => 'a_session_'.$projectId.'='.$session, ]), [ 'email' => 'torsten@appwrite.io', 'password' => 'new-password', @@ -346,13 +344,13 @@ class RealtimeCustomClientTest extends Scope $this->assertCount(2, $response['data']['channels']); $this->assertArrayHasKey('timestamp', $response['data']); $this->assertContains('account', $response['data']['channels']); - $this->assertContains('account.' . $userId, $response['data']['channels']); + $this->assertContains('account.'.$userId, $response['data']['channels']); $this->assertContains("users.{$userId}.update.email", $response['data']['events']); $this->assertContains("users.{$userId}.update", $response['data']['events']); $this->assertContains("users.{$userId}", $response['data']['events']); - $this->assertContains("users.*.update.email", $response['data']['events']); - $this->assertContains("users.*.update", $response['data']['events']); - $this->assertContains("users.*", $response['data']['events']); + $this->assertContains('users.*.update.email', $response['data']['events']); + $this->assertContains('users.*.update', $response['data']['events']); + $this->assertContains('users.*', $response['data']['events']); $this->assertNotEmpty($response['data']['payload']); $this->assertEquals('torsten@appwrite.io', $response['data']['payload']['email']); @@ -363,7 +361,7 @@ class RealtimeCustomClientTest extends Scope 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $projectId, - 'cookie' => 'a_session_' . $projectId . '=' . $session, + 'cookie' => 'a_session_'.$projectId.'='.$session, ]), [ 'url' => 'http://localhost/verification', ]); @@ -377,7 +375,7 @@ class RealtimeCustomClientTest extends Scope $this->assertCount(2, $response['data']['channels']); $this->assertArrayHasKey('timestamp', $response['data']); $this->assertContains('account', $response['data']['channels']); - $this->assertContains('account.' . $userId, $response['data']['channels']); + $this->assertContains('account.'.$userId, $response['data']['channels']); $this->assertContains("users.{$userId}.verification.{$verificationId}.create", $response['data']['events']); $this->assertContains("users.{$userId}.verification.{$verificationId}", $response['data']['events']); $this->assertContains("users.{$userId}.verification.*.create", $response['data']['events']); @@ -385,9 +383,9 @@ class RealtimeCustomClientTest extends Scope $this->assertContains("users.{$userId}", $response['data']['events']); $this->assertContains("users.*.verification.{$verificationId}.create", $response['data']['events']); $this->assertContains("users.*.verification.{$verificationId}", $response['data']['events']); - $this->assertContains("users.*.verification.*.create", $response['data']['events']); - $this->assertContains("users.*.verification.*", $response['data']['events']); - $this->assertContains("users.*", $response['data']['events']); + $this->assertContains('users.*.verification.*.create', $response['data']['events']); + $this->assertContains('users.*.verification.*', $response['data']['events']); + $this->assertContains('users.*', $response['data']['events']); $lastEmail = $this->getLastEmail(); $verification = substr($lastEmail['text'], strpos($lastEmail['text'], '&secret=', 0) + 8, 256); @@ -399,7 +397,7 @@ class RealtimeCustomClientTest extends Scope 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $projectId, - 'cookie' => 'a_session_' . $projectId . '=' . $session, + 'cookie' => 'a_session_'.$projectId.'='.$session, ]), [ 'userId' => $userId, 'secret' => $verification, @@ -414,7 +412,7 @@ class RealtimeCustomClientTest extends Scope $this->assertCount(2, $response['data']['channels']); $this->assertArrayHasKey('timestamp', $response['data']); $this->assertContains('account', $response['data']['channels']); - $this->assertContains('account.' . $userId, $response['data']['channels']); + $this->assertContains('account.'.$userId, $response['data']['channels']); $this->assertContains("users.{$userId}.verification.{$verificationId}.update", $response['data']['events']); $this->assertContains("users.{$userId}.verification.{$verificationId}", $response['data']['events']); $this->assertContains("users.{$userId}.verification.*.update", $response['data']['events']); @@ -422,9 +420,9 @@ class RealtimeCustomClientTest extends Scope $this->assertContains("users.{$userId}", $response['data']['events']); $this->assertContains("users.*.verification.{$verificationId}.update", $response['data']['events']); $this->assertContains("users.*.verification.{$verificationId}", $response['data']['events']); - $this->assertContains("users.*.verification.*.update", $response['data']['events']); - $this->assertContains("users.*.verification.*", $response['data']['events']); - $this->assertContains("users.*", $response['data']['events']); + $this->assertContains('users.*.verification.*.update', $response['data']['events']); + $this->assertContains('users.*.verification.*', $response['data']['events']); + $this->assertContains('users.*', $response['data']['events']); /** * Test Acoount Prefs Update */ @@ -432,12 +430,12 @@ class RealtimeCustomClientTest extends Scope 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $projectId, - 'cookie' => 'a_session_' . $projectId . '=' . $session, + 'cookie' => 'a_session_'.$projectId.'='.$session, ]), [ 'prefs' => [ 'prefKey1' => 'prefValue1', 'prefKey2' => 'prefValue2', - ] + ], ]); $response = json_decode($client->receive(), true); @@ -449,13 +447,13 @@ class RealtimeCustomClientTest extends Scope $this->assertCount(2, $response['data']['channels']); $this->assertArrayHasKey('timestamp', $response['data']); $this->assertContains('account', $response['data']['channels']); - $this->assertContains('account.' . $userId, $response['data']['channels']); + $this->assertContains('account.'.$userId, $response['data']['channels']); $this->assertContains("users.{$userId}.update.prefs", $response['data']['events']); $this->assertContains("users.{$userId}.update", $response['data']['events']); $this->assertContains("users.{$userId}", $response['data']['events']); - $this->assertContains("users.*.update.prefs", $response['data']['events']); - $this->assertContains("users.*.update", $response['data']['events']); - $this->assertContains("users.*", $response['data']['events']); + $this->assertContains('users.*.update.prefs', $response['data']['events']); + $this->assertContains('users.*.update', $response['data']['events']); + $this->assertContains('users.*', $response['data']['events']); $this->assertNotEmpty($response['data']['payload']); $createSession = function () use ($projectId): array { @@ -468,10 +466,10 @@ class RealtimeCustomClientTest extends Scope 'password' => 'new-password', ]); - $sessionNew = $this->client->parseCookie((string)$response['headers']['set-cookie'])['a_session_' . $projectId]; + $sessionNew = $this->client->parseCookie((string) $response['headers']['set-cookie'])['a_session_'.$projectId]; $sessionNewId = $response['body']['$id']; - return array("session" => $sessionNew, "sessionId" => $sessionNewId); + return ['session' => $sessionNew, 'sessionId' => $sessionNewId]; }; /** @@ -490,7 +488,7 @@ class RealtimeCustomClientTest extends Scope $this->assertCount(2, $response['data']['channels']); $this->assertArrayHasKey('timestamp', $response['data']); $this->assertContains('account', $response['data']['channels']); - $this->assertContains('account.' . $userId, $response['data']['channels']); + $this->assertContains('account.'.$userId, $response['data']['channels']); $this->assertContains("users.{$userId}.sessions.{$sessionNewId}.create", $response['data']['events']); $this->assertContains("users.{$userId}.sessions.{$sessionNewId}", $response['data']['events']); $this->assertContains("users.{$userId}.sessions.*.create", $response['data']['events']); @@ -498,19 +496,19 @@ class RealtimeCustomClientTest extends Scope $this->assertContains("users.{$userId}", $response['data']['events']); $this->assertContains("users.*.sessions.{$sessionNewId}.create", $response['data']['events']); $this->assertContains("users.*.sessions.{$sessionNewId}", $response['data']['events']); - $this->assertContains("users.*.sessions.*.create", $response['data']['events']); - $this->assertContains("users.*.sessions.*", $response['data']['events']); - $this->assertContains("users.*", $response['data']['events']); + $this->assertContains('users.*.sessions.*.create', $response['data']['events']); + $this->assertContains('users.*.sessions.*', $response['data']['events']); + $this->assertContains('users.*', $response['data']['events']); $this->assertNotEmpty($response['data']['payload']); /** * Test Account Session Delete */ - $this->client->call(Client::METHOD_DELETE, '/account/sessions/' . $sessionNewId, array_merge([ + $this->client->call(Client::METHOD_DELETE, '/account/sessions/'.$sessionNewId, array_merge([ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $projectId, - 'cookie' => 'a_session_' . $projectId . '=' . $sessionNew, + 'cookie' => 'a_session_'.$projectId.'='.$sessionNew, ])); $response = json_decode($client->receive(), true); @@ -522,7 +520,7 @@ class RealtimeCustomClientTest extends Scope $this->assertCount(2, $response['data']['channels']); $this->assertArrayHasKey('timestamp', $response['data']); $this->assertContains('account', $response['data']['channels']); - $this->assertContains('account.' . $userId, $response['data']['channels']); + $this->assertContains('account.'.$userId, $response['data']['channels']); $this->assertContains("users.{$userId}.sessions.{$sessionNewId}.delete", $response['data']['events']); $this->assertContains("users.{$userId}.sessions.{$sessionNewId}", $response['data']['events']); $this->assertContains("users.{$userId}.sessions.*.delete", $response['data']['events']); @@ -530,21 +528,20 @@ class RealtimeCustomClientTest extends Scope $this->assertContains("users.{$userId}", $response['data']['events']); $this->assertContains("users.*.sessions.{$sessionNewId}.delete", $response['data']['events']); $this->assertContains("users.*.sessions.{$sessionNewId}", $response['data']['events']); - $this->assertContains("users.*.sessions.*.delete", $response['data']['events']); - $this->assertContains("users.*.sessions.*", $response['data']['events']); - $this->assertContains("users.*", $response['data']['events']); + $this->assertContains('users.*.sessions.*.delete', $response['data']['events']); + $this->assertContains('users.*.sessions.*', $response['data']['events']); + $this->assertContains('users.*', $response['data']['events']); $this->assertNotEmpty($response['data']['payload']); /** * Test User Account Session Delete */ - $sessionData = $createSession(); $sessionNew = $sessionData['session']; $sessionNewId = $sessionData['sessionId']; $client->receive(); // Receive the creation message and drop; this was tested earlier already - $this->client->call(Client::METHOD_DELETE, '/users/' . $userId . '/sessions/' . $sessionNewId, array_merge([ + $this->client->call(Client::METHOD_DELETE, '/users/'.$userId.'/sessions/'.$sessionNewId, array_merge([ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $projectId, @@ -559,7 +556,7 @@ class RealtimeCustomClientTest extends Scope $this->assertCount(2, $response['data']['channels']); $this->assertArrayHasKey('timestamp', $response['data']); $this->assertContains('account', $response['data']['channels']); - $this->assertContains('account.' . $userId, $response['data']['channels']); + $this->assertContains('account.'.$userId, $response['data']['channels']); $this->assertContains("users.{$userId}.sessions.{$sessionNewId}.delete", $response['data']['events']); $this->assertContains("users.{$userId}.sessions.{$sessionNewId}", $response['data']['events']); $this->assertContains("users.{$userId}.sessions.*.delete", $response['data']['events']); @@ -567,9 +564,9 @@ class RealtimeCustomClientTest extends Scope $this->assertContains("users.{$userId}", $response['data']['events']); $this->assertContains("users.*.sessions.{$sessionNewId}.delete", $response['data']['events']); $this->assertContains("users.*.sessions.{$sessionNewId}", $response['data']['events']); - $this->assertContains("users.*.sessions.*.delete", $response['data']['events']); - $this->assertContains("users.*.sessions.*", $response['data']['events']); - $this->assertContains("users.*", $response['data']['events']); + $this->assertContains('users.*.sessions.*.delete', $response['data']['events']); + $this->assertContains('users.*.sessions.*', $response['data']['events']); + $this->assertContains('users.*', $response['data']['events']); $this->assertNotEmpty($response['data']['payload']); /** @@ -596,7 +593,7 @@ class RealtimeCustomClientTest extends Scope $this->assertCount(2, $response['data']['channels']); $this->assertArrayHasKey('timestamp', $response['data']); $this->assertContains('account', $response['data']['channels']); - $this->assertContains('account.' . $userId, $response['data']['channels']); + $this->assertContains('account.'.$userId, $response['data']['channels']); $this->assertContains("users.{$userId}.recovery.{$recoveryId}.create", $response['data']['events']); $this->assertContains("users.{$userId}.recovery.{$recoveryId}", $response['data']['events']); $this->assertContains("users.{$userId}.recovery.*.create", $response['data']['events']); @@ -604,9 +601,9 @@ class RealtimeCustomClientTest extends Scope $this->assertContains("users.{$userId}", $response['data']['events']); $this->assertContains("users.*.recovery.{$recoveryId}.create", $response['data']['events']); $this->assertContains("users.*.recovery.{$recoveryId}", $response['data']['events']); - $this->assertContains("users.*.recovery.*.create", $response['data']['events']); - $this->assertContains("users.*.recovery.*", $response['data']['events']); - $this->assertContains("users.*", $response['data']['events']); + $this->assertContains('users.*.recovery.*.create', $response['data']['events']); + $this->assertContains('users.*.recovery.*', $response['data']['events']); + $this->assertContains('users.*', $response['data']['events']); $this->assertNotEmpty($response['data']['payload']); $response = $this->client->call(Client::METHOD_PUT, '/account/recovery', array_merge([ @@ -629,7 +626,7 @@ class RealtimeCustomClientTest extends Scope $this->assertCount(2, $response['data']['channels']); $this->assertArrayHasKey('timestamp', $response['data']); $this->assertContains('account', $response['data']['channels']); - $this->assertContains('account.' . $userId, $response['data']['channels']); + $this->assertContains('account.'.$userId, $response['data']['channels']); $this->assertContains("users.{$userId}.recovery.{$recoveryId}.update", $response['data']['events']); $this->assertContains("users.{$userId}.recovery.{$recoveryId}", $response['data']['events']); $this->assertContains("users.{$userId}.recovery.*.update", $response['data']['events']); @@ -637,9 +634,9 @@ class RealtimeCustomClientTest extends Scope $this->assertContains("users.{$userId}", $response['data']['events']); $this->assertContains("users.*.recovery.{$recoveryId}.update", $response['data']['events']); $this->assertContains("users.*.recovery.{$recoveryId}", $response['data']['events']); - $this->assertContains("users.*.recovery.*.update", $response['data']['events']); - $this->assertContains("users.*.recovery.*", $response['data']['events']); - $this->assertContains("users.*", $response['data']['events']); + $this->assertContains('users.*.recovery.*.update', $response['data']['events']); + $this->assertContains('users.*.recovery.*', $response['data']['events']); + $this->assertContains('users.*', $response['data']['events']); $this->assertNotEmpty($response['data']['payload']); $client->close(); @@ -653,7 +650,7 @@ class RealtimeCustomClientTest extends Scope $client = $this->getWebsocket(['documents', 'collections'], [ 'origin' => 'http://localhost', - 'cookie' => 'a_session_' . $projectId . '=' . $session + 'cookie' => 'a_session_'.$projectId.'='.$session, ]); $response = json_decode($client->receive(), true); @@ -674,7 +671,7 @@ class RealtimeCustomClientTest extends Scope $database = $this->client->call(Client::METHOD_POST, '/databases', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'databaseId' => ID::unique(), 'name' => 'Actors DB', @@ -685,10 +682,10 @@ class RealtimeCustomClientTest extends Scope /** * Test Collection Create */ - $actors = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections', array_merge([ + $actors = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'collectionId' => ID::unique(), 'name' => 'Actors', @@ -700,10 +697,10 @@ class RealtimeCustomClientTest extends Scope $actorsId = $actors['body']['$id']; - $name = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $actorsId . '/attributes/string', array_merge([ + $name = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$actorsId.'/attributes/string', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'name', 'size' => 256, @@ -721,13 +718,13 @@ class RealtimeCustomClientTest extends Scope /** * Test Document Create */ - $document = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $actorsId . '/documents', array_merge([ + $document = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$actorsId.'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'documentId' => ID::unique(), 'data' => [ - 'name' => 'Chris Evans' + 'name' => 'Chris Evans', ], 'permissions' => [ Permission::read(Role::any()), @@ -747,8 +744,8 @@ class RealtimeCustomClientTest extends Scope $this->assertArrayHasKey('timestamp', $response['data']); $this->assertCount(3, $response['data']['channels']); $this->assertContains('documents', $response['data']['channels']); - $this->assertContains('databases.' . $databaseId . '.collections.' . $actorsId . '.documents.' . $documentId, $response['data']['channels']); - $this->assertContains('databases.' . $databaseId . '.collections.' . $actorsId . '.documents', $response['data']['channels']); + $this->assertContains('databases.'.$databaseId.'.collections.'.$actorsId.'.documents.'.$documentId, $response['data']['channels']); + $this->assertContains('databases.'.$databaseId.'.collections.'.$actorsId.'.documents', $response['data']['channels']); $this->assertContains("databases.{$databaseId}.collections.{$actorsId}.documents.{$documentId}.create", $response['data']['events']); $this->assertContains("databases.{$databaseId}.collections.{$actorsId}.documents.{$documentId}", $response['data']['events']); $this->assertContains("databases.{$databaseId}.collections.{$actorsId}.documents.*.create", $response['data']['events']); @@ -760,20 +757,20 @@ class RealtimeCustomClientTest extends Scope $this->assertContains("databases.{$databaseId}.collections.*.documents.*", $response['data']['events']); $this->assertContains("databases.{$databaseId}.collections.*", $response['data']['events']); $this->assertContains("databases.{$databaseId}", $response['data']['events']); - $this->assertContains("databases.*", $response['data']['events']); + $this->assertContains('databases.*', $response['data']['events']); $this->assertNotEmpty($response['data']['payload']); $this->assertEquals($response['data']['payload']['name'], 'Chris Evans'); /** * Test Document Update */ - $document = $this->client->call(Client::METHOD_PATCH, '/databases/' . $databaseId . '/collections/' . $actorsId . '/documents/' . $documentId, array_merge([ + $document = $this->client->call(Client::METHOD_PATCH, '/databases/'.$databaseId.'/collections/'.$actorsId.'/documents/'.$documentId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'documentId' => ID::unique(), 'data' => [ - 'name' => 'Chris Evans 2' + 'name' => 'Chris Evans 2', ], 'permissions' => [ Permission::read(Role::any()), @@ -804,7 +801,7 @@ class RealtimeCustomClientTest extends Scope $this->assertContains("databases.{$databaseId}.collections.*.documents.*", $response['data']['events']); $this->assertContains("databases.{$databaseId}.collections.*", $response['data']['events']); $this->assertContains("databases.{$databaseId}", $response['data']['events']); - $this->assertContains("databases.*", $response['data']['events']); + $this->assertContains('databases.*', $response['data']['events']); $this->assertNotEmpty($response['data']['payload']); $this->assertEquals($response['data']['payload']['name'], 'Chris Evans 2'); @@ -812,13 +809,13 @@ class RealtimeCustomClientTest extends Scope /** * Test Document Delete */ - $document = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $actorsId . '/documents', array_merge([ + $document = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$actorsId.'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'documentId' => ID::unique(), 'data' => [ - 'name' => 'Bradley Cooper' + 'name' => 'Bradley Cooper', ], 'permissions' => [ Permission::read(Role::any()), @@ -831,7 +828,7 @@ class RealtimeCustomClientTest extends Scope $documentId = $document['body']['$id']; - $this->client->call(Client::METHOD_DELETE, '/databases/' . $databaseId . '/collections/' . $actorsId . '/documents/' . $documentId, array_merge([ + $this->client->call(Client::METHOD_DELETE, '/databases/'.$databaseId.'/collections/'.$actorsId.'/documents/'.$documentId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -858,7 +855,7 @@ class RealtimeCustomClientTest extends Scope $this->assertContains("databases.{$databaseId}.collections.*.documents.*", $response['data']['events']); $this->assertContains("databases.{$databaseId}.collections.*", $response['data']['events']); $this->assertContains("databases.{$databaseId}", $response['data']['events']); - $this->assertContains("databases.*", $response['data']['events']); + $this->assertContains('databases.*', $response['data']['events']); $this->assertNotEmpty($response['data']['payload']); $this->assertEquals($response['data']['payload']['name'], 'Bradley Cooper'); @@ -873,7 +870,7 @@ class RealtimeCustomClientTest extends Scope $client = $this->getWebsocket(['documents', 'collections'], [ 'origin' => 'http://localhost', - 'cookie' => 'a_session_' . $projectId . '=' . $session + 'cookie' => 'a_session_'.$projectId.'='.$session, ]); $response = json_decode($client->receive(), true); @@ -894,7 +891,7 @@ class RealtimeCustomClientTest extends Scope $database = $this->client->call(Client::METHOD_POST, '/databases', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'databaseId' => ID::unique(), 'name' => 'Actors DB', @@ -905,10 +902,10 @@ class RealtimeCustomClientTest extends Scope /** * Test Collection Create */ - $actors = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections', array_merge([ + $actors = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'collectionId' => ID::unique(), 'name' => 'Actors', @@ -917,15 +914,15 @@ class RealtimeCustomClientTest extends Scope Permission::create(Role::any()), Permission::update(Role::any()), Permission::delete(Role::any()), - ] + ], ]); $actorsId = $actors['body']['$id']; - $name = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $actorsId . '/attributes/string', array_merge([ + $name = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$actorsId.'/attributes/string', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'name', 'size' => 256, @@ -943,13 +940,13 @@ class RealtimeCustomClientTest extends Scope /** * Test Document Create */ - $document = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $actorsId . '/documents', array_merge([ + $document = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$actorsId.'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'documentId' => ID::unique(), 'data' => [ - 'name' => 'Chris Evans' + 'name' => 'Chris Evans', ], 'permissions' => [], ]); @@ -978,19 +975,19 @@ class RealtimeCustomClientTest extends Scope $this->assertContains("databases.{$databaseId}.collections.*.documents.*", $response['data']['events']); $this->assertContains("databases.{$databaseId}.collections.*", $response['data']['events']); $this->assertContains("databases.{$databaseId}", $response['data']['events']); - $this->assertContains("databases.*", $response['data']['events']); + $this->assertContains('databases.*', $response['data']['events']); $this->assertNotEmpty($response['data']['payload']); $this->assertEquals($response['data']['payload']['name'], 'Chris Evans'); /** * Test Document Update */ - $document = $this->client->call(Client::METHOD_PATCH, '/databases/' . $databaseId . '/collections/' . $actorsId . '/documents/' . $documentId, array_merge([ + $document = $this->client->call(Client::METHOD_PATCH, '/databases/'.$databaseId.'/collections/'.$actorsId.'/documents/'.$documentId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'data' => [ - 'name' => 'Chris Evans 2' + 'name' => 'Chris Evans 2', ], 'permissions' => [], ]); @@ -1017,7 +1014,7 @@ class RealtimeCustomClientTest extends Scope $this->assertContains("databases.{$databaseId}.collections.*.documents.*", $response['data']['events']); $this->assertContains("databases.{$databaseId}.collections.*", $response['data']['events']); $this->assertContains("databases.{$databaseId}", $response['data']['events']); - $this->assertContains("databases.*", $response['data']['events']); + $this->assertContains('databases.*', $response['data']['events']); $this->assertNotEmpty($response['data']['payload']); $this->assertEquals($response['data']['payload']['name'], 'Chris Evans 2'); @@ -1025,13 +1022,13 @@ class RealtimeCustomClientTest extends Scope /** * Test Document Delete */ - $document = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $actorsId . '/documents', array_merge([ + $document = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$actorsId.'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'documentId' => ID::unique(), 'data' => [ - 'name' => 'Bradley Cooper' + 'name' => 'Bradley Cooper', ], 'permissions' => [], ]); @@ -1040,7 +1037,7 @@ class RealtimeCustomClientTest extends Scope $client->receive(); - $this->client->call(Client::METHOD_DELETE, '/databases/' . $databaseId . '/collections/' . $actorsId . '/documents/' . $documentId, array_merge([ + $this->client->call(Client::METHOD_DELETE, '/databases/'.$databaseId.'/collections/'.$actorsId.'/documents/'.$documentId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -1067,7 +1064,7 @@ class RealtimeCustomClientTest extends Scope $this->assertContains("databases.{$databaseId}.collections.*.documents.*", $response['data']['events']); $this->assertContains("databases.{$databaseId}.collections.*", $response['data']['events']); $this->assertContains("databases.{$databaseId}", $response['data']['events']); - $this->assertContains("databases.*", $response['data']['events']); + $this->assertContains('databases.*', $response['data']['events']); $this->assertNotEmpty($response['data']['payload']); $this->assertEquals($response['data']['payload']['name'], 'Bradley Cooper'); @@ -1082,7 +1079,7 @@ class RealtimeCustomClientTest extends Scope $client = $this->getWebsocket(['files'], [ 'origin' => 'http://localhost', - 'cookie' => 'a_session_' . $projectId . '=' . $session + 'cookie' => 'a_session_'.$projectId.'='.$session, ]); $response = json_decode($client->receive(), true); @@ -1101,7 +1098,7 @@ class RealtimeCustomClientTest extends Scope $bucket1 = $this->client->call(Client::METHOD_POST, '/storage/buckets', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'bucketId' => ID::unique(), 'name' => 'Bucket 1', @@ -1110,7 +1107,7 @@ class RealtimeCustomClientTest extends Scope Permission::create(Role::any()), Permission::update(Role::any()), Permission::delete(Role::any()), - ] + ], ]); $bucketId = $bucket1['body']['$id']; @@ -1118,12 +1115,12 @@ class RealtimeCustomClientTest extends Scope /** * Test File Create */ - $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/' . $bucketId . '/files', array_merge([ + $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/'.$bucketId.'/files', array_merge([ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'fileId' => ID::unique(), - 'file' => new CURLFile(realpath(__DIR__ . '/../../../resources/logo.png'), 'image/png', 'logo.png'), + 'file' => new CURLFile(realpath(__DIR__.'/../../../resources/logo.png'), 'image/png', 'logo.png'), 'permissions' => [ Permission::read(Role::any()), Permission::update(Role::any()), @@ -1151,9 +1148,9 @@ class RealtimeCustomClientTest extends Scope $this->assertContains("buckets.{$bucketId}", $response['data']['events']); $this->assertContains("buckets.*.files.{$fileId}.create", $response['data']['events']); $this->assertContains("buckets.*.files.{$fileId}", $response['data']['events']); - $this->assertContains("buckets.*.files.*.create", $response['data']['events']); - $this->assertContains("buckets.*.files.*", $response['data']['events']); - $this->assertContains("buckets.*", $response['data']['events']); + $this->assertContains('buckets.*.files.*.create', $response['data']['events']); + $this->assertContains('buckets.*.files.*', $response['data']['events']); + $this->assertContains('buckets.*', $response['data']['events']); $this->assertNotEmpty($response['data']['payload']); $fileId = $file['body']['$id']; @@ -1161,7 +1158,7 @@ class RealtimeCustomClientTest extends Scope /** * Test File Update */ - $this->client->call(Client::METHOD_PUT, '/storage/buckets/' . $bucketId . '/files/' . $fileId, array_merge([ + $this->client->call(Client::METHOD_PUT, '/storage/buckets/'.$bucketId.'/files/'.$fileId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1190,15 +1187,15 @@ class RealtimeCustomClientTest extends Scope $this->assertContains("buckets.{$bucketId}", $response['data']['events']); $this->assertContains("buckets.*.files.{$fileId}.update", $response['data']['events']); $this->assertContains("buckets.*.files.{$fileId}", $response['data']['events']); - $this->assertContains("buckets.*.files.*.update", $response['data']['events']); - $this->assertContains("buckets.*.files.*", $response['data']['events']); - $this->assertContains("buckets.*", $response['data']['events']); + $this->assertContains('buckets.*.files.*.update', $response['data']['events']); + $this->assertContains('buckets.*.files.*', $response['data']['events']); + $this->assertContains('buckets.*', $response['data']['events']); $this->assertNotEmpty($response['data']['payload']); /** * Test File Delete */ - $this->client->call(Client::METHOD_DELETE, '/storage/buckets/' . $bucketId . '/files/' . $fileId, array_merge([ + $this->client->call(Client::METHOD_DELETE, '/storage/buckets/'.$bucketId.'/files/'.$fileId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -1221,9 +1218,9 @@ class RealtimeCustomClientTest extends Scope $this->assertContains("buckets.{$bucketId}", $response['data']['events']); $this->assertContains("buckets.*.files.{$fileId}.delete", $response['data']['events']); $this->assertContains("buckets.*.files.{$fileId}", $response['data']['events']); - $this->assertContains("buckets.*.files.*.delete", $response['data']['events']); - $this->assertContains("buckets.*.files.*", $response['data']['events']); - $this->assertContains("buckets.*", $response['data']['events']); + $this->assertContains('buckets.*.files.*.delete', $response['data']['events']); + $this->assertContains('buckets.*.files.*', $response['data']['events']); + $this->assertContains('buckets.*', $response['data']['events']); $this->assertNotEmpty($response['data']['payload']); $client->close(); @@ -1237,7 +1234,7 @@ class RealtimeCustomClientTest extends Scope $client = $this->getWebsocket(['executions'], [ 'origin' => 'http://localhost', - 'cookie' => 'a_session_' . $projectId . '=' . $session + 'cookie' => 'a_session_'.$projectId.'='.$session, ]); $response = json_decode($client->receive(), true); @@ -1257,7 +1254,7 @@ class RealtimeCustomClientTest extends Scope $function = $this->client->call(Client::METHOD_POST, '/functions', [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ], [ 'functionId' => ID::unique(), 'name' => 'Test', @@ -1274,17 +1271,17 @@ class RealtimeCustomClientTest extends Scope $folder = 'timeout'; $stderr = ''; $stdout = ''; - $code = realpath(__DIR__ . '/../../../resources/functions') . "/{$folder}/code.tar.gz"; + $code = realpath(__DIR__.'/../../../resources/functions')."/{$folder}/code.tar.gz"; - Console::execute('cd ' . realpath(__DIR__ . "/../../../resources/functions") . "/{$folder} && tar --exclude code.tar.gz -czf code.tar.gz .", '', $stdout, $stderr); + Console::execute('cd '.realpath(__DIR__.'/../../../resources/functions')."/{$folder} && tar --exclude code.tar.gz -czf code.tar.gz .", '', $stdout, $stderr); - $deployment = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/deployments', array_merge([ + $deployment = $this->client->call(Client::METHOD_POST, '/functions/'.$functionId.'/deployments', array_merge([ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'entrypoint' => 'index.php', - 'code' => new CURLFile($code, 'application/x-gzip', basename($code)) + 'code' => new CURLFile($code, 'application/x-gzip', basename($code)), ]); $deploymentId = $deployment['body']['$id'] ?? ''; @@ -1295,20 +1292,20 @@ class RealtimeCustomClientTest extends Scope // Wait for deployment to be built. sleep(5); - $response = $this->client->call(Client::METHOD_PATCH, '/functions/' . $functionId . '/deployments/' . $deploymentId, array_merge([ + $response = $this->client->call(Client::METHOD_PATCH, '/functions/'.$functionId.'/deployments/'.$deploymentId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), []); $this->assertEquals($response['headers']['status-code'], 200); $this->assertNotEmpty($response['body']['$id']); - $execution = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/executions', array_merge([ + $execution = $this->client->call(Client::METHOD_POST, '/functions/'.$functionId.'/executions', array_merge([ 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'] + 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'async' => true + 'async' => true, ]); $this->assertEquals($execution['headers']['status-code'], 202); @@ -1336,9 +1333,9 @@ class RealtimeCustomClientTest extends Scope $this->assertContains("functions.{$functionId}", $response['data']['events']); $this->assertContains("functions.*.executions.{$executionId}.create", $response['data']['events']); $this->assertContains("functions.*.executions.{$executionId}", $response['data']['events']); - $this->assertContains("functions.*.executions.*.create", $response['data']['events']); - $this->assertContains("functions.*.executions.*", $response['data']['events']); - $this->assertContains("functions.*", $response['data']['events']); + $this->assertContains('functions.*.executions.*.create', $response['data']['events']); + $this->assertContains('functions.*.executions.*', $response['data']['events']); + $this->assertContains('functions.*', $response['data']['events']); $this->assertNotEmpty($response['data']['payload']); $this->assertArrayHasKey('type', $responseUpdate); @@ -1358,15 +1355,15 @@ class RealtimeCustomClientTest extends Scope $this->assertContains("functions.{$functionId}", $responseUpdate['data']['events']); $this->assertContains("functions.*.executions.{$executionId}.update", $responseUpdate['data']['events']); $this->assertContains("functions.*.executions.{$executionId}", $responseUpdate['data']['events']); - $this->assertContains("functions.*.executions.*.update", $responseUpdate['data']['events']); - $this->assertContains("functions.*.executions.*", $responseUpdate['data']['events']); - $this->assertContains("functions.*", $responseUpdate['data']['events']); + $this->assertContains('functions.*.executions.*.update', $responseUpdate['data']['events']); + $this->assertContains('functions.*.executions.*', $responseUpdate['data']['events']); + $this->assertContains('functions.*', $responseUpdate['data']['events']); $this->assertNotEmpty($responseUpdate['data']['payload']); $client->close(); // Cleanup : Delete function - $response = $this->client->call(Client::METHOD_DELETE, '/functions/' . $functionId, [ + $response = $this->client->call(Client::METHOD_DELETE, '/functions/'.$functionId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], 'x-appwrite-key' => $this->getProject()['apiKey'], @@ -1383,7 +1380,7 @@ class RealtimeCustomClientTest extends Scope $client = $this->getWebsocket(['teams'], [ 'origin' => 'http://localhost', - 'cookie' => 'a_session_' . $projectId . '=' . $session + 'cookie' => 'a_session_'.$projectId.'='.$session, ]); $response = json_decode($client->receive(), true); @@ -1405,7 +1402,7 @@ class RealtimeCustomClientTest extends Scope 'x-appwrite-project' => $projectId, ], $this->getHeaders()), [ 'teamId' => ID::unique(), - 'name' => 'Arsenal' + 'name' => 'Arsenal', ]); $teamId = $team['body']['$id'] ?? ''; @@ -1425,18 +1422,18 @@ class RealtimeCustomClientTest extends Scope $this->assertContains("teams.{$teamId}", $response['data']['channels']); $this->assertContains("teams.{$teamId}.create", $response['data']['events']); $this->assertContains("teams.{$teamId}", $response['data']['events']); - $this->assertContains("teams.*.create", $response['data']['events']); - $this->assertContains("teams.*", $response['data']['events']); + $this->assertContains('teams.*.create', $response['data']['events']); + $this->assertContains('teams.*', $response['data']['events']); $this->assertNotEmpty($response['data']['payload']); /** * Test Team Update */ - $team = $this->client->call(Client::METHOD_PUT, '/teams/' . $teamId, array_merge([ + $team = $this->client->call(Client::METHOD_PUT, '/teams/'.$teamId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $projectId, ], $this->getHeaders()), [ - 'name' => 'Manchester' + 'name' => 'Manchester', ]); $this->assertEquals($team['headers']['status-code'], 200); @@ -1454,8 +1451,8 @@ class RealtimeCustomClientTest extends Scope $this->assertContains("teams.{$teamId}", $response['data']['channels']); $this->assertContains("teams.{$teamId}.update", $response['data']['events']); $this->assertContains("teams.{$teamId}", $response['data']['events']); - $this->assertContains("teams.*.update", $response['data']['events']); - $this->assertContains("teams.*", $response['data']['events']); + $this->assertContains('teams.*.update', $response['data']['events']); + $this->assertContains('teams.*', $response['data']['events']); $this->assertNotEmpty($response['data']['payload']); $client->close(); @@ -1476,7 +1473,7 @@ class RealtimeCustomClientTest extends Scope $client = $this->getWebsocket(['memberships'], [ 'origin' => 'http://localhost', - 'cookie' => 'a_session_' . $projectId . '=' . $session + 'cookie' => 'a_session_'.$projectId.'='.$session, ]); $response = json_decode($client->receive(), true); @@ -1490,7 +1487,7 @@ class RealtimeCustomClientTest extends Scope $this->assertNotEmpty($response['data']['user']); $this->assertEquals($user['$id'], $response['data']['user']['$id']); - $response = $this->client->call(Client::METHOD_GET, '/teams/' . $teamId . '/memberships', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/teams/'.$teamId.'/memberships', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -1501,12 +1498,12 @@ class RealtimeCustomClientTest extends Scope * Test Update Membership */ $roles = ['admin', 'editor', 'uncle']; - $this->client->call(Client::METHOD_PATCH, '/teams/' . $teamId . '/memberships/' . $membershipId, array_merge([ + $this->client->call(Client::METHOD_PATCH, '/teams/'.$teamId.'/memberships/'.$membershipId, array_merge([ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'roles' => $roles + 'roles' => $roles, ]); $response = json_decode($client->receive(), true); @@ -1526,9 +1523,9 @@ class RealtimeCustomClientTest extends Scope $this->assertContains("teams.{$teamId}", $response['data']['events']); $this->assertContains("teams.*.memberships.{$membershipId}.update", $response['data']['events']); $this->assertContains("teams.*.memberships.{$membershipId}", $response['data']['events']); - $this->assertContains("teams.*.memberships.*.update", $response['data']['events']); - $this->assertContains("teams.*.memberships.*", $response['data']['events']); - $this->assertContains("teams.*", $response['data']['events']); + $this->assertContains('teams.*.memberships.*.update', $response['data']['events']); + $this->assertContains('teams.*.memberships.*', $response['data']['events']); + $this->assertContains('teams.*', $response['data']['events']); $this->assertNotEmpty($response['data']['payload']); $client->close(); diff --git a/tests/e2e/Services/Storage/StorageBase.php b/tests/e2e/Services/Storage/StorageBase.php index 72d3a99537..2b952731ca 100644 --- a/tests/e2e/Services/Storage/StorageBase.php +++ b/tests/e2e/Services/Storage/StorageBase.php @@ -25,7 +25,7 @@ trait StorageBase 'name' => 'Test Bucket', 'fileSecurity' => true, 'maximumFileSize' => 2000000, //2MB - 'allowedFileExtensions' => ["jpg", "png"], + 'allowedFileExtensions' => ['jpg', 'png'], 'permissions' => [ Permission::read(Role::any()), Permission::create(Role::any()), @@ -38,12 +38,12 @@ trait StorageBase $bucketId = $bucket['body']['$id']; - $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/' . $bucketId . '/files', array_merge([ + $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/'.$bucketId.'/files', array_merge([ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'fileId' => ID::unique(), - 'file' => new CURLFile(realpath(__DIR__ . '/../../../resources/logo.png'), 'image/png', 'logo.png'), + 'file' => new CURLFile(realpath(__DIR__.'/../../../resources/logo.png'), 'image/png', 'logo.png'), 'permissions' => [ Permission::read(Role::any()), Permission::update(Role::any()), @@ -57,7 +57,7 @@ trait StorageBase $this->assertEquals('logo.png', $file['body']['name']); $this->assertEquals('image/png', $file['body']['mimeType']); $this->assertEquals(47218, $file['body']['sizeOriginal']); - $this->assertTrue(md5_file(realpath(__DIR__ . '/../../../resources/logo.png')) != $file['body']['signature']); // should validate that the file is encrypted + $this->assertTrue(md5_file(realpath(__DIR__.'/../../../resources/logo.png')) != $file['body']['signature']); // should validate that the file is encrypted /** * Test for Large File above 20MB @@ -85,27 +85,26 @@ trait StorageBase /** * Chunked Upload */ - - $source = __DIR__ . "/../../../resources/disk-a/large-file.mp4"; + $source = __DIR__.'/../../../resources/disk-a/large-file.mp4'; $totalSize = \filesize($source); $chunkSize = 5 * 1024 * 1024; - $handle = @fopen($source, "rb"); + $handle = @fopen($source, 'rb'); $fileId = 'unique()'; $mimeType = mime_content_type($source); $counter = 0; $size = filesize($source); $headers = [ 'content-type' => 'multipart/form-data', - 'x-appwrite-project' => $this->getProject()['$id'] + 'x-appwrite-project' => $this->getProject()['$id'], ]; $id = ''; - while (!feof($handle)) { - $curlFile = new \CURLFile('data://' . $mimeType . ';base64,' . base64_encode(@fread($handle, $chunkSize)), $mimeType, 'large-file.mp4'); - $headers['content-range'] = 'bytes ' . ($counter * $chunkSize) . '-' . min(((($counter * $chunkSize) + $chunkSize) - 1), $size) . '/' . $size; - if (!empty($id)) { + while (! feof($handle)) { + $curlFile = new \CURLFile('data://'.$mimeType.';base64,'.base64_encode(@fread($handle, $chunkSize)), $mimeType, 'large-file.mp4'); + $headers['content-range'] = 'bytes '.($counter * $chunkSize).'-'.min(((($counter * $chunkSize) + $chunkSize) - 1), $size).'/'.$size; + if (! empty($id)) { $headers['x-appwrite-id'] = $id; } - $largeFile = $this->client->call(Client::METHOD_POST, '/storage/buckets/' . $bucket2['body']['$id'] . '/files', array_merge($headers, $this->getHeaders()), [ + $largeFile = $this->client->call(Client::METHOD_POST, '/storage/buckets/'.$bucket2['body']['$id'].'/files', array_merge($headers, $this->getHeaders()), [ 'fileId' => $fileId, 'file' => $curlFile, 'permissions' => [ @@ -125,28 +124,28 @@ trait StorageBase $this->assertEquals('large-file.mp4', $largeFile['body']['name']); $this->assertEquals('video/mp4', $largeFile['body']['mimeType']); $this->assertEquals($totalSize, $largeFile['body']['sizeOriginal']); - $this->assertEquals(md5_file(realpath(__DIR__ . '/../../../resources/disk-a/large-file.mp4')), $largeFile['body']['signature']); // should validate that the file is not encrypted + $this->assertEquals(md5_file(realpath(__DIR__.'/../../../resources/disk-a/large-file.mp4')), $largeFile['body']['signature']); // should validate that the file is not encrypted /** * Failure * Test for Chunk above 5MB */ - $source = __DIR__ . "/../../../resources/disk-a/large-file.mp4"; + $source = __DIR__.'/../../../resources/disk-a/large-file.mp4'; $totalSize = \filesize($source); $chunkSize = 6 * 1024 * 1024; - $handle = @fopen($source, "rb"); + $handle = @fopen($source, 'rb'); $fileId = 'unique()'; $mimeType = mime_content_type($source); $counter = 0; $size = filesize($source); $headers = [ 'content-type' => 'multipart/form-data', - 'x-appwrite-project' => $this->getProject()['$id'] + 'x-appwrite-project' => $this->getProject()['$id'], ]; $id = ''; - $curlFile = new \CURLFile('data://' . $mimeType . ';base64,' . base64_encode(@fread($handle, $chunkSize)), $mimeType, 'large-file.mp4'); - $headers['content-range'] = 'bytes ' . ($counter * $chunkSize) . '-' . min(((($counter * $chunkSize) + $chunkSize) - 1), $size) . '/' . $size; - $res = $this->client->call(Client::METHOD_POST, '/storage/buckets/' . $bucket2['body']['$id'] . '/files', $this->getHeaders(), [ + $curlFile = new \CURLFile('data://'.$mimeType.';base64,'.base64_encode(@fread($handle, $chunkSize)), $mimeType, 'large-file.mp4'); + $headers['content-range'] = 'bytes '.($counter * $chunkSize).'-'.min(((($counter * $chunkSize) + $chunkSize) - 1), $size).'/'.$size; + $res = $this->client->call(Client::METHOD_POST, '/storage/buckets/'.$bucket2['body']['$id'].'/files', $this->getHeaders(), [ 'fileId' => $fileId, 'file' => $curlFile, 'permissions' => [ @@ -159,17 +158,15 @@ trait StorageBase $this->assertEquals(413, $res['headers']['status-code']); - /** * Test for FAILURE unknown Bucket */ - $res = $this->client->call(Client::METHOD_POST, '/storage/buckets/empty/files', array_merge([ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'fileId' => ID::unique(), - 'file' => new CURLFile(realpath(__DIR__ . '/../../../resources/logo.png'), 'image/png', 'logo.png'), + 'file' => new CURLFile(realpath(__DIR__.'/../../../resources/logo.png'), 'image/png', 'logo.png'), 'permissions' => [ Permission::read(Role::any()), Permission::update(Role::any()), @@ -181,13 +178,12 @@ trait StorageBase /** * Test for FAILURE file above bucket's file size limit */ - - $res = $this->client->call(Client::METHOD_POST, '/storage/buckets/' . $bucketId . '/files', array_merge([ + $res = $this->client->call(Client::METHOD_POST, '/storage/buckets/'.$bucketId.'/files', array_merge([ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'fileId' => ID::unique(), - 'file' => new CURLFile(realpath(__DIR__ . '/../../../resources/disk-b/kitten-1.png'), 'image/png', 'kitten-1.png'), + 'file' => new CURLFile(realpath(__DIR__.'/../../../resources/disk-b/kitten-1.png'), 'image/png', 'kitten-1.png'), 'permissions' => [ Permission::read(Role::any()), Permission::update(Role::any()), @@ -201,13 +197,12 @@ trait StorageBase /** * Test for FAILURE unsupported bucket file extension */ - - $res = $this->client->call(Client::METHOD_POST, '/storage/buckets/' . $bucketId . '/files', array_merge([ + $res = $this->client->call(Client::METHOD_POST, '/storage/buckets/'.$bucketId.'/files', array_merge([ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'fileId' => ID::unique(), - 'file' => new CURLFile(realpath(__DIR__ . '/../../../resources/disk-a/kitten-3.gif'), 'image/gif', 'kitten-3.gif'), + 'file' => new CURLFile(realpath(__DIR__.'/../../../resources/disk-a/kitten-3.gif'), 'image/gif', 'kitten-3.gif'), 'permissions' => [ Permission::read(Role::any()), Permission::update(Role::any()), @@ -230,7 +225,7 @@ trait StorageBase 'name' => 'Test Bucket 2', 'fileSecurity' => true, 'maximumFileSize' => 200000000, //200MB - 'allowedFileExtensions' => ["jpg", "png"], + 'allowedFileExtensions' => ['jpg', 'png'], 'permissions' => [ Permission::read(Role::any()), Permission::create(Role::any()), @@ -255,7 +250,7 @@ trait StorageBase 'name' => 'Test Bucket', 'fileSecurity' => true, 'maximumFileSize' => 2000000, //2MB - 'allowedFileExtensions' => ["jpg", "png"], + 'allowedFileExtensions' => ['jpg', 'png'], 'compression' => 'zstd', 'permissions' => [ Permission::read(Role::any()), @@ -270,12 +265,12 @@ trait StorageBase $bucketId = $bucket['body']['$id']; - $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/' . $bucketId . '/files', array_merge([ + $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/'.$bucketId.'/files', array_merge([ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'fileId' => ID::unique(), - 'file' => new CURLFile(realpath(__DIR__ . '/../../../resources/logo.png'), 'image/png', 'logo.png'), + 'file' => new CURLFile(realpath(__DIR__.'/../../../resources/logo.png'), 'image/png', 'logo.png'), 'permissions' => [ Permission::read(Role::any()), Permission::update(Role::any()), @@ -289,7 +284,7 @@ trait StorageBase $this->assertEquals('logo.png', $file['body']['name']); $this->assertEquals('image/png', $file['body']['mimeType']); $this->assertEquals(47218, $file['body']['sizeOriginal']); - $this->assertTrue(md5_file(realpath(__DIR__ . '/../../../resources/logo.png')) != $file['body']['signature']); // should validate that the file is encrypted + $this->assertTrue(md5_file(realpath(__DIR__.'/../../../resources/logo.png')) != $file['body']['signature']); // should validate that the file is encrypted return ['bucketId' => $bucketId]; } @@ -302,7 +297,7 @@ trait StorageBase /** * Test for SUCCESS */ - $files = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $data['bucketId'] . '/files', array_merge([ + $files = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$data['bucketId'].'/files', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -310,38 +305,38 @@ trait StorageBase $this->assertGreaterThan(0, $files['body']['total']); $this->assertGreaterThan(0, count($files['body']['files'])); - $files = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $data['bucketId'] . '/files', array_merge([ + $files = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$data['bucketId'].'/files', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'limit(0)' ] + 'queries' => ['limit(0)'], ]); $this->assertEquals(200, $files['headers']['status-code']); $this->assertEquals(0, count($files['body']['files'])); - $files = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $data['bucketId'] . '/files', array_merge([ + $files = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$data['bucketId'].'/files', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'offset(1)' ] + 'queries' => ['offset(1)'], ]); $this->assertEquals(200, $files['headers']['status-code']); $this->assertEquals(0, count($files['body']['files'])); - $files = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $data['bucketId'] . '/files', array_merge([ + $files = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$data['bucketId'].'/files', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'equal("mimeType", "image/png")' ] + 'queries' => ['equal("mimeType", "image/png")'], ]); $this->assertEquals(200, $files['headers']['status-code']); $this->assertEquals(1, count($files['body']['files'])); - $files = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $data['bucketId'] . '/files', array_merge([ + $files = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$data['bucketId'].'/files', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'equal("mimeType", "image/jpeg")' ] + 'queries' => ['equal("mimeType", "image/jpeg")'], ]); $this->assertEquals(200, $files['headers']['status-code']); $this->assertEquals(0, count($files['body']['files'])); @@ -349,7 +344,6 @@ trait StorageBase /** * Test for FAILURE unknown Bucket */ - $files = $this->client->call(Client::METHOD_GET, '/storage/buckets/empty/files', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], @@ -368,7 +362,7 @@ trait StorageBase /** * Test for SUCCESS */ - $file1 = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $data['fileId'], array_merge([ + $file1 = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$data['fileId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -383,7 +377,7 @@ trait StorageBase $this->assertIsArray($file1['body']['$permissions']); $this->assertCount(3, $file1['body']['$permissions']); - $file2 = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $data['fileId'] . '/preview', array_merge([ + $file2 = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$data['fileId'].'/preview', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -393,7 +387,7 @@ trait StorageBase $this->assertNotEmpty($file2['body']); //new image preview features - $file3 = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $data['fileId'] . '/preview', array_merge([ + $file3 = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$data['fileId'].'/preview', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -411,13 +405,13 @@ trait StorageBase $image = new \Imagick(); $image->readImageBlob($file3['body']); - $original = new \Imagick(__DIR__ . '/../../../resources/logo-after.png'); + $original = new \Imagick(__DIR__.'/../../../resources/logo-after.png'); $this->assertEquals($image->getImageWidth(), $original->getImageWidth()); $this->assertEquals($image->getImageHeight(), $original->getImageHeight()); $this->assertEquals('PNG', $image->getImageFormat()); - $file4 = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $data['fileId'] . '/preview', array_merge([ + $file4 = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$data['fileId'].'/preview', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -434,13 +428,13 @@ trait StorageBase $image = new \Imagick(); $image->readImageBlob($file4['body']); - $original = new \Imagick(__DIR__ . '/../../../resources/logo-after.jpg'); + $original = new \Imagick(__DIR__.'/../../../resources/logo-after.jpg'); $this->assertEquals($image->getImageWidth(), $original->getImageWidth()); $this->assertEquals($image->getImageHeight(), $original->getImageHeight()); $this->assertEquals('JPEG', $image->getImageFormat()); - $file5 = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $data['fileId'] . '/download', array_merge([ + $file5 = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$data['fileId'].'/download', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -451,13 +445,13 @@ trait StorageBase $this->assertNotEmpty($file5['body']); // Test ranged download - $file51 = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $data['fileId'] . '/download', array_merge([ + $file51 = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$data['fileId'].'/download', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], 'Range' => 'bytes=0-99', ], $this->getHeaders())); - $path = __DIR__ . '/../../../resources/logo.png'; + $path = __DIR__.'/../../../resources/logo.png'; $originalChunk = \file_get_contents($path, false, null, 0, 100); $this->assertEquals(206, $file51['headers']['status-code']); @@ -467,7 +461,7 @@ trait StorageBase $this->assertEquals($originalChunk, $file51['body']); // Test ranged download - with invalid range - $file52 = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $data['fileId'] . '/download', array_merge([ + $file52 = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$data['fileId'].'/download', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], 'Range' => 'bytes=0-', @@ -476,7 +470,7 @@ trait StorageBase $this->assertEquals(206, $file52['headers']['status-code']); // Test ranged download - with invalid range - $file53 = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $data['fileId'] . '/download', array_merge([ + $file53 = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$data['fileId'].'/download', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], 'Range' => 'bytes=988', @@ -485,7 +479,7 @@ trait StorageBase $this->assertEquals(416, $file53['headers']['status-code']); // Test ranged download - with invalid range - $file54 = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $data['fileId'] . '/download', array_merge([ + $file54 = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$data['fileId'].'/download', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], 'Range' => 'bytes=-988', @@ -493,7 +487,7 @@ trait StorageBase $this->assertEquals(416, $file54['headers']['status-code']); - $file6 = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $data['fileId'] . '/view', array_merge([ + $file6 = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$data['fileId'].'/view', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -503,7 +497,7 @@ trait StorageBase $this->assertNotEmpty($file6['body']); // Test for negative angle values in fileGetPreview - $file7 = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $data['fileId'] . '/preview', array_merge([ + $file7 = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$data['fileId'].'/preview', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -521,7 +515,7 @@ trait StorageBase $image = new \Imagick(); $image->readImageBlob($file7['body']); - $original = new \Imagick(__DIR__ . '/../../../resources/logo-after.png'); + $original = new \Imagick(__DIR__.'/../../../resources/logo-after.png'); $this->assertEquals($image->getImageWidth(), $original->getImageWidth()); $this->assertEquals($image->getImageHeight(), $original->getImageHeight()); @@ -530,7 +524,7 @@ trait StorageBase /** * Test large files decompress successfully */ - $file7 = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $data['largeBucketId'] . '/files/' . $data['largeFileId'] . '/download', array_merge([ + $file7 = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$data['largeBucketId'].'/files/'.$data['largeFileId'].'/download', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -539,17 +533,16 @@ trait StorageBase $this->assertEquals('attachment; filename="large-file.mp4"', $file7['headers']['content-disposition']); $this->assertEquals('video/mp4', $file7['headers']['content-type']); $this->assertNotEmpty($fileData); - $this->assertEquals(md5_file(realpath(__DIR__ . '/../../../resources/disk-a/large-file.mp4')), md5($fileData)); // validate the file is downloaded correctly + $this->assertEquals(md5_file(realpath(__DIR__.'/../../../resources/disk-a/large-file.mp4')), md5($fileData)); // validate the file is downloaded correctly /** * Test for FAILURE unknown Bucket */ - - $file8 = $this->client->call(Client::METHOD_GET, '/storage/buckets/empty/files/' . $data['fileId'], array_merge([ + $file8 = $this->client->call(Client::METHOD_GET, '/storage/buckets/empty/files/'.$data['fileId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'limit' => 2 + 'limit' => 2, ]); $this->assertEquals(404, $file8['headers']['status-code']); @@ -564,12 +557,12 @@ trait StorageBase { $bucketId = $data['bucketId']; - $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/' . $bucketId . '/files', array_merge([ + $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/'.$bucketId.'/files', array_merge([ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'fileId' => ID::custom('testcache'), - 'file' => new CURLFile(realpath(__DIR__ . '/../../../resources/logo.png'), 'image/png', 'logo.png'), + 'file' => new CURLFile(realpath(__DIR__.'/../../../resources/logo.png'), 'image/png', 'logo.png'), 'permissions' => [ Permission::read(Role::any()), Permission::update(Role::any()), @@ -582,7 +575,7 @@ trait StorageBase $fileId = $file['body']['$id']; //get image preview - $file3 = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId . '/preview', array_merge([ + $file3 = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId.'/preview', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -601,7 +594,7 @@ trait StorageBase $imageBefore = new \Imagick(); $imageBefore->readImageBlob($file3['body']); - $file = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/' . $data['bucketId'] . '/files/' . $fileId, array_merge([ + $file = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/'.$data['bucketId'].'/files/'.$fileId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -610,12 +603,12 @@ trait StorageBase $this->assertEmpty($file['body']); sleep(1); //upload again using the same ID - $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/' . $bucketId . '/files', array_merge([ + $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/'.$bucketId.'/files', array_merge([ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'fileId' => ID::custom('testcache'), - 'file' => new CURLFile(realpath(__DIR__ . '/../../../resources/disk-b/kitten-2.png'), 'image/png', 'logo.png'), + 'file' => new CURLFile(realpath(__DIR__.'/../../../resources/disk-b/kitten-2.png'), 'image/png', 'logo.png'), 'permissions' => [ Permission::read(Role::any()), Permission::update(Role::any()), @@ -626,7 +619,7 @@ trait StorageBase $this->assertNotEmpty($file['body']['$id']); //get image preview after - $file3 = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId . '/preview', array_merge([ + $file3 = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId.'/preview', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -657,12 +650,12 @@ trait StorageBase { $bucketId = $data['bucketId']; - $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/' . $bucketId . '/files', array_merge([ + $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/'.$bucketId.'/files', array_merge([ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'fileId' => ID::unique(), - 'file' => new CURLFile(realpath(__DIR__ . '/../../../resources/logo.png'), 'image/png', 'logo.png'), + 'file' => new CURLFile(realpath(__DIR__.'/../../../resources/logo.png'), 'image/png', 'logo.png'), 'permissions' => [ Permission::read(Role::any()), Permission::update(Role::any()), @@ -675,7 +668,7 @@ trait StorageBase $fileId = $file['body']['$id']; //get image preview - $file3 = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId . '/preview', array_merge([ + $file3 = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId.'/preview', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -702,7 +695,7 @@ trait StorageBase /** * Test for SUCCESS */ - $file = $this->client->call(Client::METHOD_PUT, '/storage/buckets/' . $data['bucketId'] . '/files/' . $data['fileId'], array_merge([ + $file = $this->client->call(Client::METHOD_PUT, '/storage/buckets/'.$data['bucketId'].'/files/'.$data['fileId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -710,7 +703,7 @@ trait StorageBase Permission::read(Role::user($this->getUser()['$id'])), Permission::update(Role::user($this->getUser()['$id'])), Permission::delete(Role::user($this->getUser()['$id'])), - ] + ], ]); $this->assertEquals(200, $file['headers']['status-code']); @@ -732,8 +725,7 @@ trait StorageBase /** * Test for FAILURE unknown Bucket */ - - $file = $this->client->call(Client::METHOD_PUT, '/storage/buckets/empty/files/' . $data['fileId'], array_merge([ + $file = $this->client->call(Client::METHOD_PUT, '/storage/buckets/empty/files/'.$data['fileId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -741,7 +733,7 @@ trait StorageBase Permission::read(Role::user($this->getUser()['$id'])), Permission::update(Role::user($this->getUser()['$id'])), Permission::delete(Role::user($this->getUser()['$id'])), - ] + ], ]); $this->assertEquals(404, $file['headers']['status-code']); @@ -757,7 +749,7 @@ trait StorageBase /** * Test for SUCCESS */ - $file = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/' . $data['bucketId'] . '/files/' . $data['fileId'], array_merge([ + $file = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/'.$data['bucketId'].'/files/'.$data['fileId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -765,7 +757,7 @@ trait StorageBase $this->assertEquals(204, $file['headers']['status-code']); $this->assertEmpty($file['body']); - $file = $this->client->call(Client::METHOD_GET, '/storage/files/' . $data['fileId'], array_merge([ + $file = $this->client->call(Client::METHOD_GET, '/storage/files/'.$data['fileId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); diff --git a/tests/e2e/Services/Storage/StorageConsoleClientTest.php b/tests/e2e/Services/Storage/StorageConsoleClientTest.php index 8fda8e0464..5c23b80c02 100644 --- a/tests/e2e/Services/Storage/StorageConsoleClientTest.php +++ b/tests/e2e/Services/Storage/StorageConsoleClientTest.php @@ -3,8 +3,8 @@ namespace Tests\E2E\Services\Storage; use Tests\E2E\Client; -use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\ProjectCustom; +use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\SideConsole; use Utopia\Database\Helpers\ID; @@ -21,9 +21,9 @@ class StorageConsoleClientTest extends Scope */ $response = $this->client->call(Client::METHOD_GET, '/storage/usage', array_merge([ 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'] + 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'range' => '32h' + 'range' => '32h', ]); $this->assertEquals($response['headers']['status-code'], 400); @@ -33,9 +33,9 @@ class StorageConsoleClientTest extends Scope */ $response = $this->client->call(Client::METHOD_GET, '/storage/usage', array_merge([ 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'] + 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'range' => '24h' + 'range' => '24h', ]); $this->assertEquals($response['headers']['status-code'], 200); @@ -54,7 +54,7 @@ class StorageConsoleClientTest extends Scope ], $this->getHeaders()), [ 'bucketId' => ID::unique(), 'name' => 'Test Bucket', - 'permission' => 'file' + 'permission' => 'file', ]); $this->assertEquals(201, $bucket['headers']['status-code']); $bucketId = $bucket['body']['$id']; @@ -62,12 +62,11 @@ class StorageConsoleClientTest extends Scope /** * Test for FAILURE */ - - $response = $this->client->call(Client::METHOD_GET, '/storage/' . $bucketId . '/usage', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/storage/'.$bucketId.'/usage', array_merge([ 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'] + 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'range' => '32h' + 'range' => '32h', ]); $this->assertEquals($response['headers']['status-code'], 400); @@ -76,9 +75,9 @@ class StorageConsoleClientTest extends Scope $response = $this->client->call(Client::METHOD_GET, '/storage/randomBucketId/usage', array_merge([ 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'] + 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'range' => '24h' + 'range' => '24h', ]); $this->assertEquals($response['headers']['status-code'], 404); @@ -86,11 +85,11 @@ class StorageConsoleClientTest extends Scope /** * Test for SUCCESS */ - $response = $this->client->call(Client::METHOD_GET, '/storage/' . $bucketId . '/usage', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/storage/'.$bucketId.'/usage', array_merge([ 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'] + 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'range' => '24h' + 'range' => '24h', ]); $this->assertEquals($response['headers']['status-code'], 200); diff --git a/tests/e2e/Services/Storage/StorageCustomClientTest.php b/tests/e2e/Services/Storage/StorageCustomClientTest.php index 46ef1d6986..05afa0ebe2 100644 --- a/tests/e2e/Services/Storage/StorageCustomClientTest.php +++ b/tests/e2e/Services/Storage/StorageCustomClientTest.php @@ -4,8 +4,8 @@ namespace Tests\E2E\Services\Storage; use CURLFile; use Tests\E2E\Client; -use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\ProjectCustom; +use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\SideClient; use Utopia\Database\Helpers\ID; use Utopia\Database\Helpers\Permission; @@ -45,13 +45,13 @@ class StorageCustomClientTest extends Scope $this->assertEquals(201, $bucket['headers']['status-code']); $this->assertNotEmpty($bucketId); - $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/' . $bucketId . '/files', array_merge([ + $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/'.$bucketId.'/files', array_merge([ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'fileId' => ID::unique(), - 'file' => new CURLFile(realpath(__DIR__ . '/../../../resources/logo.png'), 'image/png', 'permissions.png'), + 'file' => new CURLFile(realpath(__DIR__.'/../../../resources/logo.png'), 'image/png', 'permissions.png'), ]); $fileId = $file['body']['$id']; @@ -63,14 +63,14 @@ class StorageCustomClientTest extends Scope $this->assertEquals('image/png', $file['body']['mimeType']); $this->assertEquals(47218, $file['body']['sizeOriginal']); - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId . '/preview', array_merge([ + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId.'/preview', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); $this->assertEquals(404, $file['headers']['status-code']); - $file = $this->client->call(Client::METHOD_PUT, '/storage/buckets/' . $bucketId . '/files/' . $fileId, [ + $file = $this->client->call(Client::METHOD_PUT, '/storage/buckets/'.$bucketId.'/files/'.$fileId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], 'x-appwrite-key' => $this->getProject()['apiKey'], @@ -83,14 +83,14 @@ class StorageCustomClientTest extends Scope $this->assertEquals(200, $file['headers']['status-code']); - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId . '/preview', array_merge([ + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId.'/preview', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); $this->assertEquals(200, $file['headers']['status-code']); - $file = $this->client->call(Client::METHOD_PUT, '/storage/buckets/' . $bucketId . '/files/' . $fileId, [ + $file = $this->client->call(Client::METHOD_PUT, '/storage/buckets/'.$bucketId.'/files/'.$fileId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], 'x-appwrite-key' => $this->getProject()['apiKey'], @@ -101,14 +101,14 @@ class StorageCustomClientTest extends Scope $this->assertEquals(200, $file['headers']['status-code']); - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId . '/preview', array_merge([ + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId.'/preview', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); $this->assertEquals(404, $file['headers']['status-code']); - $file = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/' . $bucketId . '/files/' . $fileId, [ + $file = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/'.$bucketId.'/files/'.$fileId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], 'x-appwrite-key' => $this->getProject()['apiKey'], @@ -120,35 +120,34 @@ class StorageCustomClientTest extends Scope public function testBucketAnyPermissions(): void { - /** * Test for SUCCESS */ $bucket = $this->client->call(Client::METHOD_POST, '/storage/buckets', [ - 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'], + 'content-type' => 'application/json', + 'x-appwrite-project' => $this->getProject()['$id'], + 'x-appwrite-key' => $this->getProject()['apiKey'], ], [ - 'bucketId' => ID::unique(), - 'name' => 'Test Bucket', - 'permissions' => [ - Permission::read(Role::any()), - Permission::create(Role::any()), - Permission::update(Role::any()), - Permission::delete(Role::any()), - ], + 'bucketId' => ID::unique(), + 'name' => 'Test Bucket', + 'permissions' => [ + Permission::read(Role::any()), + Permission::create(Role::any()), + Permission::update(Role::any()), + Permission::delete(Role::any()), + ], ]); $bucketId = $bucket['body']['$id']; $this->assertEquals(201, $bucket['headers']['status-code']); $this->assertNotEmpty($bucketId); - $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/' . $bucketId . '/files', [ - 'content-type' => 'multipart/form-data', - 'x-appwrite-project' => $this->getProject()['$id'], + $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/'.$bucketId.'/files', [ + 'content-type' => 'multipart/form-data', + 'x-appwrite-project' => $this->getProject()['$id'], ], [ - 'fileId' => ID::unique(), - 'file' => new CURLFile(realpath(__DIR__ . '/../../../resources/logo.png'), 'image/png', 'permissions.png'), + 'fileId' => ID::unique(), + 'file' => new CURLFile(realpath(__DIR__.'/../../../resources/logo.png'), 'image/png', 'permissions.png'), ]); $fileId = $file['body']['$id']; @@ -160,46 +159,46 @@ class StorageCustomClientTest extends Scope $this->assertEquals('image/png', $file['body']['mimeType']); $this->assertEquals(47218, $file['body']['sizeOriginal']); - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId, [ - 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'], + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId, [ + 'content-type' => 'application/json', + 'x-appwrite-project' => $this->getProject()['$id'], ]); $this->assertEquals(200, $file['headers']['status-code']); - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId . '/preview', [ - 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'], + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId.'/preview', [ + 'content-type' => 'application/json', + 'x-appwrite-project' => $this->getProject()['$id'], ]); $this->assertEquals(200, $file['headers']['status-code']); - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId . '/download', [ - 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'], + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId.'/download', [ + 'content-type' => 'application/json', + 'x-appwrite-project' => $this->getProject()['$id'], ]); $this->assertEquals(200, $file['headers']['status-code']); - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId . '/view', [ - 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'], + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId.'/view', [ + 'content-type' => 'application/json', + 'x-appwrite-project' => $this->getProject()['$id'], ]); $this->assertEquals(200, $file['headers']['status-code']); - $file = $this->client->call(Client::METHOD_PUT, '/storage/buckets/' . $bucketId . '/files/' . $fileId, [ - 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'], + $file = $this->client->call(Client::METHOD_PUT, '/storage/buckets/'.$bucketId.'/files/'.$fileId, [ + 'content-type' => 'application/json', + 'x-appwrite-project' => $this->getProject()['$id'], ], [ - 'name' => 'permissions.png', + 'name' => 'permissions.png', ]); $this->assertEquals(200, $file['headers']['status-code']); - $file = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/' . $bucketId . '/files/' . $fileId, [ - 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'], + $file = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/'.$bucketId.'/files/'.$fileId, [ + 'content-type' => 'application/json', + 'x-appwrite-project' => $this->getProject()['$id'], ]); $this->assertEquals(204, $file['headers']['status-code']); @@ -230,12 +229,12 @@ class StorageCustomClientTest extends Scope $this->assertEquals(201, $bucket['headers']['status-code']); $this->assertNotEmpty($bucketId); - $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/' . $bucketId . '/files', array_merge([ + $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/'.$bucketId.'/files', array_merge([ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'fileId' => ID::unique(), - 'file' => new CURLFile(realpath(__DIR__ . '/../../../resources/logo.png'), 'image/png', 'permissions.png'), + 'file' => new CURLFile(realpath(__DIR__.'/../../../resources/logo.png'), 'image/png', 'permissions.png'), ]); $fileId = $file['body']['$id']; @@ -247,35 +246,35 @@ class StorageCustomClientTest extends Scope $this->assertEquals('image/png', $file['body']['mimeType']); $this->assertEquals(47218, $file['body']['sizeOriginal']); - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId, array_merge([ + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); $this->assertEquals(200, $file['headers']['status-code']); - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId . '/preview', array_merge([ + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId.'/preview', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); $this->assertEquals(200, $file['headers']['status-code']); - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId . '/download', array_merge([ + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId.'/download', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); $this->assertEquals(200, $file['headers']['status-code']); - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId . '/view', array_merge([ + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId.'/view', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); $this->assertEquals(200, $file['headers']['status-code']); - $file = $this->client->call(Client::METHOD_PUT, '/storage/buckets/' . $bucketId . '/files/' . $fileId, array_merge([ + $file = $this->client->call(Client::METHOD_PUT, '/storage/buckets/'.$bucketId.'/files/'.$fileId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -287,24 +286,24 @@ class StorageCustomClientTest extends Scope /** * Test for FAILURE */ - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId, [ + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId, [ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], ]); $this->assertEquals($file['headers']['status-code'], 401); - $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/' . $bucketId . '/files', [ + $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/'.$bucketId.'/files', [ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], ], [ 'fileId' => ID::unique(), - 'file' => new CURLFile(realpath(__DIR__ . '/../../../resources/logo.png'), 'image/png', 'permissions.png'), + 'file' => new CURLFile(realpath(__DIR__.'/../../../resources/logo.png'), 'image/png', 'permissions.png'), ]); $this->assertEquals($file['headers']['status-code'], 401); - $file = $this->client->call(Client::METHOD_PUT, '/storage/buckets/' . $bucketId . '/files/' . $fileId, [ + $file = $this->client->call(Client::METHOD_PUT, '/storage/buckets/'.$bucketId.'/files/'.$fileId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], [ @@ -313,7 +312,7 @@ class StorageCustomClientTest extends Scope $this->assertEquals($file['headers']['status-code'], 401); - $file = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/' . $bucketId . '/files/' . $fileId, [ + $file = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/'.$bucketId.'/files/'.$fileId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ]); @@ -323,7 +322,7 @@ class StorageCustomClientTest extends Scope /** * Test for SUCCESS */ - $file = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/' . $bucketId . '/files/' . $fileId, array_merge([ + $file = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/'.$bucketId.'/files/'.$fileId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -356,12 +355,12 @@ class StorageCustomClientTest extends Scope $this->assertEquals(201, $bucket['headers']['status-code']); $this->assertNotEmpty($bucketId); - $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/' . $bucketId . '/files', array_merge([ + $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/'.$bucketId.'/files', array_merge([ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'fileId' => ID::unique(), - 'file' => new CURLFile(realpath(__DIR__ . '/../../../resources/logo.png'), 'image/png', 'permissions.png'), + 'file' => new CURLFile(realpath(__DIR__.'/../../../resources/logo.png'), 'image/png', 'permissions.png'), ]); $fileId = $file['body']['$id']; @@ -373,35 +372,35 @@ class StorageCustomClientTest extends Scope $this->assertEquals('image/png', $file['body']['mimeType']); $this->assertEquals(47218, $file['body']['sizeOriginal']); - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId, array_merge([ + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); $this->assertEquals(200, $file['headers']['status-code']); - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId . '/preview', array_merge([ + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId.'/preview', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); $this->assertEquals(200, $file['headers']['status-code']); - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId . '/download', array_merge([ + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId.'/download', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); $this->assertEquals(200, $file['headers']['status-code']); - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId . '/view', array_merge([ + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId.'/view', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); $this->assertEquals(200, $file['headers']['status-code']); - $file = $this->client->call(Client::METHOD_PUT, '/storage/buckets/' . $bucketId . '/files/' . $fileId, array_merge([ + $file = $this->client->call(Client::METHOD_PUT, '/storage/buckets/'.$bucketId.'/files/'.$fileId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -413,22 +412,22 @@ class StorageCustomClientTest extends Scope /** * Test for FAILURE */ - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId, [ + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId, [ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], ]); $this->assertEquals(401, $file['headers']['status-code']); - $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/' . $bucketId . '/files', [ + $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/'.$bucketId.'/files', [ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], ], [ 'fileId' => ID::unique(), - 'file' => new CURLFile(realpath(__DIR__ . '/../../../resources/logo.png'), 'image/png', 'permissions.png'), + 'file' => new CURLFile(realpath(__DIR__.'/../../../resources/logo.png'), 'image/png', 'permissions.png'), ]); - $this->client->call(CLient::METHOD_PUT, '/storage/buckets/' . $bucketId . '/files/' . $fileId, [ + $this->client->call(CLient::METHOD_PUT, '/storage/buckets/'.$bucketId.'/files/'.$fileId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], [ @@ -439,50 +438,50 @@ class StorageCustomClientTest extends Scope $this->assertEquals($file['headers']['status-code'], 401); - $file = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/' . $bucketId . '/files/' . $fileId, [ + $file = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/'.$bucketId.'/files/'.$fileId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ]); $this->assertEquals($file['headers']['status-code'], 401); - $email = ID::unique() . '@localhost.test'; + $email = ID::unique().'@localhost.test'; $password = 'password'; $user2 = $this->createUser('user2', $email, $password); - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId, [ + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId, [ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $user2['session'], + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$user2['session'], ]); $this->assertEquals($file['headers']['status-code'], 401); - $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/' . $bucketId . '/files', [ + $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/'.$bucketId.'/files', [ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $user2['session'], + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$user2['session'], ], [ 'fileId' => ID::unique(), - 'file' => new CURLFile(realpath(__DIR__ . '/../../../resources/logo.png'), 'image/png', 'permissions.png'), + 'file' => new CURLFile(realpath(__DIR__.'/../../../resources/logo.png'), 'image/png', 'permissions.png'), ]); $this->assertEquals($file['headers']['status-code'], 401); - $file = $this->client->call(Client::METHOD_PUT, '/storage/buckets/' . $bucketId . '/files/' . $fileId, [ + $file = $this->client->call(Client::METHOD_PUT, '/storage/buckets/'.$bucketId.'/files/'.$fileId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $user2['session'], + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$user2['session'], ], [ 'permissions' => [], ]); $this->assertEquals($file['headers']['status-code'], 401); - $file = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/' . $bucketId . '/files/' . $fileId, [ + $file = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/'.$bucketId.'/files/'.$fileId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $user2['session'], + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$user2['session'], ]); $this->assertEquals($file['headers']['status-code'], 401); @@ -490,12 +489,11 @@ class StorageCustomClientTest extends Scope /** * Test for SUCCESS */ - $file = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/' . $bucketId . '/files/' . $fileId, array_merge([ + $file = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/'.$bucketId.'/files/'.$fileId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); - $this->assertEquals(204, $file['headers']['status-code']); $this->assertEmpty($file['body']); } @@ -504,8 +502,8 @@ class StorageCustomClientTest extends Scope { $team1 = $this->createTeam(ID::unique(), 'Team 1'); $team2 = $this->createTeam(ID::unique(), 'Team 1'); - $user1 = $this->createUser(ID::unique(), ID::unique() . '@localhost.test', 'password'); - $user2 = $this->createUser(ID::unique(), ID::unique() . '@localhost.test', 'password'); + $user1 = $this->createUser(ID::unique(), ID::unique().'@localhost.test', 'password'); + $user2 = $this->createUser(ID::unique(), ID::unique().'@localhost.test', 'password'); $this->addToTeam($user1['$id'], $team1['$id']); $this->addToTeam($user2['$id'], $team2['$id']); @@ -534,13 +532,13 @@ class StorageCustomClientTest extends Scope $this->assertNotEmpty($bucketId); // Team 1 create success - $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/' . $bucketId . '/files', [ + $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/'.$bucketId.'/files', [ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $user1['session'], + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$user1['session'], ], [ 'fileId' => ID::unique(), - 'file' => new CURLFile(realpath(__DIR__ . '/../../../resources/logo.png'), 'image/png', 'permissions.png'), + 'file' => new CURLFile(realpath(__DIR__.'/../../../resources/logo.png'), 'image/png', 'permissions.png'), ]); $fileId = $file['body']['$id']; @@ -553,73 +551,73 @@ class StorageCustomClientTest extends Scope $this->assertEquals(47218, $file['body']['sizeOriginal']); // Team 1 read success - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId, [ + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $user1['session'], + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$user1['session'], ]); $this->assertEquals(200, $file['headers']['status-code']); // Team 2 read success - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId, [ + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $user2['session'], + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$user2['session'], ]); $this->assertEquals(200, $file['headers']['status-code']); // Team 1 preview success - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId . '/preview', [ + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId.'/preview', [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $user1['session'], + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$user1['session'], ]); $this->assertEquals(200, $file['headers']['status-code']); // Team 2 preview success - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId . '/preview', [ + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId.'/preview', [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $user2['session'], + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$user2['session'], ]); $this->assertEquals(200, $file['headers']['status-code']); // Team 1 download success - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId . '/download', [ + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId.'/download', [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $user1['session'], + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$user1['session'], ]); $this->assertEquals(200, $file['headers']['status-code']); // Team 2 download success - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId . '/download', [ + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId.'/download', [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $user2['session'], + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$user2['session'], ]); $this->assertEquals(200, $file['headers']['status-code']); // Team 1 view success - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId . '/view', [ + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId.'/view', [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $user1['session'], + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$user1['session'], ]); $this->assertEquals(200, $file['headers']['status-code']); // Team 1 view success - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId . '/view', [ + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId.'/view', [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $user2['session'], + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$user2['session'], ]); $this->assertEquals(200, $file['headers']['status-code']); @@ -629,22 +627,22 @@ class StorageCustomClientTest extends Scope */ // Team 2 create failure - $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/' . $bucketId . '/files', [ + $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/'.$bucketId.'/files', [ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $user2['session'], + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$user2['session'], ], [ 'fileId' => ID::unique(), - 'file' => new CURLFile(realpath(__DIR__ . '/../../../resources/logo.png'), 'image/png', 'permissions.png'), + 'file' => new CURLFile(realpath(__DIR__.'/../../../resources/logo.png'), 'image/png', 'permissions.png'), ]); $this->assertEquals($file['headers']['status-code'], 401); // Team 2 update failure - $file = $this->client->call(Client::METHOD_PUT, '/storage/buckets/' . $bucketId . '/files/' . $fileId, [ + $file = $this->client->call(Client::METHOD_PUT, '/storage/buckets/'.$bucketId.'/files/'.$fileId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $user2['session'], + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$user2['session'], ], [ 'permissions' => [], ]); @@ -652,10 +650,10 @@ class StorageCustomClientTest extends Scope $this->assertEquals($file['headers']['status-code'], 401); // Team 2 delete failure - $file = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/' . $bucketId . '/files/' . $fileId, [ + $file = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/'.$bucketId.'/files/'.$fileId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $user2['session'], + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$user2['session'], ]); $this->assertEquals($file['headers']['status-code'], 401); @@ -664,10 +662,10 @@ class StorageCustomClientTest extends Scope * Test for SUCCESS */ // Team 1 delete success - $file = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/' . $bucketId . '/files/' . $fileId, [ + $file = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/'.$bucketId.'/files/'.$fileId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $user1['session'], + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$user1['session'], ]); $this->assertEquals(204, $file['headers']['status-code']); @@ -687,20 +685,20 @@ class StorageCustomClientTest extends Scope 'bucketId' => ID::unique(), 'name' => 'Test Bucket', 'permissions' => [], - 'fileSecurity' => true + 'fileSecurity' => true, ]); $bucketId = $bucket['body']['$id']; $this->assertEquals(201, $bucket['headers']['status-code']); $this->assertNotEmpty($bucketId); - $file1 = $this->client->call(Client::METHOD_POST, '/storage/buckets/' . $bucketId . '/files', [ + $file1 = $this->client->call(Client::METHOD_POST, '/storage/buckets/'.$bucketId.'/files', [ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], 'x-appwrite-key' => $this->getProject()['apiKey'], ], [ 'fileId' => ID::unique(), - 'file' => new CURLFile(realpath(__DIR__ . '/../../../resources/logo.png'), 'image/png', 'permissions.png'), + 'file' => new CURLFile(realpath(__DIR__.'/../../../resources/logo.png'), 'image/png', 'permissions.png'), 'permissions' => [ Permission::read(Role::any()), ], @@ -715,28 +713,28 @@ class StorageCustomClientTest extends Scope $this->assertEquals('image/png', $file1['body']['mimeType']); $this->assertEquals(47218, $file1['body']['sizeOriginal']); - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId, [ + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ]); $this->assertEquals(200, $file['headers']['status-code']); - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId . '/preview', [ + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId.'/preview', [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ]); $this->assertEquals(200, $file['headers']['status-code']); - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId . '/download', [ + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId.'/download', [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ]); $this->assertEquals(200, $file['headers']['status-code']); - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId . '/view', [ + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId.'/view', [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ]); @@ -746,17 +744,17 @@ class StorageCustomClientTest extends Scope /** * Test for FAILURE */ - $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/' . $bucketId . '/files', [ + $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/'.$bucketId.'/files', [ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], ], [ 'fileId' => ID::unique(), - 'file' => new CURLFile(realpath(__DIR__ . '/../../../resources/logo.png'), 'image/png', 'permissions.png'), + 'file' => new CURLFile(realpath(__DIR__.'/../../../resources/logo.png'), 'image/png', 'permissions.png'), ]); $this->assertEquals(401, $file['headers']['status-code']); - $file = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/' . $bucketId . '/files/' . $fileId, [ + $file = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/'.$bucketId.'/files/'.$fileId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ]); @@ -777,20 +775,20 @@ class StorageCustomClientTest extends Scope 'bucketId' => ID::unique(), 'name' => 'Test Bucket', 'permissions' => [], - 'fileSecurity' => true + 'fileSecurity' => true, ]); $bucketId = $bucket['body']['$id']; $this->assertEquals(201, $bucket['headers']['status-code']); $this->assertNotEmpty($bucketId); - $file1 = $this->client->call(Client::METHOD_POST, '/storage/buckets/' . $bucketId . '/files', [ + $file1 = $this->client->call(Client::METHOD_POST, '/storage/buckets/'.$bucketId.'/files', [ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], 'x-appwrite-key' => $this->getProject()['apiKey'], ], [ 'fileId' => ID::unique(), - 'file' => new CURLFile(realpath(__DIR__ . '/../../../resources/logo.png'), 'image/png', 'permissions.png'), + 'file' => new CURLFile(realpath(__DIR__.'/../../../resources/logo.png'), 'image/png', 'permissions.png'), 'permissions' => [ Permission::read(Role::users()), ], @@ -805,28 +803,28 @@ class StorageCustomClientTest extends Scope $this->assertEquals('image/png', $file1['body']['mimeType']); $this->assertEquals(47218, $file1['body']['sizeOriginal']); - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId, array_merge([ + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); $this->assertEquals(200, $file['headers']['status-code']); - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId . '/preview', array_merge([ + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId.'/preview', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); $this->assertEquals(200, $file['headers']['status-code']); - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId . '/download', array_merge([ + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId.'/download', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); $this->assertEquals(200, $file['headers']['status-code']); - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId . '/view', array_merge([ + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId.'/view', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -836,17 +834,17 @@ class StorageCustomClientTest extends Scope /** * Test for FAILURE */ - $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/' . $bucketId . '/files', [ + $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/'.$bucketId.'/files', [ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], ], [ 'fileId' => ID::unique(), - 'file' => new CURLFile(realpath(__DIR__ . '/../../../resources/logo.png'), 'image/png', 'permissions.png'), + 'file' => new CURLFile(realpath(__DIR__.'/../../../resources/logo.png'), 'image/png', 'permissions.png'), ]); $this->assertEquals(401, $file['headers']['status-code']); - $file = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/' . $bucketId . '/files/' . $fileId, array_merge([ + $file = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/'.$bucketId.'/files/'.$fileId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -867,20 +865,20 @@ class StorageCustomClientTest extends Scope 'bucketId' => ID::unique(), 'name' => 'Test Bucket', 'permissions' => [], - 'fileSecurity' => true + 'fileSecurity' => true, ]); $bucketId = $bucket['body']['$id']; $this->assertEquals(201, $bucket['headers']['status-code']); $this->assertNotEmpty($bucketId); - $file1 = $this->client->call(Client::METHOD_POST, '/storage/buckets/' . $bucketId . '/files', [ + $file1 = $this->client->call(Client::METHOD_POST, '/storage/buckets/'.$bucketId.'/files', [ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], 'x-appwrite-key' => $this->getProject()['apiKey'], ], [ 'fileId' => ID::unique(), - 'file' => new CURLFile(realpath(__DIR__ . '/../../../resources/logo.png'), 'image/png', 'permissions.png'), + 'file' => new CURLFile(realpath(__DIR__.'/../../../resources/logo.png'), 'image/png', 'permissions.png'), 'permissions' => [ Permission::read(Role::user($this->getUser()['$id'])), ], @@ -895,28 +893,28 @@ class StorageCustomClientTest extends Scope $this->assertEquals('image/png', $file1['body']['mimeType']); $this->assertEquals(47218, $file1['body']['sizeOriginal']); - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId, array_merge([ + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); $this->assertEquals(200, $file['headers']['status-code']); - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId . '/preview', array_merge([ + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId.'/preview', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); $this->assertEquals(200, $file['headers']['status-code']); - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId . '/download', array_merge([ + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId.'/download', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); $this->assertEquals(200, $file['headers']['status-code']); - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId . '/view', array_merge([ + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId.'/view', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -926,58 +924,58 @@ class StorageCustomClientTest extends Scope /** * Test for FAILURE */ - $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/' . $bucketId . '/files', [ + $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/'.$bucketId.'/files', [ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], ], [ 'fileId' => ID::unique(), - 'file' => new CURLFile(realpath(__DIR__ . '/../../../resources/logo.png'), 'image/png', 'permissions.png'), + 'file' => new CURLFile(realpath(__DIR__.'/../../../resources/logo.png'), 'image/png', 'permissions.png'), ]); $this->assertEquals(401, $file['headers']['status-code']); - $file = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/' . $bucketId . '/files/' . $fileId, array_merge([ + $file = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/'.$bucketId.'/files/'.$fileId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); $this->assertEquals(401, $file['headers']['status-code']); - $user2 = $this->createUser(ID::unique(), uniqid() . '@localhost.test', 'password'); + $user2 = $this->createUser(ID::unique(), uniqid().'@localhost.test', 'password'); - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId, [ + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId, [ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $user2['session'], + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$user2['session'], ]); $this->assertEquals($file['headers']['status-code'], 404); - $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/' . $bucketId . '/files', [ + $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/'.$bucketId.'/files', [ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $user2['session'], + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$user2['session'], ], [ 'fileId' => ID::unique(), - 'file' => new CURLFile(realpath(__DIR__ . '/../../../resources/logo.png'), 'image/png', 'permissions.png'), + 'file' => new CURLFile(realpath(__DIR__.'/../../../resources/logo.png'), 'image/png', 'permissions.png'), ]); $this->assertEquals($file['headers']['status-code'], 401); - $file = $this->client->call(Client::METHOD_PUT, '/storage/buckets/' . $bucketId . '/files/' . $fileId, [ + $file = $this->client->call(Client::METHOD_PUT, '/storage/buckets/'.$bucketId.'/files/'.$fileId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $user2['session'], + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$user2['session'], ], [ 'permissions' => [], ]); $this->assertEquals($file['headers']['status-code'], 401); - $file = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/' . $bucketId . '/files/' . $fileId, [ + $file = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/'.$bucketId.'/files/'.$fileId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $user2['session'], + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$user2['session'], ]); $this->assertEquals($file['headers']['status-code'], 401); @@ -987,8 +985,8 @@ class StorageCustomClientTest extends Scope { $team1 = $this->createTeam(ID::unique(), 'Team 1'); $team2 = $this->createTeam(ID::unique(), 'Team 1'); - $user1 = $this->createUser(ID::unique(), ID::unique() . '@localhost.test', 'password'); - $user2 = $this->createUser(ID::unique(), ID::unique() . '@localhost.test', 'password'); + $user1 = $this->createUser(ID::unique(), ID::unique().'@localhost.test', 'password'); + $user2 = $this->createUser(ID::unique(), ID::unique().'@localhost.test', 'password'); $this->addToTeam($user1['$id'], $team1['$id']); $this->addToTeam($user2['$id'], $team2['$id']); @@ -1011,13 +1009,13 @@ class StorageCustomClientTest extends Scope $this->assertEquals(201, $bucket['headers']['status-code']); $this->assertNotEmpty($bucketId); - $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/' . $bucketId . '/files', [ + $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/'.$bucketId.'/files', [ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], 'x-appwrite-key' => $this->getProject()['apiKey'], ], [ 'fileId' => ID::unique(), - 'file' => new CURLFile(realpath(__DIR__ . '/../../../resources/logo.png'), 'image/png', 'permissions.png'), + 'file' => new CURLFile(realpath(__DIR__.'/../../../resources/logo.png'), 'image/png', 'permissions.png'), 'permissions' => [ Permission::read(Role::team(ID::custom($team1['$id']))), Permission::read(Role::team(ID::custom($team2['$id']))), @@ -1036,73 +1034,73 @@ class StorageCustomClientTest extends Scope $this->assertEquals(47218, $file['body']['sizeOriginal']); // Team 1 read success - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId, [ + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $user1['session'], + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$user1['session'], ]); $this->assertEquals(200, $file['headers']['status-code']); // Team 2 read success - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId, [ + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $user2['session'], + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$user2['session'], ]); $this->assertEquals(200, $file['headers']['status-code']); // Team 1 preview success - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId . '/preview', [ + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId.'/preview', [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $user1['session'], + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$user1['session'], ]); $this->assertEquals(200, $file['headers']['status-code']); // Team 2 preview success - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId . '/preview', [ + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId.'/preview', [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $user2['session'], + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$user2['session'], ]); $this->assertEquals(200, $file['headers']['status-code']); // Team 1 download success - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId . '/download', [ + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId.'/download', [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $user1['session'], + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$user1['session'], ]); $this->assertEquals(200, $file['headers']['status-code']); // Team 2 download success - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId . '/download', [ + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId.'/download', [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $user2['session'], + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$user2['session'], ]); $this->assertEquals(200, $file['headers']['status-code']); // Team 1 view success - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId . '/view', [ + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId.'/view', [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $user1['session'], + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$user1['session'], ]); $this->assertEquals(200, $file['headers']['status-code']); // Team 1 view success - $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/' . $bucketId . '/files/' . $fileId . '/view', [ + $file = $this->client->call(Client::METHOD_GET, '/storage/buckets/'.$bucketId.'/files/'.$fileId.'/view', [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $user2['session'], + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$user2['session'], ]); $this->assertEquals(200, $file['headers']['status-code']); @@ -1112,32 +1110,32 @@ class StorageCustomClientTest extends Scope */ // Team 1 create failure - $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/' . $bucketId . '/files', [ + $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/'.$bucketId.'/files', [ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $user1['session'], + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$user1['session'], ], [ 'fileId' => ID::unique(), - 'file' => new CURLFile(realpath(__DIR__ . '/../../../resources/logo.png'), 'image/png', 'permissions.png'), + 'file' => new CURLFile(realpath(__DIR__.'/../../../resources/logo.png'), 'image/png', 'permissions.png'), ]); // Team 2 create failure - $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/' . $bucketId . '/files', [ + $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/'.$bucketId.'/files', [ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $user2['session'], + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$user2['session'], ], [ 'fileId' => ID::unique(), - 'file' => new CURLFile(realpath(__DIR__ . '/../../../resources/logo.png'), 'image/png', 'permissions.png'), + 'file' => new CURLFile(realpath(__DIR__.'/../../../resources/logo.png'), 'image/png', 'permissions.png'), ]); $this->assertEquals($file['headers']['status-code'], 401); // Team 2 update failure - $file = $this->client->call(Client::METHOD_PUT, '/storage/buckets/' . $bucketId . '/files/' . $fileId, [ + $file = $this->client->call(Client::METHOD_PUT, '/storage/buckets/'.$bucketId.'/files/'.$fileId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $user2['session'], + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$user2['session'], ], [ 'permissions' => [], ]); @@ -1145,10 +1143,10 @@ class StorageCustomClientTest extends Scope $this->assertEquals($file['headers']['status-code'], 401); // Team 2 delete failure - $file = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/' . $bucketId . '/files/' . $fileId, [ + $file = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/'.$bucketId.'/files/'.$fileId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $user2['session'], + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$user2['session'], ]); $this->assertEquals($file['headers']['status-code'], 401); @@ -1157,10 +1155,10 @@ class StorageCustomClientTest extends Scope * Test for SUCCESS */ // Team 1 delete success - $file = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/' . $bucketId . '/files/' . $fileId, [ + $file = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/'.$bucketId.'/files/'.$fileId, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $user1['session'], + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$user1['session'], ]); $this->assertEquals(204, $file['headers']['status-code']); @@ -1195,15 +1193,15 @@ class StorageCustomClientTest extends Scope $this->assertContains(Permission::delete(Role::user($this->getUser()['$id'])), $bucket['body']['$permissions']); // File aliases write to update, delete - $file1 = $this->client->call(Client::METHOD_POST, '/storage/buckets/' . $bucketId . '/files', array_merge([ + $file1 = $this->client->call(Client::METHOD_POST, '/storage/buckets/'.$bucketId.'/files', array_merge([ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'fileId' => ID::unique(), - 'file' => new CURLFile(realpath(__DIR__ . '/../../../resources/logo.png'), 'image/png', 'permissions.png'), + 'file' => new CURLFile(realpath(__DIR__.'/../../../resources/logo.png'), 'image/png', 'permissions.png'), 'permissions' => [ Permission::write(Role::user($this->getUser()['$id'])), - ] + ], ]); $this->assertNotContains(Permission::create(Role::user($this->getUser()['$id'])), $file1['body']['$permissions']); @@ -1215,15 +1213,15 @@ class StorageCustomClientTest extends Scope */ // File does not allow create permission - $file2 = $this->client->call(Client::METHOD_POST, '/storage/buckets/' . $bucketId . '/files', [ + $file2 = $this->client->call(Client::METHOD_POST, '/storage/buckets/'.$bucketId.'/files', [ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], ], [ 'fileId' => ID::unique(), - 'file' => new CURLFile(realpath(__DIR__ . '/../../../resources/logo.png'), 'image/png', 'permissions.png'), + 'file' => new CURLFile(realpath(__DIR__.'/../../../resources/logo.png'), 'image/png', 'permissions.png'), 'permissions' => [ Permission::create(Role::user($this->getUser()['$id'])), - ] + ], ]); $this->assertEquals(400, $file2['headers']['status-code']); @@ -1252,12 +1250,12 @@ class StorageCustomClientTest extends Scope $this->assertEquals(201, $bucket['headers']['status-code']); $this->assertNotEmpty($bucket['body']['$id']); - $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/' . $bucket['body']['$id'] . '/files', array_merge([ + $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/'.$bucket['body']['$id'].'/files', array_merge([ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'fileId' => ID::unique(), - 'file' => new CURLFile(realpath(__DIR__ . '/../../../resources/logo.png'), 'image/png', 'permissions.png'), + 'file' => new CURLFile(realpath(__DIR__.'/../../../resources/logo.png'), 'image/png', 'permissions.png'), ]); $this->assertEquals($file['headers']['status-code'], 201); @@ -1282,12 +1280,12 @@ class StorageCustomClientTest extends Scope /** * Test for FAILURE */ - $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/' . $data['bucketId'] . '/files', array_merge([ + $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/'.$data['bucketId'].'/files', array_merge([ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'fileId' => ID::unique(), - 'file' => new CURLFile(realpath(__DIR__ . '/../../../resources/logo.png'), 'image/png', 'permissions.png'), + 'file' => new CURLFile(realpath(__DIR__.'/../../../resources/logo.png'), 'image/png', 'permissions.png'), 'folderId' => ID::custom('xyz'), 'permissions' => [ Permission::read(Role::user(ID::custom('notme'))), @@ -1298,33 +1296,33 @@ class StorageCustomClientTest extends Scope $this->assertStringStartsWith('Permissions must be one of:', $file['body']['message']); $this->assertStringContainsString('any', $file['body']['message']); $this->assertStringContainsString('users', $file['body']['message']); - $this->assertStringContainsString('user:' . $this->getUser()['$id'], $file['body']['message']); + $this->assertStringContainsString('user:'.$this->getUser()['$id'], $file['body']['message']); - $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/' . $data['bucketId'] . '/files', array_merge([ + $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/'.$data['bucketId'].'/files', array_merge([ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'fileId' => ID::unique(), - 'file' => new CURLFile(realpath(__DIR__ . '/../../../resources/logo.png'), 'image/png', 'permissions.png'), + 'file' => new CURLFile(realpath(__DIR__.'/../../../resources/logo.png'), 'image/png', 'permissions.png'), 'folderId' => ID::custom('xyz'), 'permissions' => [ Permission::update(Role::user(ID::custom('notme'))), Permission::delete(Role::user(ID::custom('notme'))), - ] + ], ]); $this->assertEquals(401, $file['headers']['status-code']); $this->assertStringStartsWith('Permissions must be one of:', $file['body']['message']); $this->assertStringContainsString('any', $file['body']['message']); $this->assertStringContainsString('users', $file['body']['message']); - $this->assertStringContainsString('user:' . $this->getUser()['$id'], $file['body']['message']); + $this->assertStringContainsString('user:'.$this->getUser()['$id'], $file['body']['message']); - $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/' . $data['bucketId'] . '/files', array_merge([ + $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/'.$data['bucketId'].'/files', array_merge([ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'fileId' => ID::unique(), - 'file' => new CURLFile(realpath(__DIR__ . '/../../../resources/logo.png'), 'image/png', 'permissions.png'), + 'file' => new CURLFile(realpath(__DIR__.'/../../../resources/logo.png'), 'image/png', 'permissions.png'), 'folderId' => ID::custom('xyz'), 'permissions' => [ Permission::read(Role::user(ID::custom('notme'))), @@ -1337,7 +1335,7 @@ class StorageCustomClientTest extends Scope $this->assertStringStartsWith('Permissions must be one of:', $file['body']['message']); $this->assertStringContainsString('any', $file['body']['message']); $this->assertStringContainsString('users', $file['body']['message']); - $this->assertStringContainsString('user:' . $this->getUser()['$id'], $file['body']['message']); + $this->assertStringContainsString('user:'.$this->getUser()['$id'], $file['body']['message']); } /** @@ -1348,7 +1346,7 @@ class StorageCustomClientTest extends Scope /** * Test for FAILURE */ - $file = $this->client->call(Client::METHOD_PUT, '/storage/buckets/' . $data['bucketId'] . '/files/' . $data['fileId'], array_merge([ + $file = $this->client->call(Client::METHOD_PUT, '/storage/buckets/'.$data['bucketId'].'/files/'.$data['fileId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1361,25 +1359,25 @@ class StorageCustomClientTest extends Scope $this->assertStringStartsWith('Permissions must be one of:', $file['body']['message']); $this->assertStringContainsString('any', $file['body']['message']); $this->assertStringContainsString('users', $file['body']['message']); - $this->assertStringContainsString('user:' . $this->getUser()['$id'], $file['body']['message']); + $this->assertStringContainsString('user:'.$this->getUser()['$id'], $file['body']['message']); - $file = $this->client->call(Client::METHOD_PUT, '/storage/buckets/' . $data['bucketId'] . '/files/' . $data['fileId'], array_merge([ + $file = $this->client->call(Client::METHOD_PUT, '/storage/buckets/'.$data['bucketId'].'/files/'.$data['fileId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'permissions' => [ Permission::update(Role::user(ID::custom('notme'))), Permission::delete(Role::user(ID::custom('notme'))), - ] + ], ]); $this->assertEquals(401, $file['headers']['status-code']); $this->assertStringStartsWith('Permissions must be one of:', $file['body']['message']); $this->assertStringContainsString('any', $file['body']['message']); $this->assertStringContainsString('users', $file['body']['message']); - $this->assertStringContainsString('user:' . $this->getUser()['$id'], $file['body']['message']); + $this->assertStringContainsString('user:'.$this->getUser()['$id'], $file['body']['message']); - $file = $this->client->call(Client::METHOD_PUT, '/storage/buckets/' . $data['bucketId'] . '/files/' . $data['fileId'], array_merge([ + $file = $this->client->call(Client::METHOD_PUT, '/storage/buckets/'.$data['bucketId'].'/files/'.$data['fileId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -1394,6 +1392,6 @@ class StorageCustomClientTest extends Scope $this->assertStringStartsWith('Permissions must be one of:', $file['body']['message']); $this->assertStringContainsString('any', $file['body']['message']); $this->assertStringContainsString('users', $file['body']['message']); - $this->assertStringContainsString('user:' . $this->getUser()['$id'], $file['body']['message']); + $this->assertStringContainsString('user:'.$this->getUser()['$id'], $file['body']['message']); } } diff --git a/tests/e2e/Services/Storage/StorageCustomServerTest.php b/tests/e2e/Services/Storage/StorageCustomServerTest.php index 86c9c54302..c40f227b16 100644 --- a/tests/e2e/Services/Storage/StorageCustomServerTest.php +++ b/tests/e2e/Services/Storage/StorageCustomServerTest.php @@ -84,8 +84,8 @@ class StorageCustomServerTest extends Scope '/storage/buckets', array_merge( [ - 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'], + 'content-type' => 'application/json', + 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders() ) @@ -99,7 +99,7 @@ class StorageCustomServerTest extends Scope 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'limit(1)' ], + 'queries' => ['limit(1)'], ]); $this->assertEquals(200, $response['headers']['status-code']); @@ -109,7 +109,7 @@ class StorageCustomServerTest extends Scope 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'offset(1)' ], + 'queries' => ['offset(1)'], ]); $this->assertEquals(200, $response['headers']['status-code']); @@ -119,7 +119,7 @@ class StorageCustomServerTest extends Scope 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'equal("$id", "bucket1")' ], + 'queries' => ['equal("$id", "bucket1")'], ]); $this->assertEquals(200, $response['headers']['status-code']); @@ -129,7 +129,7 @@ class StorageCustomServerTest extends Scope 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'equal("fileSecurity", true)' ], + 'queries' => ['equal("fileSecurity", true)'], ]); $this->assertEquals(200, $response['headers']['status-code']); @@ -139,7 +139,7 @@ class StorageCustomServerTest extends Scope 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'cursorAfter("' . $response['body']['buckets'][0]['$id'] . '")' ], + 'queries' => ['cursorAfter("'.$response['body']['buckets'][0]['$id'].'")'], ]); $this->assertEquals(200, $response['headers']['status-code']); @@ -148,6 +148,7 @@ class StorageCustomServerTest extends Scope $this->assertCount(1, $response['body']['buckets']); $this->assertEquals('bucket1', $response['body']['buckets'][0]['$id']); + return $data; } @@ -162,11 +163,11 @@ class StorageCustomServerTest extends Scope */ $response = $this->client->call( Client::METHOD_GET, - '/storage/buckets/' . $id, + '/storage/buckets/'.$id, array_merge( [ - 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'], + 'content-type' => 'application/json', + 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders() ) @@ -179,14 +180,13 @@ class StorageCustomServerTest extends Scope /** * Test for FAILURE */ - $response = $this->client->call( Client::METHOD_GET, '/storage/buckets/empty', array_merge( [ - 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'], + 'content-type' => 'application/json', + 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders() ) @@ -198,8 +198,8 @@ class StorageCustomServerTest extends Scope '/storage/buckets/id-is-really-long-id-is-really-long-id-is-really-long-id-is-really-long', array_merge( [ - 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'], + 'content-type' => 'application/json', + 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders() ) @@ -218,7 +218,7 @@ class StorageCustomServerTest extends Scope /** * Test for SUCCESS */ - $bucket = $this->client->call(Client::METHOD_PUT, '/storage/buckets/' . $id, array_merge([ + $bucket = $this->client->call(Client::METHOD_PUT, '/storage/buckets/'.$id, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -241,7 +241,7 @@ class StorageCustomServerTest extends Scope /** * Test for FAILURE */ - $bucket = $this->client->call(Client::METHOD_PUT, '/storage/buckets/' . $id, array_merge([ + $bucket = $this->client->call(Client::METHOD_PUT, '/storage/buckets/'.$id, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -264,11 +264,11 @@ class StorageCustomServerTest extends Scope */ $response = $this->client->call( Client::METHOD_DELETE, - '/storage/buckets/' . $id, + '/storage/buckets/'.$id, array_merge( [ - 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'], + 'content-type' => 'application/json', + 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders() ) @@ -278,11 +278,11 @@ class StorageCustomServerTest extends Scope $response = $this->client->call( Client::METHOD_GET, - '/storage/buckets/' . $id, + '/storage/buckets/'.$id, array_merge( [ - 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'], + 'content-type' => 'application/json', + 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders() ) diff --git a/tests/e2e/Services/Storage/StoragePermissionsScope.php b/tests/e2e/Services/Storage/StoragePermissionsScope.php index 09b35fad36..e6502cc183 100644 --- a/tests/e2e/Services/Storage/StoragePermissionsScope.php +++ b/tests/e2e/Services/Storage/StoragePermissionsScope.php @@ -7,6 +7,7 @@ use Tests\E2E\Client; trait StoragePermissionsScope { public array $users = []; + public array $teams = []; public function createUser(string $id, string $email, string $password = 'test123!'): array @@ -18,7 +19,7 @@ trait StoragePermissionsScope ], [ 'userId' => $id, 'email' => $email, - 'password' => $password + 'password' => $password, ]); $this->assertEquals(201, $user['headers']['status-code']); @@ -32,8 +33,7 @@ trait StoragePermissionsScope 'password' => $password, ]); - $session = $this->client->parseCookie((string)$session['headers']['set-cookie'])['a_session_' . $this->getProject()['$id']]; - + $session = $this->client->parseCookie((string) $session['headers']['set-cookie'])['a_session_'.$this->getProject()['$id']]; $user = [ '$id' => $user['body']['$id'], @@ -54,7 +54,7 @@ trait StoragePermissionsScope { $team = $this->client->call(Client::METHOD_POST, '/teams', $this->getServerHeader(), [ 'teamId' => $id, - 'name' => $name + 'name' => $name, ]); $this->teams[$id] = $team['body']; @@ -63,16 +63,16 @@ trait StoragePermissionsScope public function addToTeam(string $user, string $team, array $roles = []): array { - $membership = $this->client->call(Client::METHOD_POST, '/teams/' . $team . '/memberships', $this->getServerHeader(), [ + $membership = $this->client->call(Client::METHOD_POST, '/teams/'.$team.'/memberships', $this->getServerHeader(), [ 'teamId' => $team, 'email' => $this->getCreatedUser($user)['email'], 'roles' => $roles, - 'url' => 'http://localhost:5000/join-us#title' + 'url' => 'http://localhost:5000/join-us#title', ]); return [ 'user' => $membership['body']['userId'], - 'membership' => $membership['body']['$id'] + 'membership' => $membership['body']['$id'], ]; } @@ -81,7 +81,7 @@ trait StoragePermissionsScope return [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]; } } diff --git a/tests/e2e/Services/Teams/TeamsBase.php b/tests/e2e/Services/Teams/TeamsBase.php index daaf65494d..25e379822b 100644 --- a/tests/e2e/Services/Teams/TeamsBase.php +++ b/tests/e2e/Services/Teams/TeamsBase.php @@ -39,7 +39,7 @@ trait TeamsBase 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'teamId' => $teamId, - 'name' => 'Manchester United' + 'name' => 'Manchester United', ]); $this->assertEquals(201, $response2['headers']['status-code']); @@ -55,7 +55,7 @@ trait TeamsBase 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'teamId' => ID::unique(), - 'name' => 'Newcastle' + 'name' => 'Newcastle', ]); $this->assertEquals(201, $response3['headers']['status-code']); @@ -88,7 +88,7 @@ trait TeamsBase /** * Test for SUCCESS */ - $response = $this->client->call(Client::METHOD_GET, '/teams/' . $id, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/teams/'.$id, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -130,7 +130,7 @@ trait TeamsBase 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'limit(2)' ], + 'queries' => ['limit(2)'], ]); $this->assertEquals(200, $response['headers']['status-code']); @@ -140,7 +140,7 @@ trait TeamsBase 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'offset(1)' ], + 'queries' => ['offset(1)'], ]); $this->assertEquals(200, $response['headers']['status-code']); @@ -150,7 +150,7 @@ trait TeamsBase 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'greaterThanEqual("total", 0)' ], + 'queries' => ['greaterThanEqual("total", 0)'], ]); $this->assertEquals(200, $response['headers']['status-code']); @@ -160,7 +160,7 @@ trait TeamsBase 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'equal("name", ["Arsenal", "Newcastle"])' ], + 'queries' => ['equal("name", ["Arsenal", "Newcastle"])'], ]); $this->assertEquals(200, $response['headers']['status-code']); @@ -209,7 +209,7 @@ trait TeamsBase 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'limit(2)' ], + 'queries' => ['limit(2)'], ]); $this->assertEquals(200, $teams['headers']['status-code']); @@ -221,7 +221,7 @@ trait TeamsBase 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'limit(1)', 'cursorAfter("' . $teams['body']['teams'][0]['$id'] . '")' ], + 'queries' => ['limit(1)', 'cursorAfter("'.$teams['body']['teams'][0]['$id'].'")'], ]); $this->assertEquals(200, $response['headers']['status-code']); @@ -234,7 +234,7 @@ trait TeamsBase 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'limit(1)', 'cursorBefore("' . $teams['body']['teams'][1]['$id'] . '")' ], + 'queries' => ['limit(1)', 'cursorBefore("'.$teams['body']['teams'][1]['$id'].'")'], ]); $this->assertEquals(200, $response['headers']['status-code']); @@ -250,7 +250,7 @@ trait TeamsBase 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'cursorAfter("unknown")' ], + 'queries' => ['cursorAfter("unknown")'], ]); $this->assertEquals(400, $response['headers']['status-code']); @@ -268,7 +268,7 @@ trait TeamsBase 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'teamId' => ID::unique(), - 'name' => 'Demo' + 'name' => 'Demo', ]); $this->assertEquals(201, $response['headers']['status-code']); @@ -279,12 +279,12 @@ trait TeamsBase $dateValidator = new DatetimeValidator(); $this->assertEquals(true, $dateValidator->isValid($response['body']['$createdAt'])); - $response = $this->client->call(Client::METHOD_PUT, '/teams/' . $response['body']['$id'], array_merge([ + $response = $this->client->call(Client::METHOD_PUT, '/teams/'.$response['body']['$id'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'teamId' => ID::unique(), - 'name' => 'Demo New' + 'name' => 'Demo New', ]); $this->assertEquals(200, $response['headers']['status-code']); @@ -297,7 +297,7 @@ trait TeamsBase /** * Test for FAILURE */ - $response = $this->client->call(Client::METHOD_PUT, '/teams/' . $response['body']['$id'], array_merge([ + $response = $this->client->call(Client::METHOD_PUT, '/teams/'.$response['body']['$id'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -318,7 +318,7 @@ trait TeamsBase 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'teamId' => ID::unique(), - 'name' => 'Demo' + 'name' => 'Demo', ]); $teamUid = $response['body']['$id']; @@ -331,7 +331,7 @@ trait TeamsBase $dateValidator = new DatetimeValidator(); $this->assertEquals(true, $dateValidator->isValid($response['body']['$createdAt'])); - $response = $this->client->call(Client::METHOD_DELETE, '/teams/' . $teamUid, array_merge([ + $response = $this->client->call(Client::METHOD_DELETE, '/teams/'.$teamUid, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -342,7 +342,7 @@ trait TeamsBase /** * Test for FAILURE */ - $response = $this->client->call(Client::METHOD_GET, '/teams/' . $teamUid, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/teams/'.$teamUid, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); diff --git a/tests/e2e/Services/Teams/TeamsBaseClient.php b/tests/e2e/Services/Teams/TeamsBaseClient.php index 4e6cf85a10..e402c0dbd4 100644 --- a/tests/e2e/Services/Teams/TeamsBaseClient.php +++ b/tests/e2e/Services/Teams/TeamsBaseClient.php @@ -19,7 +19,7 @@ trait TeamsBaseClient /** * Test for SUCCESS */ - $response = $this->client->call(Client::METHOD_GET, '/teams/' . $teamUid . '/memberships', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/teams/'.$teamUid.'/memberships', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -35,51 +35,51 @@ trait TeamsBaseClient $membershipId = $response['body']['memberships'][0]['$id']; - $response = $this->client->call(Client::METHOD_GET, '/teams/' . $teamUid . '/memberships', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/teams/'.$teamUid.'/memberships', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'limit(0)' ] + 'queries' => ['limit(0)'], ]); $this->assertEquals(200, $response['headers']['status-code']); $this->assertCount(0, $response['body']['memberships']); - $response = $this->client->call(Client::METHOD_GET, '/teams/' . $teamUid . '/memberships', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/teams/'.$teamUid.'/memberships', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'offset(1)' ] + 'queries' => ['offset(1)'], ]); $this->assertEquals(200, $response['headers']['status-code']); $this->assertCount(0, $response['body']['memberships']); - $response = $this->client->call(Client::METHOD_GET, '/teams/' . $teamUid . '/memberships', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/teams/'.$teamUid.'/memberships', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'equal("confirm", true)' ] + 'queries' => ['equal("confirm", true)'], ]); $this->assertEquals(200, $response['headers']['status-code']); $this->assertCount(1, $response['body']['memberships']); - $response = $this->client->call(Client::METHOD_GET, '/teams/' . $teamUid . '/memberships', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/teams/'.$teamUid.'/memberships', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'equal("confirm", false)' ] + 'queries' => ['equal("confirm", false)'], ]); $this->assertEquals(200, $response['headers']['status-code']); $this->assertCount(0, $response['body']['memberships']); - $response = $this->client->call(Client::METHOD_GET, '/teams/' . $teamUid . '/memberships', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/teams/'.$teamUid.'/memberships', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'search' => $this->getUser()['$id'] + 'search' => $this->getUser()['$id'], ]); $this->assertEquals(200, $response['headers']['status-code']); @@ -91,11 +91,11 @@ trait TeamsBaseClient $this->assertContains('owner', $response['body']['memberships'][0]['roles']); $this->assertContains('player', $response['body']['memberships'][0]['roles']); - $response = $this->client->call(Client::METHOD_GET, '/teams/' . $teamUid . '/memberships', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/teams/'.$teamUid.'/memberships', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'search' => $membershipId + 'search' => $membershipId, ]); $this->assertEquals(200, $response['headers']['status-code']); @@ -107,11 +107,11 @@ trait TeamsBaseClient $this->assertContains('owner', $response['body']['memberships'][0]['roles']); $this->assertContains('player', $response['body']['memberships'][0]['roles']); - $response = $this->client->call(Client::METHOD_GET, '/teams/' . $teamUid . '/memberships', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/teams/'.$teamUid.'/memberships', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'search' => 'unknown' + 'search' => 'unknown', ]); $this->assertEquals(200, $response['headers']['status-code']); @@ -137,7 +137,7 @@ trait TeamsBaseClient /** * Test for SUCCESS */ - $response = $this->client->call(Client::METHOD_GET, '/teams/' . $teamUid . '/memberships/' . $membershipUid, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/teams/'.$teamUid.'/memberships/'.$membershipUid, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -157,15 +157,14 @@ trait TeamsBaseClient /** * Test for FAILURE */ - - $response = $this->client->call(Client::METHOD_GET, '/teams/' . $teamUid . '/memberships/' . $membershipUid . 'dasdasd', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/teams/'.$teamUid.'/memberships/'.$membershipUid.'dasdasd', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); $this->assertEquals(404, $response['headers']['status-code']); - $response = $this->client->call(Client::METHOD_GET, '/teams/' . $teamUid . '/memberships/' . $membershipUid, [ + $response = $this->client->call(Client::METHOD_GET, '/teams/'.$teamUid.'/memberships/'.$membershipUid, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ]); @@ -180,20 +179,20 @@ trait TeamsBaseClient { $teamUid = $data['teamUid'] ?? ''; $teamName = $data['teamName'] ?? ''; - $email = uniqid() . 'friend@localhost.test'; + $email = uniqid().'friend@localhost.test'; $name = 'Friend User'; /** * Test for SUCCESS */ - $response = $this->client->call(Client::METHOD_POST, '/teams/' . $teamUid . '/memberships', array_merge([ + $response = $this->client->call(Client::METHOD_POST, '/teams/'.$teamUid.'/memberships', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'email' => $email, 'name' => $name, 'roles' => ['admin', 'editor'], - 'url' => 'http://localhost:5000/join-us#title' + 'url' => 'http://localhost:5000/join-us#title', ]); $this->assertEquals(201, $response['headers']['status-code']); @@ -212,7 +211,7 @@ trait TeamsBaseClient $this->assertEquals($email, $lastEmail['to'][0]['address']); $this->assertEquals($name, $lastEmail['to'][0]['name']); - $this->assertEquals('Invitation to ' . $teamName . ' Team at ' . $this->getProject()['name'], $lastEmail['subject']); + $this->assertEquals('Invitation to '.$teamName.' Team at '.$this->getProject()['name'], $lastEmail['subject']); $secret = substr($lastEmail['text'], strpos($lastEmail['text'], '&secret=', 0) + 8, 256); $membershipUid = substr($lastEmail['text'], strpos($lastEmail['text'], '?membershipId=', 0) + 14, 20); @@ -221,51 +220,50 @@ trait TeamsBaseClient /** * Test for FAILURE */ - - $response = $this->client->call(Client::METHOD_POST, '/teams/' . $teamUid . '/memberships', array_merge([ + $response = $this->client->call(Client::METHOD_POST, '/teams/'.$teamUid.'/memberships', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'email' => $email, 'name' => 'Friend User', 'roles' => ['admin', 'editor'], - 'url' => 'http://localhost:5000/join-us#title' + 'url' => 'http://localhost:5000/join-us#title', ]); $this->assertEquals(409, $response['headers']['status-code']); - $response = $this->client->call(Client::METHOD_POST, '/teams/' . $teamUid . '/memberships', array_merge([ + $response = $this->client->call(Client::METHOD_POST, '/teams/'.$teamUid.'/memberships', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'email' => 'dasdkaskdjaskdjasjkd', 'name' => $name, 'roles' => ['admin', 'editor'], - 'url' => 'http://localhost:5000/join-us#title' + 'url' => 'http://localhost:5000/join-us#title', ]); $this->assertEquals(400, $response['headers']['status-code']); - $response = $this->client->call(Client::METHOD_POST, '/teams/' . $teamUid . '/memberships', array_merge([ + $response = $this->client->call(Client::METHOD_POST, '/teams/'.$teamUid.'/memberships', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'email' => $email, 'name' => $name, 'roles' => 'bad string', - 'url' => 'http://localhost:5000/join-us#title' + 'url' => 'http://localhost:5000/join-us#title', ]); $this->assertEquals(400, $response['headers']['status-code']); - $response = $this->client->call(Client::METHOD_POST, '/teams/' . $teamUid . '/memberships', array_merge([ + $response = $this->client->call(Client::METHOD_POST, '/teams/'.$teamUid.'/memberships', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'email' => $email, 'name' => $name, 'roles' => ['admin', 'editor'], - 'url' => 'http://example.com/join-us#title' // bad url + 'url' => 'http://example.com/join-us#title', // bad url ]); $this->assertEquals(400, $response['headers']['status-code']); @@ -277,7 +275,7 @@ trait TeamsBaseClient 'membershipUid' => $membershipUid, 'userUid' => $userUid, 'email' => $email, - 'name' => $name + 'name' => $name, ]; } @@ -286,7 +284,7 @@ trait TeamsBaseClient */ public function testListTeamMemberships($data): void { - $memberships = $this->client->call(Client::METHOD_GET, '/teams/' . $data['teamUid'] . '/memberships', array_merge([ + $memberships = $this->client->call(Client::METHOD_GET, '/teams/'.$data['teamUid'].'/memberships', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -296,11 +294,11 @@ trait TeamsBaseClient $this->assertNotEmpty($memberships['body']['memberships']); $this->assertCount(2, $memberships['body']['memberships']); - $response = $this->client->call(Client::METHOD_GET, '/teams/' . $data['teamUid'] . '/memberships', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/teams/'.$data['teamUid'].'/memberships', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'cursorAfter("' . $memberships['body']['memberships'][0]['$id'] . '")' ] + 'queries' => ['cursorAfter("'.$memberships['body']['memberships'][0]['$id'].'")'], ]); $this->assertEquals(200, $response['headers']['status-code']); @@ -325,7 +323,7 @@ trait TeamsBaseClient /** * Test for SUCCESS */ - $response = $this->client->call(Client::METHOD_PATCH, '/teams/' . $teamUid . '/memberships/' . $membershipUid . '/status', array_merge([ + $response = $this->client->call(Client::METHOD_PATCH, '/teams/'.$teamUid.'/memberships/'.$membershipUid.'/status', array_merge([ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], @@ -342,19 +340,18 @@ trait TeamsBaseClient $dateValidator = new DatetimeValidator(); $this->assertEquals(true, $dateValidator->isValid($response['body']['joined'])); $this->assertEquals(true, $response['body']['confirm']); - $session = $this->client->parseCookie((string)$response['headers']['set-cookie'])['a_session_' . $this->getProject()['$id']]; + $session = $this->client->parseCookie((string) $response['headers']['set-cookie'])['a_session_'.$this->getProject()['$id']]; $data['session'] = $session; $response = $this->client->call(Client::METHOD_GET, '/account', array_merge([ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ])); $this->assertEquals(true, $response['body']['emailVerification']); - /** [START] TESTS TO CHECK PASSWORD UPDATE OF NEW USER CREATED USING TEAM INVITE */ /** * New User tries to update password without old password -> SHOULD PASS @@ -363,9 +360,9 @@ trait TeamsBaseClient 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), [ - 'password' => 'new-password' + 'password' => 'new-password', ]); $this->assertEquals($response['headers']['status-code'], 200); @@ -383,7 +380,7 @@ trait TeamsBaseClient 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), [ 'password' => 'new-password', ]); @@ -396,10 +393,10 @@ trait TeamsBaseClient 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), [ 'password' => 'newer-password', - 'oldPassword' => 'new-password' + 'oldPassword' => 'new-password', ]); $this->assertEquals($response['headers']['status-code'], 200); @@ -415,7 +412,7 @@ trait TeamsBaseClient /** * Test for FAILURE */ - $response = $this->client->call(Client::METHOD_PATCH, '/teams/' . $teamUid . '/memberships/' . $membershipUid . '/status', array_merge([ + $response = $this->client->call(Client::METHOD_PATCH, '/teams/'.$teamUid.'/memberships/'.$membershipUid.'/status', array_merge([ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], @@ -426,7 +423,7 @@ trait TeamsBaseClient $this->assertEquals(401, $response['headers']['status-code']); - $response = $this->client->call(Client::METHOD_PATCH, '/teams/' . $teamUid . '/memberships/' . $membershipUid . '/status', array_merge([ + $response = $this->client->call(Client::METHOD_PATCH, '/teams/'.$teamUid.'/memberships/'.$membershipUid.'/status', array_merge([ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], @@ -437,7 +434,7 @@ trait TeamsBaseClient $this->assertEquals(400, $response['headers']['status-code']); - $response = $this->client->call(Client::METHOD_PATCH, '/teams/' . $teamUid . '/memberships/' . $membershipUid . '/status', array_merge([ + $response = $this->client->call(Client::METHOD_PATCH, '/teams/'.$teamUid.'/memberships/'.$membershipUid.'/status', array_merge([ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], @@ -448,7 +445,7 @@ trait TeamsBaseClient $this->assertEquals(401, $response['headers']['status-code']); - $response = $this->client->call(Client::METHOD_PATCH, '/teams/' . $teamUid . '/memberships/' . $membershipUid . '/status', array_merge([ + $response = $this->client->call(Client::METHOD_PATCH, '/teams/'.$teamUid.'/memberships/'.$membershipUid.'/status', array_merge([ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], @@ -459,7 +456,7 @@ trait TeamsBaseClient $this->assertEquals(400, $response['headers']['status-code']); - $response = $this->client->call(Client::METHOD_PATCH, '/teams/' . $teamUid . '/memberships/' . $membershipUid . '/status', array_merge([ + $response = $this->client->call(Client::METHOD_PATCH, '/teams/'.$teamUid.'/memberships/'.$membershipUid.'/status', array_merge([ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], @@ -486,12 +483,12 @@ trait TeamsBaseClient * Test for SUCCESS */ $roles = ['admin', 'editor', 'uncle']; - $response = $this->client->call(Client::METHOD_PATCH, '/teams/' . $teamUid . '/memberships/' . $membershipUid, array_merge([ + $response = $this->client->call(Client::METHOD_PATCH, '/teams/'.$teamUid.'/memberships/'.$membershipUid, array_merge([ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'roles' => $roles + 'roles' => $roles, ]); $this->assertEquals(200, $response['headers']['status-code']); @@ -506,12 +503,12 @@ trait TeamsBaseClient /** * Test for unknown team */ - $response = $this->client->call(Client::METHOD_PATCH, '/teams/' . 'abc' . '/memberships/' . $membershipUid, array_merge([ + $response = $this->client->call(Client::METHOD_PATCH, '/teams/'.'abc'.'/memberships/'.$membershipUid, array_merge([ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'roles' => $roles + 'roles' => $roles, ]); $this->assertEquals(404, $response['headers']['status-code']); @@ -519,27 +516,26 @@ trait TeamsBaseClient /** * Test for unknown membership ID */ - $response = $this->client->call(Client::METHOD_PATCH, '/teams/' . $teamUid . '/memberships/' . 'abc', array_merge([ + $response = $this->client->call(Client::METHOD_PATCH, '/teams/'.$teamUid.'/memberships/'.'abc', array_merge([ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'roles' => $roles + 'roles' => $roles, ]); $this->assertEquals(404, $response['headers']['status-code']); - /** * Test for when a user other than the owner tries to update membership */ - $response = $this->client->call(Client::METHOD_PATCH, '/teams/' . $teamUid . '/memberships/' . $membershipUid, [ + $response = $this->client->call(Client::METHOD_PATCH, '/teams/'.$teamUid.'/memberships/'.$membershipUid, [ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ], [ - 'roles' => $roles + 'roles' => $roles, ]); $this->assertEquals(401, $response['headers']['status-code']); @@ -548,7 +544,7 @@ trait TeamsBaseClient return $data; } - /** + /** * @depends testUpdateTeamMembershipRoles */ public function testDeleteTeamMembership($data): array @@ -557,7 +553,7 @@ trait TeamsBaseClient $membershipUid = $data['membershipUid'] ?? ''; $session = $data['session'] ?? ''; - $response = $this->client->call(Client::METHOD_GET, '/teams/' . $teamUid . '/memberships', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/teams/'.$teamUid.'/memberships', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -574,11 +570,11 @@ trait TeamsBaseClient /** * Test deleting a membership that does not exists */ - $response = $this->client->call(Client::METHOD_DELETE, '/teams/' . $teamUid . '/memberships/dne', [ + $response = $this->client->call(Client::METHOD_DELETE, '/teams/'.$teamUid.'/memberships/dne', [ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]); $this->assertEquals(404, $response['headers']['status-code']); @@ -586,11 +582,11 @@ trait TeamsBaseClient /** * Test deleting another user's membership */ - $response = $this->client->call(Client::METHOD_DELETE, '/teams/' . $teamUid . '/memberships/' . $ownerMembershipUid, [ + $response = $this->client->call(Client::METHOD_DELETE, '/teams/'.$teamUid.'/memberships/'.$ownerMembershipUid, [ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]); $this->assertEquals(401, $response['headers']['status-code']); @@ -602,17 +598,17 @@ trait TeamsBaseClient /** * Test for when a user other than the owner tries to delete their membership */ - $response = $this->client->call(Client::METHOD_DELETE, '/teams/' . $teamUid . '/memberships/' . $membershipUid, [ + $response = $this->client->call(Client::METHOD_DELETE, '/teams/'.$teamUid.'/memberships/'.$membershipUid, [ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]); $this->assertEquals(204, $response['headers']['status-code']); $this->assertEmpty($response['body']); - $response = $this->client->call(Client::METHOD_GET, '/teams/' . $teamUid . '/memberships', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/teams/'.$teamUid.'/memberships', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -623,7 +619,7 @@ trait TeamsBaseClient /** * Test for when the owner tries to delete their membership */ - $response = $this->client->call(Client::METHOD_DELETE, '/teams/' . $teamUid . '/memberships/' . $ownerMembershipUid, array_merge([ + $response = $this->client->call(Client::METHOD_DELETE, '/teams/'.$teamUid.'/memberships/'.$ownerMembershipUid, array_merge([ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], @@ -632,7 +628,7 @@ trait TeamsBaseClient $this->assertEquals(204, $response['headers']['status-code']); $this->assertEmpty($response['body']); - $response = $this->client->call(Client::METHOD_GET, '/teams/' . $teamUid . '/memberships/' . $ownerMembershipUid, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/teams/'.$teamUid.'/memberships/'.$ownerMembershipUid, array_merge([ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], diff --git a/tests/e2e/Services/Teams/TeamsBaseServer.php b/tests/e2e/Services/Teams/TeamsBaseServer.php index 0714192bdf..d0feeaf7bd 100644 --- a/tests/e2e/Services/Teams/TeamsBaseServer.php +++ b/tests/e2e/Services/Teams/TeamsBaseServer.php @@ -17,7 +17,7 @@ trait TeamsBaseServer /** * Test for SUCCESS */ - $response = $this->client->call(Client::METHOD_GET, '/teams/' . $id . '/memberships', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/teams/'.$id.'/memberships', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -43,7 +43,7 @@ trait TeamsBaseServer /** * Test for SUCCESS */ - $response = $this->client->call(Client::METHOD_GET, '/teams/' . $teamUid . '/memberships/' . $membershipUid, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/teams/'.$teamUid.'/memberships/'.$membershipUid, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -63,15 +63,14 @@ trait TeamsBaseServer /** * Test for FAILURE */ - - $response = $this->client->call(Client::METHOD_GET, '/teams/' . $teamUid . '/memberships/' . $membershipUid . 'dasdasd', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/teams/'.$teamUid.'/memberships/'.$membershipUid.'dasdasd', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); $this->assertEquals(404, $response['headers']['status-code']); - $response = $this->client->call(Client::METHOD_GET, '/teams/' . $teamUid . '/memberships/' . $membershipUid, [ + $response = $this->client->call(Client::METHOD_GET, '/teams/'.$teamUid.'/memberships/'.$membershipUid, [ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ]); @@ -86,19 +85,19 @@ trait TeamsBaseServer { $teamUid = $data['teamUid'] ?? ''; $teamName = $data['teamName'] ?? ''; - $email = uniqid() . 'friend@localhost.test'; + $email = uniqid().'friend@localhost.test'; /** * Test for SUCCESS */ - $response = $this->client->call(Client::METHOD_POST, '/teams/' . $teamUid . '/memberships', array_merge([ + $response = $this->client->call(Client::METHOD_POST, '/teams/'.$teamUid.'/memberships', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'email' => $email, 'name' => 'Friend User', 'roles' => ['admin', 'editor'], - 'url' => 'http://localhost:5000/join-us#title' + 'url' => 'http://localhost:5000/join-us#title', ]); $this->assertEquals(201, $response['headers']['status-code']); @@ -128,51 +127,50 @@ trait TeamsBaseServer /** * Test for FAILURE */ - - $response = $this->client->call(Client::METHOD_POST, '/teams/' . $teamUid . '/memberships', array_merge([ + $response = $this->client->call(Client::METHOD_POST, '/teams/'.$teamUid.'/memberships', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'email' => $email, 'name' => 'Friend User', 'roles' => ['admin', 'editor'], - 'url' => 'http://localhost:5000/join-us#title' + 'url' => 'http://localhost:5000/join-us#title', ]); $this->assertEquals(409, $response['headers']['status-code']); - $response = $this->client->call(Client::METHOD_POST, '/teams/' . $teamUid . '/memberships', array_merge([ + $response = $this->client->call(Client::METHOD_POST, '/teams/'.$teamUid.'/memberships', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'email' => 'dasdkaskdjaskdjasjkd', 'name' => 'Friend User', 'roles' => ['admin', 'editor'], - 'url' => 'http://localhost:5000/join-us#title' + 'url' => 'http://localhost:5000/join-us#title', ]); $this->assertEquals(400, $response['headers']['status-code']); - $response = $this->client->call(Client::METHOD_POST, '/teams/' . $teamUid . '/memberships', array_merge([ + $response = $this->client->call(Client::METHOD_POST, '/teams/'.$teamUid.'/memberships', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'email' => $email, 'name' => 'Friend User', 'roles' => 'bad string', - 'url' => 'http://localhost:5000/join-us#title' + 'url' => 'http://localhost:5000/join-us#title', ]); $this->assertEquals(400, $response['headers']['status-code']); - $response = $this->client->call(Client::METHOD_POST, '/teams/' . $teamUid . '/memberships', array_merge([ + $response = $this->client->call(Client::METHOD_POST, '/teams/'.$teamUid.'/memberships', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'email' => $email, 'name' => 'Friend User', 'roles' => ['admin', 'editor'], - 'url' => 'http://example.com/join-us#title' // bad url + 'url' => 'http://example.com/join-us#title', // bad url ]); $this->assertEquals(400, $response['headers']['status-code']); @@ -180,7 +178,7 @@ trait TeamsBaseServer return [ 'teamUid' => $teamUid, 'userUid' => $userUid, - 'membershipUid' => $membershipUid + 'membershipUid' => $membershipUid, ]; } @@ -196,12 +194,12 @@ trait TeamsBaseServer * Test for SUCCESS */ $roles = ['admin', 'editor', 'uncle']; - $response = $this->client->call(Client::METHOD_PATCH, '/teams/' . $teamUid . '/memberships/' . $membershipUid, array_merge([ + $response = $this->client->call(Client::METHOD_PATCH, '/teams/'.$teamUid.'/memberships/'.$membershipUid, array_merge([ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'roles' => $roles + 'roles' => $roles, ]); $this->assertEquals(200, $response['headers']['status-code']); @@ -213,19 +211,18 @@ trait TeamsBaseServer $this->assertEquals($roles[1], $response['body']['roles'][1]); $this->assertEquals($roles[2], $response['body']['roles'][2]); - /** * Test for FAILURE */ $apiKey = $this->getNewKey(['teams.read']); $roles = ['admin', 'editor', 'uncle']; - $response = $this->client->call(Client::METHOD_PATCH, '/teams/' . $teamUid . '/memberships/' . $membershipUid, [ + $response = $this->client->call(Client::METHOD_PATCH, '/teams/'.$teamUid.'/memberships/'.$membershipUid, [ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $apiKey + 'x-appwrite-key' => $apiKey, ], [ - 'roles' => $roles + 'roles' => $roles, ]); $this->assertEquals(401, $response['headers']['status-code']); @@ -242,12 +239,11 @@ trait TeamsBaseServer $userUid = $data['userUid'] ?? ''; /** Get Team Count */ - $response = $this->client->call(Client::METHOD_GET, '/teams/' . $teamUid, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/teams/'.$teamUid, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); - $this->assertEquals(200, $response['headers']['status-code']); $this->assertNotEmpty($response['body']['$id']); $this->assertEquals('Arsenal', $response['body']['name']); @@ -257,7 +253,7 @@ trait TeamsBaseServer $this->assertEquals(true, $dateValidator->isValid($response['body']['$createdAt'])); /** Delete User */ - $user = $this->client->call(Client::METHOD_DELETE, '/users/' . $userUid, array_merge([ + $user = $this->client->call(Client::METHOD_DELETE, '/users/'.$userUid, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -268,12 +264,11 @@ trait TeamsBaseServer sleep(5); /** Get Team Count */ - $response = $this->client->call(Client::METHOD_GET, '/teams/' . $teamUid, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/teams/'.$teamUid, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); - $this->assertEquals(200, $response['headers']['status-code']); $this->assertNotEmpty($response['body']['$id']); $this->assertEquals('Arsenal', $response['body']['name']); diff --git a/tests/e2e/Services/Teams/TeamsConsoleClientTest.php b/tests/e2e/Services/Teams/TeamsConsoleClientTest.php index e86c18a8e2..7c5a667bbc 100644 --- a/tests/e2e/Services/Teams/TeamsConsoleClientTest.php +++ b/tests/e2e/Services/Teams/TeamsConsoleClientTest.php @@ -3,8 +3,8 @@ namespace Tests\E2E\Services\Teams; use Tests\E2E\Client; -use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\ProjectConsole; +use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\SideClient; use Utopia\Database\Helpers\ID; @@ -22,10 +22,10 @@ class TeamsConsoleClientTest extends Scope */ $response = $this->client->call(Client::METHOD_POST, '/teams', \array_merge([ 'content-type' => 'application/json', - 'x-appwrite-project' => 'console' + 'x-appwrite-project' => 'console', ], $this->getHeaders()), [ 'name' => 'Latest version Team', - 'teamId' => ID::unique() + 'teamId' => ID::unique(), ]); $this->assertEquals(201, $response['headers']['status-code']); @@ -37,9 +37,9 @@ class TeamsConsoleClientTest extends Scope $response = $this->client->call(Client::METHOD_POST, '/teams', \array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => 'console', - 'x-appwrite-response-format' => '0.11.0' + 'x-appwrite-response-format' => '0.11.0', ], $this->getHeaders()), [ - 'name' => 'Latest version Team' + 'name' => 'Latest version Team', // Notice "teamId' is not defined ]); @@ -49,14 +49,14 @@ class TeamsConsoleClientTest extends Scope /** * Cleanup, so I don't invalidate some listTeams requests by mistake */ - $response = $this->client->call(Client::METHOD_DELETE, '/teams/' . $team1Id, \array_merge([ + $response = $this->client->call(Client::METHOD_DELETE, '/teams/'.$team1Id, \array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => 'console', ], $this->getHeaders())); $this->assertEquals(204, $response['headers']['status-code']); - $response = $this->client->call(Client::METHOD_DELETE, '/teams/' . $team2Id, \array_merge([ + $response = $this->client->call(Client::METHOD_DELETE, '/teams/'.$team2Id, \array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => 'console', ], $this->getHeaders())); @@ -71,18 +71,18 @@ class TeamsConsoleClientTest extends Scope { $teamUid = $data['teamUid'] ?? ''; $teamName = $data['teamName'] ?? ''; - $email = uniqid() . 'friend@localhost.test'; + $email = uniqid().'friend@localhost.test'; $name = 'Friend User'; $password = 'password'; // Create a user account before we create a invite so we can check if the user has permissions when it shouldn't $user = $this->client->call(Client::METHOD_POST, '/account', [ 'content-type' => 'application/json', - 'x-appwrite-project' => 'console'], [ - 'userId' => 'unique()', - 'email' => $email, - 'password' => $password, - 'name' => $name, + 'x-appwrite-project' => 'console', ], [ + 'userId' => 'unique()', + 'email' => $email, + 'password' => $password, + 'name' => $name, ], false); $this->assertEquals(201, $user['headers']['status-code']); @@ -90,14 +90,14 @@ class TeamsConsoleClientTest extends Scope /** * Test for SUCCESS */ - $response = $this->client->call(Client::METHOD_POST, '/teams/' . $teamUid . '/memberships', array_merge([ + $response = $this->client->call(Client::METHOD_POST, '/teams/'.$teamUid.'/memberships', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'email' => $email, 'name' => $name, 'roles' => ['admin', 'editor'], - 'url' => 'http://localhost:5000/join-us#title' + 'url' => 'http://localhost:5000/join-us#title', ]); $this->assertEquals(201, $response['headers']['status-code']); @@ -108,7 +108,7 @@ class TeamsConsoleClientTest extends Scope ], $this->getHeaders())); $this->assertEquals(401, $response['headers']['status-code']); - $response = $this->client->call(Client::METHOD_GET, '/teams/' . $teamUid . '/memberships', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/teams/'.$teamUid.'/memberships', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -117,7 +117,7 @@ class TeamsConsoleClientTest extends Scope $ownerMembershipUid = $response['body']['memberships'][1]['$id']; - $response = $this->client->call(Client::METHOD_DELETE, '/teams/' . $teamUid . '/memberships/' . $ownerMembershipUid, array_merge([ + $response = $this->client->call(Client::METHOD_DELETE, '/teams/'.$teamUid.'/memberships/'.$ownerMembershipUid, array_merge([ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], diff --git a/tests/e2e/Services/Teams/TeamsCustomClientTest.php b/tests/e2e/Services/Teams/TeamsCustomClientTest.php index 3b46cbcb7f..83a8080d1d 100644 --- a/tests/e2e/Services/Teams/TeamsCustomClientTest.php +++ b/tests/e2e/Services/Teams/TeamsCustomClientTest.php @@ -2,8 +2,8 @@ namespace Tests\E2E\Services\Teams; -use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\ProjectCustom; +use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\SideClient; class TeamsCustomClientTest extends Scope diff --git a/tests/e2e/Services/Teams/TeamsCustomServerTest.php b/tests/e2e/Services/Teams/TeamsCustomServerTest.php index ccbb598934..325b5892fc 100644 --- a/tests/e2e/Services/Teams/TeamsCustomServerTest.php +++ b/tests/e2e/Services/Teams/TeamsCustomServerTest.php @@ -5,7 +5,6 @@ namespace Tests\E2E\Services\Teams; use Tests\E2E\Scopes\ProjectCustom; use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\SideServer; -use Tests\E2E\Client; class TeamsCustomServerTest extends Scope { diff --git a/tests/e2e/Services/Users/UsersBase.php b/tests/e2e/Services/Users/UsersBase.php index fde65e94ec..5383c1235f 100644 --- a/tests/e2e/Services/Users/UsersBase.php +++ b/tests/e2e/Services/Users/UsersBase.php @@ -56,7 +56,7 @@ trait UsersBase $this->assertEquals(true, $res['body']['status']); $this->assertGreaterThan('2000-01-01 00:00:00', $res['body']['registration']); - /** + /** * Test Create with hashed passwords */ $res = $this->client->call(Client::METHOD_POST, '/users/md5', array_merge([ @@ -105,7 +105,7 @@ trait UsersBase 'email' => 'sha512@appwrite.io', 'password' => '4243da0a694e8a2f727c8060fe0507c8fa01ca68146c76d2c190805b638c20c6bf6ba04e21f11ae138785d0bff63c416e6f87badbffad37f6dee50094cc38c70', // appwrite (sha512) 'name' => 'SHA512 User', - 'passwordVersion' => 'sha512' + 'passwordVersion' => 'sha512', ]); $this->assertEquals($res['headers']['status-code'], 201); @@ -125,7 +125,7 @@ trait UsersBase 'passwordCpu' => 16384, 'passwordMemory' => 13, 'passwordParallel' => 2, - 'passwordLength' => 64 + 'passwordLength' => 64, ]); $this->assertEquals($res['headers']['status-code'], 201); @@ -180,7 +180,7 @@ trait UsersBase */ public function testCreateUserSessionHashed(array $data): void { - $userIds = [ 'md5', 'bcrypt', 'argon2', 'sha512', 'scrypt', 'phpass', 'scrypt-modified' ]; + $userIds = ['md5', 'bcrypt', 'argon2', 'sha512', 'scrypt', 'phpass', 'scrypt-modified']; foreach ($userIds as $userId) { // Ensure sessions can be created with hashed passwords @@ -189,7 +189,7 @@ trait UsersBase 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ]), [ - 'email' => $userId . '@appwrite.io', + 'email' => $userId.'@appwrite.io', 'password' => 'appwrite', ]); @@ -199,14 +199,14 @@ trait UsersBase foreach ($userIds as $userId) { // Ensure all passwords were re-hashed - $response = $this->client->call(Client::METHOD_GET, '/users/' . $userId, array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/users/'.$userId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); $this->assertEquals(200, $response['headers']['status-code']); $this->assertEquals($userId, $response['body']['$id']); - $this->assertEquals($userId . '@appwrite.io', $response['body']['email']); + $this->assertEquals($userId.'@appwrite.io', $response['body']['email']); $this->assertEquals('argon2', $response['body']['hash']); $this->assertStringStartsWith('$argon2', $response['body']['password']); } @@ -218,7 +218,7 @@ trait UsersBase 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ]), [ - 'email' => $userId . '@appwrite.io', + 'email' => $userId.'@appwrite.io', 'password' => 'appwrite', ]); @@ -236,7 +236,7 @@ trait UsersBase { /** * Test for SUCCESS - */ + */ // Email + password $response = $this->client->call(Client::METHOD_POST, '/users', array_merge([ @@ -347,7 +347,7 @@ trait UsersBase 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => ['equal("name", "' . $user1['name'] . '")'] + 'queries' => ['equal("name", "'.$user1['name'].'")'], ]); $this->assertEquals($response['headers']['status-code'], 200); @@ -360,7 +360,7 @@ trait UsersBase 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => ['equal("email", "' . $user1['email'] . '")'] + 'queries' => ['equal("email", "'.$user1['email'].'")'], ]); $this->assertEquals($response['headers']['status-code'], 200); @@ -373,7 +373,7 @@ trait UsersBase 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => ['equal("status", true)'] + 'queries' => ['equal("status", true)'], ]); $this->assertEquals($response['headers']['status-code'], 200); @@ -389,7 +389,7 @@ trait UsersBase 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => ['equal("status", false)'] + 'queries' => ['equal("status", false)'], ]); $this->assertEquals($response['headers']['status-code'], 200); @@ -401,7 +401,7 @@ trait UsersBase 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => ['equal("passwordUpdate", "' . $user1['passwordUpdate'] . '")'] + 'queries' => ['equal("passwordUpdate", "'.$user1['passwordUpdate'].'")'], ]); $this->assertEquals($response['headers']['status-code'], 200); @@ -414,7 +414,7 @@ trait UsersBase 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => ['equal("registration", "' . $user1['registration'] . '")'] + 'queries' => ['equal("registration", "'.$user1['registration'].'")'], ]); $this->assertEquals($response['headers']['status-code'], 200); @@ -427,7 +427,7 @@ trait UsersBase 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => ['equal("emailVerification", false)'] + 'queries' => ['equal("emailVerification", false)'], ]); $this->assertEquals($response['headers']['status-code'], 200); @@ -443,7 +443,7 @@ trait UsersBase 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => ['equal("emailVerification", true)'] + 'queries' => ['equal("emailVerification", true)'], ]); $this->assertEquals($response['headers']['status-code'], 200); @@ -455,7 +455,7 @@ trait UsersBase 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => ['equal("phoneVerification", false)'] + 'queries' => ['equal("phoneVerification", false)'], ]); $this->assertEquals($response['headers']['status-code'], 200); @@ -467,7 +467,7 @@ trait UsersBase 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => ['equal("phoneVerification", true)'] + 'queries' => ['equal("phoneVerification", true)'], ]); $this->assertEquals($response['headers']['status-code'], 200); @@ -479,7 +479,7 @@ trait UsersBase 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => ['cursorAfter("' . $data['userId'] . '")'] + 'queries' => ['cursorAfter("'.$data['userId'].'")'], ]); $this->assertEquals($response['headers']['status-code'], 200); @@ -492,7 +492,7 @@ trait UsersBase 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => ['cursorBefore("user1")'] + 'queries' => ['cursorBefore("user1")'], ]); $this->assertEquals($response['headers']['status-code'], 200); @@ -508,7 +508,7 @@ trait UsersBase 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'search' => "Ronaldo", + 'search' => 'Ronaldo', ]); $this->assertEquals($response['headers']['status-code'], 200); $this->assertNotEmpty($response['body']); @@ -520,7 +520,7 @@ trait UsersBase 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'search' => "cristiano.ronaldo@manchester-united.co.uk", + 'search' => 'cristiano.ronaldo@manchester-united.co.uk', ]); $this->assertEquals($response['headers']['status-code'], 200); $this->assertNotEmpty($response['body']); @@ -532,7 +532,7 @@ trait UsersBase 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'search' => "cristiano.ronaldo", + 'search' => 'cristiano.ronaldo', ]); $this->assertEquals($response['headers']['status-code'], 200); $this->assertNotEmpty($response['body']); @@ -544,7 +544,7 @@ trait UsersBase 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'search' => "manchester", + 'search' => 'manchester', ]); $this->assertEquals($response['headers']['status-code'], 200); $this->assertNotEmpty($response['body']); @@ -556,7 +556,7 @@ trait UsersBase 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'search' => "united.co.uk", + 'search' => 'united.co.uk', ]); $this->assertEquals($response['headers']['status-code'], 200); @@ -570,7 +570,7 @@ trait UsersBase 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'search' => "man", + 'search' => 'man', ]); $this->assertEquals($response['headers']['status-code'], 200); @@ -600,7 +600,7 @@ trait UsersBase 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => ['cursorAfter("unknown")'] + 'queries' => ['cursorAfter("unknown")'], ]); $this->assertEquals(400, $response['headers']['status-code']); @@ -614,7 +614,7 @@ trait UsersBase /** * Test for SUCCESS */ - $user = $this->client->call(Client::METHOD_GET, '/users/' . $data['userId'], array_merge([ + $user = $this->client->call(Client::METHOD_GET, '/users/'.$data['userId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -625,7 +625,7 @@ trait UsersBase $this->assertEquals($user['body']['status'], true); $this->assertGreaterThan('2000-01-01 00:00:00', $user['body']['registration']); - $sessions = $this->client->call(Client::METHOD_GET, '/users/' . $data['userId'] . '/sessions', array_merge([ + $sessions = $this->client->call(Client::METHOD_GET, '/users/'.$data['userId'].'/sessions', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -668,7 +668,7 @@ trait UsersBase /** * Test for SUCCESS */ - $user = $this->client->call(Client::METHOD_PATCH, '/users/' . $data['userId'] . '/name', array_merge([ + $user = $this->client->call(Client::METHOD_PATCH, '/users/'.$data['userId'].'/name', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -678,7 +678,7 @@ trait UsersBase $this->assertEquals($user['headers']['status-code'], 200); $this->assertEquals($user['body']['name'], 'Updated name'); - $user = $this->client->call(Client::METHOD_GET, '/users/' . $data['userId'], array_merge([ + $user = $this->client->call(Client::METHOD_GET, '/users/'.$data['userId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -735,7 +735,7 @@ trait UsersBase /** * Test for SUCCESS */ - $user = $this->client->call(Client::METHOD_PATCH, '/users/' . $data['userId'] . '/email', array_merge([ + $user = $this->client->call(Client::METHOD_PATCH, '/users/'.$data['userId'].'/email', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -745,7 +745,7 @@ trait UsersBase $this->assertEquals($user['headers']['status-code'], 200); $this->assertEquals($user['body']['email'], 'users.service@updated.com'); - $user = $this->client->call(Client::METHOD_GET, '/users/' . $data['userId'], array_merge([ + $user = $this->client->call(Client::METHOD_GET, '/users/'.$data['userId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -802,7 +802,7 @@ trait UsersBase /** * Test for SUCCESS */ - $user = $this->client->call(Client::METHOD_PATCH, '/users/' . $data['userId'] . '/password', array_merge([ + $user = $this->client->call(Client::METHOD_PATCH, '/users/'.$data['userId'].'/password', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -817,7 +817,7 @@ trait UsersBase 'x-appwrite-project' => $this->getProject()['$id'], ], [ 'email' => 'users.service@updated.com', - 'password' => 'password2' + 'password' => 'password2', ]); $this->assertEquals($session['headers']['status-code'], 201); @@ -834,7 +834,7 @@ trait UsersBase /** * Test for SUCCESS */ - $user = $this->client->call(Client::METHOD_PATCH, '/users/' . $data['userId'] . '/status', array_merge([ + $user = $this->client->call(Client::METHOD_PATCH, '/users/'.$data['userId'].'/status', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -844,7 +844,7 @@ trait UsersBase $this->assertEquals($user['headers']['status-code'], 200); $this->assertEquals($user['body']['status'], false); - $user = $this->client->call(Client::METHOD_GET, '/users/' . $data['userId'], array_merge([ + $user = $this->client->call(Client::METHOD_GET, '/users/'.$data['userId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -863,7 +863,7 @@ trait UsersBase /** * Test for SUCCESS */ - $user = $this->client->call(Client::METHOD_PATCH, '/users/' . $data['userId'] . '/verification', array_merge([ + $user = $this->client->call(Client::METHOD_PATCH, '/users/'.$data['userId'].'/verification', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -873,7 +873,7 @@ trait UsersBase $this->assertEquals($user['headers']['status-code'], 200); $this->assertEquals($user['body']['emailVerification'], true); - $user = $this->client->call(Client::METHOD_GET, '/users/' . $data['userId'], array_merge([ + $user = $this->client->call(Client::METHOD_GET, '/users/'.$data['userId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -893,7 +893,7 @@ trait UsersBase /** * Test for SUCCESS */ - $user = $this->client->call(Client::METHOD_PATCH, '/users/' . $data['userId'] . '/prefs', array_merge([ + $user = $this->client->call(Client::METHOD_PATCH, '/users/'.$data['userId'].'/prefs', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -907,7 +907,7 @@ trait UsersBase $this->assertEquals($user['body']['funcKey1'], 'funcValue1'); $this->assertEquals($user['body']['funcKey2'], 'funcValue2'); - $user = $this->client->call(Client::METHOD_GET, '/users/' . $data['userId'] . '/prefs', array_merge([ + $user = $this->client->call(Client::METHOD_GET, '/users/'.$data['userId'].'/prefs', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -921,7 +921,7 @@ trait UsersBase /** * Test for FAILURE */ - $user = $this->client->call(Client::METHOD_PATCH, '/users/' . $data['userId'] . '/prefs', array_merge([ + $user = $this->client->call(Client::METHOD_PATCH, '/users/'.$data['userId'].'/prefs', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -930,7 +930,7 @@ trait UsersBase $this->assertEquals($user['headers']['status-code'], 400); - $user = $this->client->call(Client::METHOD_PATCH, '/users/' . $data['userId'] . '/prefs', array_merge([ + $user = $this->client->call(Client::METHOD_PATCH, '/users/'.$data['userId'].'/prefs', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -948,8 +948,8 @@ trait UsersBase /** * Test for SUCCESS */ - $updatedNumber = "+910000000000"; //dummy number - $user = $this->client->call(Client::METHOD_PATCH, '/users/' . $data['userId'] . '/phone', array_merge([ + $updatedNumber = '+910000000000'; //dummy number + $user = $this->client->call(Client::METHOD_PATCH, '/users/'.$data['userId'].'/phone', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -959,7 +959,7 @@ trait UsersBase $this->assertEquals($user['headers']['status-code'], 200); $this->assertEquals($user['body']['phone'], $updatedNumber); - $user = $this->client->call(Client::METHOD_GET, '/users/' . $data['userId'], array_merge([ + $user = $this->client->call(Client::METHOD_GET, '/users/'.$data['userId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -967,16 +967,15 @@ trait UsersBase $this->assertEquals($user['headers']['status-code'], 200); $this->assertEquals($user['body']['phone'], $updatedNumber); - /** + /** * Test for FAILURE */ - - $errorType = "user_phone_already_exists"; - $user1Id = "user1"; + $errorType = 'user_phone_already_exists'; + $user1Id = 'user1'; $statusCodeForUserPhoneAlredyExists = 409; // adding same number ($updatedNumber) to different user i.e user1 - $response = $this->client->call(Client::METHOD_PATCH, '/users/' . $user1Id . '/phone', array_merge([ + $response = $this->client->call(Client::METHOD_PATCH, '/users/'.$user1Id.'/phone', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -995,7 +994,7 @@ trait UsersBase public function testUpdateUserNumberSearch($data): void { $id = $data['userId'] ?? ''; - $newNumber = "+910000000000"; //dummy number + $newNumber = '+910000000000'; //dummy number /** * Test for SUCCESS @@ -1015,7 +1014,6 @@ trait UsersBase $this->assertEquals($response['body']['users'][0]['phone'], $newNumber); } - /** * @depends testGetUser */ @@ -1024,7 +1022,7 @@ trait UsersBase /** * Test for SUCCESS */ - $logs = $this->client->call(Client::METHOD_GET, '/users/' . $data['userId'] . '/logs', array_merge([ + $logs = $this->client->call(Client::METHOD_GET, '/users/'.$data['userId'].'/logs', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -1033,11 +1031,11 @@ trait UsersBase $this->assertIsArray($logs['body']['logs']); $this->assertIsNumeric($logs['body']['total']); - $logs = $this->client->call(Client::METHOD_GET, '/users/' . $data['userId'] . '/logs', array_merge([ + $logs = $this->client->call(Client::METHOD_GET, '/users/'.$data['userId'].'/logs', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'limit(1)' ], + 'queries' => ['limit(1)'], ]); $this->assertEquals($logs['headers']['status-code'], 200); @@ -1045,22 +1043,22 @@ trait UsersBase $this->assertLessThanOrEqual(1, count($logs['body']['logs'])); $this->assertIsNumeric($logs['body']['total']); - $logs = $this->client->call(Client::METHOD_GET, '/users/' . $data['userId'] . '/logs', array_merge([ + $logs = $this->client->call(Client::METHOD_GET, '/users/'.$data['userId'].'/logs', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'offset(1)' ], + 'queries' => ['offset(1)'], ]); $this->assertEquals($logs['headers']['status-code'], 200); $this->assertIsArray($logs['body']['logs']); $this->assertIsNumeric($logs['body']['total']); - $logs = $this->client->call(Client::METHOD_GET, '/users/' . $data['userId'] . '/logs', array_merge([ + $logs = $this->client->call(Client::METHOD_GET, '/users/'.$data['userId'].'/logs', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => [ 'limit(1)', 'offset(1)' ], + 'queries' => ['limit(1)', 'offset(1)'], ]); $this->assertEquals($logs['headers']['status-code'], 200); @@ -1071,65 +1069,65 @@ trait UsersBase /** * Test for FAILURE */ - $response = $this->client->call(Client::METHOD_GET, '/users/' . $data['userId'] . '/logs', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/users/'.$data['userId'].'/logs', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => ['limit(-1)'] + 'queries' => ['limit(-1)'], ]); $this->assertEquals($response['headers']['status-code'], 400); - $response = $this->client->call(Client::METHOD_GET, '/users/' . $data['userId'] . '/logs', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/users/'.$data['userId'].'/logs', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => ['limit(101)'] + 'queries' => ['limit(101)'], ]); $this->assertEquals($response['headers']['status-code'], 400); - $response = $this->client->call(Client::METHOD_GET, '/users/' . $data['userId'] . '/logs', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/users/'.$data['userId'].'/logs', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => ['offset(-1)'] + 'queries' => ['offset(-1)'], ]); $this->assertEquals($response['headers']['status-code'], 400); - $response = $this->client->call(Client::METHOD_GET, '/users/' . $data['userId'] . '/logs', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/users/'.$data['userId'].'/logs', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => ['offset(5001)'] + 'queries' => ['offset(5001)'], ]); $this->assertEquals($response['headers']['status-code'], 400); - $response = $this->client->call(Client::METHOD_GET, '/users/' . $data['userId'] . '/logs', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/users/'.$data['userId'].'/logs', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => ['equal("$id", "asdf")'] + 'queries' => ['equal("$id", "asdf")'], ]); $this->assertEquals($response['headers']['status-code'], 400); - $response = $this->client->call(Client::METHOD_GET, '/users/' . $data['userId'] . '/logs', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/users/'.$data['userId'].'/logs', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => ['orderAsc("$id")'] + 'queries' => ['orderAsc("$id")'], ]); $this->assertEquals($response['headers']['status-code'], 400); - $response = $this->client->call(Client::METHOD_GET, '/users/' . $data['userId'] . '/logs', array_merge([ + $response = $this->client->call(Client::METHOD_GET, '/users/'.$data['userId'].'/logs', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'queries' => ['cursorAsc("$id")'] + 'queries' => ['cursorAsc("$id")'], ]); $this->assertEquals($response['headers']['status-code'], 400); @@ -1143,7 +1141,7 @@ trait UsersBase /** * Test for SUCCESS */ - $user = $this->client->call(Client::METHOD_DELETE, '/users/' . $data['userId'], array_merge([ + $user = $this->client->call(Client::METHOD_DELETE, '/users/'.$data['userId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -1153,7 +1151,7 @@ trait UsersBase /** * Test for FAILURE */ - $user = $this->client->call(Client::METHOD_DELETE, '/users/' . $data['userId'], array_merge([ + $user = $this->client->call(Client::METHOD_DELETE, '/users/'.$data['userId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); diff --git a/tests/e2e/Services/Users/UsersConsoleClientTest.php b/tests/e2e/Services/Users/UsersConsoleClientTest.php index 9cc23e825a..de9e4f87fe 100644 --- a/tests/e2e/Services/Users/UsersConsoleClientTest.php +++ b/tests/e2e/Services/Users/UsersConsoleClientTest.php @@ -2,9 +2,9 @@ namespace Tests\E2E\Services\Users; -use Tests\E2E\Scopes\Scope; -use Tests\E2E\Scopes\ProjectCustom; use Tests\E2E\Client; +use Tests\E2E\Scopes\ProjectCustom; +use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\SideConsole; class UsersConsoleClientTest extends Scope @@ -17,23 +17,22 @@ class UsersConsoleClientTest extends Scope /** * Test for FAILURE */ - $response = $this->client->call(Client::METHOD_GET, '/users/usage', array_merge([ 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'] + 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'range' => '32h', - 'provider' => 'email' + 'provider' => 'email', ]); $this->assertEquals($response['headers']['status-code'], 400); $response = $this->client->call(Client::METHOD_GET, '/users/usage', array_merge([ 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'] + 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'range' => '24h', - 'provider' => 'some-random-provider' + 'provider' => 'some-random-provider', ]); $this->assertEquals($response['headers']['status-code'], 400); @@ -43,10 +42,10 @@ class UsersConsoleClientTest extends Scope */ $response = $this->client->call(Client::METHOD_GET, '/users/usage', array_merge([ 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'] + 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'range' => '24h', - 'provider' => 'email' + 'provider' => 'email', ]); $this->assertEquals($response['headers']['status-code'], 200); @@ -63,9 +62,9 @@ class UsersConsoleClientTest extends Scope $response = $this->client->call(Client::METHOD_GET, '/users/usage', array_merge([ 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'] + 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'range' => '24h' + 'range' => '24h', ]); $this->assertEquals($response['headers']['status-code'], 200); diff --git a/tests/e2e/Services/Users/UsersCustomServerTest.php b/tests/e2e/Services/Users/UsersCustomServerTest.php index 6b9a990d4c..2442f1bf7d 100644 --- a/tests/e2e/Services/Users/UsersCustomServerTest.php +++ b/tests/e2e/Services/Users/UsersCustomServerTest.php @@ -2,7 +2,6 @@ namespace Tests\E2E\Services\Users; -use Tests\E2E\Client; use Tests\E2E\Scopes\ProjectCustom; use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\SideServer; diff --git a/tests/e2e/Services/Webhooks/WebhooksBase.php b/tests/e2e/Services/Webhooks/WebhooksBase.php index 1afa9cdb52..217548350e 100644 --- a/tests/e2e/Services/Webhooks/WebhooksBase.php +++ b/tests/e2e/Services/Webhooks/WebhooksBase.php @@ -15,10 +15,10 @@ trait WebhooksBase public static function getWebhookSignature(array $webhook, string $signatureKey): string { $payload = json_encode($webhook['data']); - $url = $webhook['url']; - return base64_encode(hash_hmac('sha1', $url . $payload, $signatureKey, true)); - } + $url = $webhook['url']; + return base64_encode(hash_hmac('sha1', $url.$payload, $signatureKey, true)); + } public function testCreateCollection(): array { @@ -26,23 +26,23 @@ trait WebhooksBase * Create database */ $database = $this->client->call(Client::METHOD_POST, '/databases', array_merge([ - 'content-type' => 'application/json', - 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'content-type' => 'application/json', + 'x-appwrite-project' => $this->getProject()['$id'], + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ - 'databaseId' => ID::unique(), - 'name' => 'Actors DB', + 'databaseId' => ID::unique(), + 'name' => 'Actors DB', ]); $databaseId = $database['body']['$id']; - /** + /** * Test for SUCCESS */ - $actors = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections', array_merge([ + $actors = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'collectionId' => ID::unique(), 'name' => 'Actors', @@ -66,8 +66,8 @@ trait WebhooksBase $this->assertEquals($webhook['method'], 'POST'); $this->assertEquals($webhook['headers']['Content-Type'], 'application/json'); $this->assertEquals($webhook['headers']['User-Agent'], 'Appwrite-Server vdev. Please report abuse at security@appwrite.io'); - $this->assertStringContainsString('databases.' . $databaseId . '.collections.*', $webhook['headers']['X-Appwrite-Webhook-Events']); - $this->assertStringContainsString('databases.' . $databaseId . '.collections.*.create', $webhook['headers']['X-Appwrite-Webhook-Events']); + $this->assertStringContainsString('databases.'.$databaseId.'.collections.*', $webhook['headers']['X-Appwrite-Webhook-Events']); + $this->assertStringContainsString('databases.'.$databaseId.'.collections.*.create', $webhook['headers']['X-Appwrite-Webhook-Events']); $this->assertStringContainsString("databases.{$databaseId}.collections.{$actorsId}", $webhook['headers']['X-Appwrite-Webhook-Events']); $this->assertStringContainsString("databases.{$databaseId}.collections.{$actorsId}.create", $webhook['headers']['X-Appwrite-Webhook-Events']); $this->assertEquals($webhook['headers']['X-Appwrite-Webhook-Signature'], $signatureExpected); @@ -90,30 +90,30 @@ trait WebhooksBase $actorsId = $data['actorsId']; $databaseId = $data['databaseId']; - $firstName = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $actorsId . '/attributes/string', array_merge([ + $firstName = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$actorsId.'/attributes/string', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'firstName', 'size' => 256, 'required' => true, ]); - $lastName = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $actorsId . '/attributes/string', array_merge([ + $lastName = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$actorsId.'/attributes/string', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'lastName', 'size' => 256, 'required' => true, ]); - $extra = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $actorsId . '/attributes/string', array_merge([ + $extra = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$actorsId.'/attributes/string', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'extra', 'size' => 64, @@ -138,9 +138,9 @@ trait WebhooksBase $this->assertEquals($webhook['method'], 'POST'); $this->assertEquals($webhook['headers']['Content-Type'], 'application/json'); $this->assertEquals($webhook['headers']['User-Agent'], 'Appwrite-Server vdev. Please report abuse at security@appwrite.io'); - $this->assertStringContainsString('databases.' . $databaseId . '.collections.*', $webhook['headers']['X-Appwrite-Webhook-Events']); - $this->assertStringContainsString('databases.' . $databaseId . '.collections.*.attributes.*', $webhook['headers']['X-Appwrite-Webhook-Events']); - $this->assertStringContainsString('databases.' . $databaseId . '.collections.*.attributes.*.create', $webhook['headers']['X-Appwrite-Webhook-Events']); + $this->assertStringContainsString('databases.'.$databaseId.'.collections.*', $webhook['headers']['X-Appwrite-Webhook-Events']); + $this->assertStringContainsString('databases.'.$databaseId.'.collections.*.attributes.*', $webhook['headers']['X-Appwrite-Webhook-Events']); + $this->assertStringContainsString('databases.'.$databaseId.'.collections.*.attributes.*.create', $webhook['headers']['X-Appwrite-Webhook-Events']); $this->assertStringContainsString("databases.{$databaseId}.collections.{$actorsId}", $webhook['headers']['X-Appwrite-Webhook-Events']); $this->assertStringContainsString("databases.{$databaseId}.collections.{$actorsId}.attributes.*", $webhook['headers']['X-Appwrite-Webhook-Events']); $this->assertStringContainsString("databases.{$databaseId}.collections.{$actorsId}.attributes.*.create", $webhook['headers']['X-Appwrite-Webhook-Events']); @@ -150,10 +150,10 @@ trait WebhooksBase $this->assertNotEmpty($webhook['data']['key']); $this->assertEquals($webhook['data']['key'], 'extra'); - $removed = $this->client->call(Client::METHOD_DELETE, '/databases/' . $databaseId . '/collections/' . $data['actorsId'] . '/attributes/' . $extra['body']['key'], array_merge([ + $removed = $this->client->call(Client::METHOD_DELETE, '/databases/'.$databaseId.'/collections/'.$data['actorsId'].'/attributes/'.$extra['body']['key'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ])); $this->assertEquals(204, $removed['headers']['status-code']); @@ -164,9 +164,9 @@ trait WebhooksBase // $this->assertEquals($webhook['method'], 'DELETE'); $this->assertEquals($webhook['headers']['Content-Type'], 'application/json'); $this->assertEquals($webhook['headers']['User-Agent'], 'Appwrite-Server vdev. Please report abuse at security@appwrite.io'); - $this->assertStringContainsString('databases.' . $databaseId . '.collections.*', $webhook['headers']['X-Appwrite-Webhook-Events']); - $this->assertStringContainsString('databases.' . $databaseId . '.collections.*.attributes.*', $webhook['headers']['X-Appwrite-Webhook-Events']); - $this->assertStringContainsString('databases.' . $databaseId . '.collections.*.attributes.*.delete', $webhook['headers']['X-Appwrite-Webhook-Events']); + $this->assertStringContainsString('databases.'.$databaseId.'.collections.*', $webhook['headers']['X-Appwrite-Webhook-Events']); + $this->assertStringContainsString('databases.'.$databaseId.'.collections.*.attributes.*', $webhook['headers']['X-Appwrite-Webhook-Events']); + $this->assertStringContainsString('databases.'.$databaseId.'.collections.*.attributes.*.delete', $webhook['headers']['X-Appwrite-Webhook-Events']); $this->assertStringContainsString("databases.{$databaseId}.collections.{$actorsId}", $webhook['headers']['X-Appwrite-Webhook-Events']); $this->assertStringContainsString("databases.{$databaseId}.collections.{$actorsId}.attributes.*", $webhook['headers']['X-Appwrite-Webhook-Events']); $this->assertStringContainsString("databases.{$databaseId}.collections.{$actorsId}.attributes.*.delete", $webhook['headers']['X-Appwrite-Webhook-Events']); @@ -190,7 +190,7 @@ trait WebhooksBase /** * Test for SUCCESS */ - $document = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $actorsId . '/documents', array_merge([ + $document = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$actorsId.'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -217,9 +217,9 @@ trait WebhooksBase $this->assertEquals($webhook['method'], 'POST'); $this->assertEquals($webhook['headers']['Content-Type'], 'application/json'); $this->assertEquals($webhook['headers']['User-Agent'], 'Appwrite-Server vdev. Please report abuse at security@appwrite.io'); - $this->assertStringContainsString('databases.' . $databaseId . '.collections.*', $webhook['headers']['X-Appwrite-Webhook-Events']); - $this->assertStringContainsString('databases.' . $databaseId . '.collections.*.documents.*', $webhook['headers']['X-Appwrite-Webhook-Events']); - $this->assertStringContainsString('databases.' . $databaseId . '.collections.*.documents.*.create', $webhook['headers']['X-Appwrite-Webhook-Events']); + $this->assertStringContainsString('databases.'.$databaseId.'.collections.*', $webhook['headers']['X-Appwrite-Webhook-Events']); + $this->assertStringContainsString('databases.'.$databaseId.'.collections.*.documents.*', $webhook['headers']['X-Appwrite-Webhook-Events']); + $this->assertStringContainsString('databases.'.$databaseId.'.collections.*.documents.*.create', $webhook['headers']['X-Appwrite-Webhook-Events']); $this->assertStringContainsString("databases.{$databaseId}.collections.*.documents.{$documentId}", $webhook['headers']['X-Appwrite-Webhook-Events']); $this->assertStringContainsString("databases.{$databaseId}.collections.*.documents.{$documentId}.create", $webhook['headers']['X-Appwrite-Webhook-Events']); $this->assertStringContainsString("databases.{$databaseId}.collections.{$actorsId}", $webhook['headers']['X-Appwrite-Webhook-Events']); @@ -253,7 +253,7 @@ trait WebhooksBase /** * Test for SUCCESS */ - $document = $this->client->call(Client::METHOD_PATCH, '/databases/' . $databaseId . '/collections/' . $actorsId . '/documents/' . $data['documentId'], array_merge([ + $document = $this->client->call(Client::METHOD_PATCH, '/databases/'.$databaseId.'/collections/'.$actorsId.'/documents/'.$data['documentId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -279,9 +279,9 @@ trait WebhooksBase $this->assertEquals($webhook['method'], 'POST'); $this->assertEquals($webhook['headers']['Content-Type'], 'application/json'); $this->assertEquals($webhook['headers']['User-Agent'], 'Appwrite-Server vdev. Please report abuse at security@appwrite.io'); - $this->assertStringContainsString('databases.' . $databaseId . '.collections.*', $webhook['headers']['X-Appwrite-Webhook-Events']); - $this->assertStringContainsString('databases.' . $databaseId . '.collections.*.documents.*', $webhook['headers']['X-Appwrite-Webhook-Events']); - $this->assertStringContainsString('databases.' . $databaseId . '.collections.*.documents.*.update', $webhook['headers']['X-Appwrite-Webhook-Events']); + $this->assertStringContainsString('databases.'.$databaseId.'.collections.*', $webhook['headers']['X-Appwrite-Webhook-Events']); + $this->assertStringContainsString('databases.'.$databaseId.'.collections.*.documents.*', $webhook['headers']['X-Appwrite-Webhook-Events']); + $this->assertStringContainsString('databases.'.$databaseId.'.collections.*.documents.*.update', $webhook['headers']['X-Appwrite-Webhook-Events']); $this->assertStringContainsString("databases.{$databaseId}.collections.*.documents.{$documentId}", $webhook['headers']['X-Appwrite-Webhook-Events']); $this->assertStringContainsString("databases.{$databaseId}.collections.*.documents.{$documentId}.update", $webhook['headers']['X-Appwrite-Webhook-Events']); $this->assertStringContainsString("databases.{$databaseId}.collections.{$actorsId}", $webhook['headers']['X-Appwrite-Webhook-Events']); @@ -314,7 +314,7 @@ trait WebhooksBase /** * Test for SUCCESS */ - $document = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $actorsId . '/documents', array_merge([ + $document = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$actorsId.'/documents', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -336,7 +336,7 @@ trait WebhooksBase $this->assertEquals($document['headers']['status-code'], 201); $this->assertNotEmpty($document['body']['$id']); - $document = $this->client->call(Client::METHOD_DELETE, '/databases/' . $databaseId . '/collections/' . $actorsId . '/documents/' . $document['body']['$id'], array_merge([ + $document = $this->client->call(Client::METHOD_DELETE, '/databases/'.$databaseId.'/collections/'.$actorsId.'/documents/'.$document['body']['$id'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -349,9 +349,9 @@ trait WebhooksBase $this->assertEquals($webhook['method'], 'POST'); $this->assertEquals($webhook['headers']['Content-Type'], 'application/json'); $this->assertEquals($webhook['headers']['User-Agent'], 'Appwrite-Server vdev. Please report abuse at security@appwrite.io'); - $this->assertStringContainsString('databases.' . $databaseId . '.collections.*', $webhook['headers']['X-Appwrite-Webhook-Events']); - $this->assertStringContainsString('databases.' . $databaseId . '.collections.*.documents.*', $webhook['headers']['X-Appwrite-Webhook-Events']); - $this->assertStringContainsString('databases.' . $databaseId . '.collections.*.documents.*.delete', $webhook['headers']['X-Appwrite-Webhook-Events']); + $this->assertStringContainsString('databases.'.$databaseId.'.collections.*', $webhook['headers']['X-Appwrite-Webhook-Events']); + $this->assertStringContainsString('databases.'.$databaseId.'.collections.*.documents.*', $webhook['headers']['X-Appwrite-Webhook-Events']); + $this->assertStringContainsString('databases.'.$databaseId.'.collections.*.documents.*.delete', $webhook['headers']['X-Appwrite-Webhook-Events']); $this->assertStringContainsString("databases.{$databaseId}.collections.*.documents.{$documentId}", $webhook['headers']['X-Appwrite-Webhook-Events']); $this->assertStringContainsString("databases.{$databaseId}.collections.*.documents.{$documentId}.delete", $webhook['headers']['X-Appwrite-Webhook-Events']); $this->assertStringContainsString("databases.{$databaseId}.collections.{$actorsId}", $webhook['headers']['X-Appwrite-Webhook-Events']); @@ -372,7 +372,6 @@ trait WebhooksBase return $data; } - public function testCreateStorageBucket(): array { /** @@ -381,7 +380,7 @@ trait WebhooksBase $bucket = $this->client->call(Client::METHOD_POST, '/storage/buckets', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'bucketId' => ID::unique(), 'name' => 'Test Bucket', @@ -430,10 +429,10 @@ trait WebhooksBase /** * Test for SUCCESS */ - $bucket = $this->client->call(Client::METHOD_PUT, '/storage/buckets/' . $data['bucketId'], array_merge([ + $bucket = $this->client->call(Client::METHOD_PUT, '/storage/buckets/'.$data['bucketId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'name' => 'Test Bucket Updated', 'fileSecurity' => true, @@ -473,10 +472,10 @@ trait WebhooksBase $bucketId = $data['bucketId']; //enable bucket - $bucket = $this->client->call(Client::METHOD_PUT, '/storage/buckets/' . $data['bucketId'], array_merge([ + $bucket = $this->client->call(Client::METHOD_PUT, '/storage/buckets/'.$data['bucketId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'name' => 'Test Bucket Updated', 'fileSecurity' => true, @@ -487,12 +486,12 @@ trait WebhooksBase /** * Test for SUCCESS */ - $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/' . $data['bucketId'] . '/files', array_merge([ + $file = $this->client->call(Client::METHOD_POST, '/storage/buckets/'.$data['bucketId'].'/files', array_merge([ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'fileId' => ID::unique(), - 'file' => new CURLFile(realpath(__DIR__ . '/../../../resources/logo.png'), 'image/png', 'logo.png'), + 'file' => new CURLFile(realpath(__DIR__.'/../../../resources/logo.png'), 'image/png', 'logo.png'), 'permissions' => [ Permission::read(Role::any()), Permission::update(Role::any()), @@ -551,7 +550,7 @@ trait WebhooksBase /** * Test for SUCCESS */ - $file = $this->client->call(Client::METHOD_PUT, '/storage/buckets/' . $bucketId . '/files/' . $fileId, array_merge([ + $file = $this->client->call(Client::METHOD_PUT, '/storage/buckets/'.$bucketId.'/files/'.$fileId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -608,7 +607,7 @@ trait WebhooksBase /** * Test for SUCCESS */ - $file = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/' . $data['bucketId'] . '/files/' . $data['fileId'], array_merge([ + $file = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/'.$data['bucketId'].'/files/'.$data['fileId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -657,10 +656,10 @@ trait WebhooksBase /** * Test for SUCCESS */ - $bucket = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/' . $bucketId, array_merge([ + $bucket = $this->client->call(Client::METHOD_DELETE, '/storage/buckets/'.$bucketId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ])); $this->assertEquals($bucket['headers']['status-code'], 204); @@ -696,7 +695,7 @@ trait WebhooksBase 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'teamId' => ID::unique(), - 'name' => 'Arsenal' + 'name' => 'Arsenal', ]); $teamId = $team['body']['$id']; @@ -740,11 +739,11 @@ trait WebhooksBase /** * Test for SUCCESS */ - $team = $this->client->call(Client::METHOD_PUT, '/teams/' . $teamId, array_merge([ + $team = $this->client->call(Client::METHOD_PUT, '/teams/'.$teamId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'name' => 'Demo New' + 'name' => 'Demo New', ]); $this->assertEquals(200, $team['headers']['status-code']); @@ -787,7 +786,7 @@ trait WebhooksBase 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'teamId' => ID::unique(), - 'name' => 'Chelsea' + 'name' => 'Chelsea', ]); $teamId = $team['body']['$id']; @@ -795,7 +794,7 @@ trait WebhooksBase $this->assertEquals(201, $team['headers']['status-code']); $this->assertNotEmpty($team['body']['$id']); - $team = $this->client->call(Client::METHOD_DELETE, '/teams/' . $team['body']['$id'], array_merge([ + $team = $this->client->call(Client::METHOD_DELETE, '/teams/'.$team['body']['$id'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -833,19 +832,19 @@ trait WebhooksBase public function testCreateTeamMembership($data): array { $teamId = $data['teamId'] ?? ''; - $email = uniqid() . 'friend@localhost.test'; + $email = uniqid().'friend@localhost.test'; /** * Test for SUCCESS */ - $team = $this->client->call(Client::METHOD_POST, '/teams/' . $teamId . '/memberships', array_merge([ + $team = $this->client->call(Client::METHOD_POST, '/teams/'.$teamId.'/memberships', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'email' => $email, 'name' => 'Friend User', 'roles' => ['admin', 'editor'], - 'url' => 'http://localhost:5000/join-us#title' + 'url' => 'http://localhost:5000/join-us#title', ]); $this->assertEquals(201, $team['headers']['status-code']); @@ -901,19 +900,19 @@ trait WebhooksBase public function testDeleteTeamMembership($data): void { $teamId = $data['teamId'] ?? ''; - $email = uniqid() . 'friend@localhost.test'; + $email = uniqid().'friend@localhost.test'; /** * Test for SUCCESS */ - $team = $this->client->call(Client::METHOD_POST, '/teams/' . $teamId . '/memberships', array_merge([ + $team = $this->client->call(Client::METHOD_POST, '/teams/'.$teamId.'/memberships', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'email' => $email, 'name' => 'Friend User', 'roles' => ['admin', 'editor'], - 'url' => 'http://localhost:5000/join-us#title' + 'url' => 'http://localhost:5000/join-us#title', ]); $membershipId = $team['body']['$id'] ?? ''; @@ -921,7 +920,7 @@ trait WebhooksBase $this->assertEquals(201, $team['headers']['status-code']); $this->assertNotEmpty($team['body']['$id']); - $team = $this->client->call(Client::METHOD_DELETE, '/teams/' . $teamId . '/memberships/' . $team['body']['$id'], array_merge([ + $team = $this->client->call(Client::METHOD_DELETE, '/teams/'.$teamId.'/memberships/'.$team['body']['$id'], array_merge([ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], diff --git a/tests/e2e/Services/Webhooks/WebhooksCustomClientTest.php b/tests/e2e/Services/Webhooks/WebhooksCustomClientTest.php index aaf7901e19..8b0a00e724 100644 --- a/tests/e2e/Services/Webhooks/WebhooksCustomClientTest.php +++ b/tests/e2e/Services/Webhooks/WebhooksCustomClientTest.php @@ -4,8 +4,8 @@ namespace Tests\E2E\Services\Webhooks; use Appwrite\Tests\Retry; use Tests\E2E\Client; -use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\ProjectCustom; +use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\SideClient; use Utopia\Database\Helpers\ID; use Utopia\Database\Validator\DatetimeValidator; @@ -18,7 +18,7 @@ class WebhooksCustomClientTest extends Scope public function testCreateAccount(): array { - $email = uniqid() . 'user@localhost.test'; + $email = uniqid().'user@localhost.test'; $password = 'password'; $name = 'User Name'; @@ -44,8 +44,8 @@ class WebhooksCustomClientTest extends Scope $webhook = $this->getLastRequest(); $signatureKey = $this->getProject()['signatureKey']; $payload = json_encode($webhook['data']); - $url = $webhook['url']; - $signatureExpected = base64_encode(hash_hmac('sha1', $url . $payload, $signatureKey, true)); + $url = $webhook['url']; + $signatureExpected = base64_encode(hash_hmac('sha1', $url.$payload, $signatureKey, true)); $this->assertEquals($webhook['method'], 'POST'); $this->assertEquals($webhook['headers']['Content-Type'], 'application/json'); @@ -77,7 +77,7 @@ class WebhooksCustomClientTest extends Scope public function testDeleteAccount(): array { - $email = uniqid() . 'user1@localhost.test'; + $email = uniqid().'user1@localhost.test'; $password = 'password'; $name = 'User Name 1'; @@ -107,13 +107,13 @@ class WebhooksCustomClientTest extends Scope $this->assertEquals($accountSession['headers']['status-code'], 201); $id = $account['body']['$id']; - $session = $this->client->parseCookie((string)$accountSession['headers']['set-cookie'])['a_session_' . $this->getProject()['$id']]; + $session = $this->client->parseCookie((string) $accountSession['headers']['set-cookie'])['a_session_'.$this->getProject()['$id']]; $account = $this->client->call(Client::METHOD_PATCH, '/account/status', array_merge([ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ])); $this->assertEquals($account['headers']['status-code'], 200); @@ -121,8 +121,8 @@ class WebhooksCustomClientTest extends Scope $webhook = $this->getLastRequest(); $signatureKey = $this->getProject()['signatureKey']; $payload = json_encode($webhook['data']); - $url = $webhook['url']; - $signatureExpected = base64_encode(hash_hmac('sha1', $url . $payload, $signatureKey, true)); + $url = $webhook['url']; + $signatureExpected = base64_encode(hash_hmac('sha1', $url.$payload, $signatureKey, true)); $this->assertEquals($webhook['method'], 'POST'); $this->assertEquals($webhook['headers']['Content-Type'], 'application/json'); @@ -171,13 +171,13 @@ class WebhooksCustomClientTest extends Scope $this->assertEquals($accountSession['headers']['status-code'], 201); $sessionId = $accountSession['body']['$id']; - $session = $this->client->parseCookie((string)$accountSession['headers']['set-cookie'])['a_session_' . $this->getProject()['$id']]; + $session = $this->client->parseCookie((string) $accountSession['headers']['set-cookie'])['a_session_'.$this->getProject()['$id']]; $webhook = $this->getLastRequest(); $signatureKey = $this->getProject()['signatureKey']; $payload = json_encode($webhook['data']); - $url = $webhook['url']; - $signatureExpected = base64_encode(hash_hmac('sha1', $url . $payload, $signatureKey, true)); + $url = $webhook['url']; + $signatureExpected = base64_encode(hash_hmac('sha1', $url.$payload, $signatureKey, true)); $this->assertEquals($webhook['method'], 'POST'); $this->assertEquals($webhook['headers']['Content-Type'], 'application/json'); @@ -250,15 +250,15 @@ class WebhooksCustomClientTest extends Scope ]); $sessionId = $accountSession['body']['$id']; - $session = $this->client->parseCookie((string)$accountSession['headers']['set-cookie'])['a_session_' . $this->getProject()['$id']]; + $session = $this->client->parseCookie((string) $accountSession['headers']['set-cookie'])['a_session_'.$this->getProject()['$id']]; $this->assertEquals($accountSession['headers']['status-code'], 201); - $accountSession = $this->client->call(Client::METHOD_DELETE, '/account/sessions/' . $sessionId, array_merge([ + $accountSession = $this->client->call(Client::METHOD_DELETE, '/account/sessions/'.$sessionId, array_merge([ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ])); $this->assertEquals($accountSession['headers']['status-code'], 204); @@ -266,8 +266,8 @@ class WebhooksCustomClientTest extends Scope $webhook = $this->getLastRequest(); $signatureKey = $this->getProject()['signatureKey']; $payload = json_encode($webhook['data']); - $url = $webhook['url']; - $signatureExpected = base64_encode(hash_hmac('sha1', $url . $payload, $signatureKey, true)); + $url = $webhook['url']; + $signatureExpected = base64_encode(hash_hmac('sha1', $url.$payload, $signatureKey, true)); $this->assertEquals($webhook['method'], 'POST'); $this->assertEquals($webhook['headers']['Content-Type'], 'application/json'); @@ -336,7 +336,7 @@ class WebhooksCustomClientTest extends Scope ]); $sessionId = $accountSession['body']['$id']; - $session = $this->client->parseCookie((string)$accountSession['headers']['set-cookie'])['a_session_' . $this->getProject()['$id']]; + $session = $this->client->parseCookie((string) $accountSession['headers']['set-cookie'])['a_session_'.$this->getProject()['$id']]; $this->assertEquals($accountSession['headers']['status-code'], 201); @@ -344,7 +344,7 @@ class WebhooksCustomClientTest extends Scope 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ])); $this->assertEquals($accountSession['headers']['status-code'], 204); @@ -352,8 +352,8 @@ class WebhooksCustomClientTest extends Scope $webhook = $this->getLastRequest(); $signatureKey = $this->getProject()['signatureKey']; $payload = json_encode($webhook['data']); - $url = $webhook['url']; - $signatureExpected = base64_encode(hash_hmac('sha1', $url . $payload, $signatureKey, true)); + $url = $webhook['url']; + $signatureExpected = base64_encode(hash_hmac('sha1', $url.$payload, $signatureKey, true)); $this->assertEquals($webhook['method'], 'POST'); $this->assertEquals($webhook['headers']['Content-Type'], 'application/json'); @@ -410,7 +410,7 @@ class WebhooksCustomClientTest extends Scope $this->assertEquals($accountSession['headers']['status-code'], 201); $sessionId = $accountSession['body']['$id']; - $session = $this->client->parseCookie((string)$accountSession['headers']['set-cookie'])['a_session_' . $this->getProject()['$id']]; + $session = $this->client->parseCookie((string) $accountSession['headers']['set-cookie'])['a_session_'.$this->getProject()['$id']]; return array_merge($data, [ 'sessionId' => $sessionId, @@ -433,9 +433,9 @@ class WebhooksCustomClientTest extends Scope 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), [ - 'name' => $newName + 'name' => $newName, ]); $this->assertEquals($account['headers']['status-code'], 200); @@ -444,9 +444,8 @@ class WebhooksCustomClientTest extends Scope $webhook = $this->getLastRequest(); $signatureKey = $this->getProject()['signatureKey']; $payload = json_encode($webhook['data']); - $url = $webhook['url']; - $signatureExpected = base64_encode(hash_hmac('sha1', $url . $payload, $signatureKey, true)); - + $url = $webhook['url']; + $signatureExpected = base64_encode(hash_hmac('sha1', $url.$payload, $signatureKey, true)); $this->assertEquals($webhook['method'], 'POST'); $this->assertEquals($webhook['headers']['Content-Type'], 'application/json'); @@ -486,7 +485,7 @@ class WebhooksCustomClientTest extends Scope 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), [ 'password' => 'new-password', 'oldPassword' => $password, @@ -498,8 +497,8 @@ class WebhooksCustomClientTest extends Scope $webhook = $this->getLastRequest(); $signatureKey = $this->getProject()['signatureKey']; $payload = json_encode($webhook['data']); - $url = $webhook['url']; - $signatureExpected = base64_encode(hash_hmac('sha1', $url . $payload, $signatureKey, true)); + $url = $webhook['url']; + $signatureExpected = base64_encode(hash_hmac('sha1', $url.$payload, $signatureKey, true)); $this->assertEquals($webhook['method'], 'POST'); $this->assertEquals($webhook['headers']['Content-Type'], 'application/json'); @@ -534,14 +533,14 @@ class WebhooksCustomClientTest extends Scope { $id = $data['id'] ?? ''; $email = $data['email'] ?? ''; - $newEmail = uniqid() . 'new@localhost.test'; + $newEmail = uniqid().'new@localhost.test'; $session = $data['session'] ?? ''; $account = $this->client->call(Client::METHOD_PATCH, '/account/email', array_merge([ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), [ 'email' => $newEmail, 'password' => 'new-password', @@ -553,8 +552,8 @@ class WebhooksCustomClientTest extends Scope $webhook = $this->getLastRequest(); $signatureKey = $this->getProject()['signatureKey']; $payload = json_encode($webhook['data']); - $url = $webhook['url']; - $signatureExpected = base64_encode(hash_hmac('sha1', $url . $payload, $signatureKey, true)); + $url = $webhook['url']; + $signatureExpected = base64_encode(hash_hmac('sha1', $url.$payload, $signatureKey, true)); $this->assertEquals($webhook['method'], 'POST'); $this->assertEquals($webhook['headers']['Content-Type'], 'application/json'); @@ -595,12 +594,12 @@ class WebhooksCustomClientTest extends Scope 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), [ 'prefs' => [ 'prefKey1' => 'prefValue1', 'prefKey2' => 'prefValue2', - ] + ], ]); $this->assertEquals($account['headers']['status-code'], 200); @@ -609,8 +608,8 @@ class WebhooksCustomClientTest extends Scope $webhook = $this->getLastRequest(); $signatureKey = $this->getProject()['signatureKey']; $payload = json_encode($webhook['data']); - $url = $webhook['url']; - $signatureExpected = base64_encode(hash_hmac('sha1', $url . $payload, $signatureKey, true)); + $url = $webhook['url']; + $signatureExpected = base64_encode(hash_hmac('sha1', $url.$payload, $signatureKey, true)); $this->assertEquals($webhook['method'], 'POST'); $this->assertEquals($webhook['headers']['Content-Type'], 'application/json'); @@ -664,8 +663,8 @@ class WebhooksCustomClientTest extends Scope $webhook = $this->getLastRequest(); $signatureKey = $this->getProject()['signatureKey']; $payload = json_encode($webhook['data']); - $url = $webhook['url']; - $signatureExpected = base64_encode(hash_hmac('sha1', $url . $payload, $signatureKey, true)); + $url = $webhook['url']; + $signatureExpected = base64_encode(hash_hmac('sha1', $url.$payload, $signatureKey, true)); $this->assertEquals($webhook['method'], 'POST'); $this->assertEquals($webhook['headers']['Content-Type'], 'application/json'); @@ -725,8 +724,8 @@ class WebhooksCustomClientTest extends Scope $webhook = $this->getLastRequest(); $signatureKey = $this->getProject()['signatureKey']; $payload = json_encode($webhook['data']); - $url = $webhook['url']; - $signatureExpected = base64_encode(hash_hmac('sha1', $url . $payload, $signatureKey, true)); + $url = $webhook['url']; + $signatureExpected = base64_encode(hash_hmac('sha1', $url.$payload, $signatureKey, true)); $this->assertEquals($webhook['method'], 'POST'); $this->assertEquals($webhook['headers']['Content-Type'], 'application/json'); @@ -769,7 +768,7 @@ class WebhooksCustomClientTest extends Scope 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), [ 'url' => 'http://localhost/verification', ]); @@ -782,8 +781,8 @@ class WebhooksCustomClientTest extends Scope $webhook = $this->getLastRequest(); $signatureKey = $this->getProject()['signatureKey']; $payload = json_encode($webhook['data']); - $url = $webhook['url']; - $signatureExpected = base64_encode(hash_hmac('sha1', $url . $payload, $signatureKey, true)); + $url = $webhook['url']; + $signatureExpected = base64_encode(hash_hmac('sha1', $url.$payload, $signatureKey, true)); $this->assertEquals($webhook['method'], 'POST'); $this->assertEquals($webhook['headers']['Content-Type'], 'application/json'); @@ -827,7 +826,7 @@ class WebhooksCustomClientTest extends Scope 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session, + 'cookie' => 'a_session_'.$this->getProject()['$id'].'='.$session, ]), [ 'userId' => $id, 'secret' => $secret, @@ -841,8 +840,8 @@ class WebhooksCustomClientTest extends Scope $webhook = $this->getLastRequest(); $signatureKey = $this->getProject()['signatureKey']; $payload = json_encode($webhook['data']); - $url = $webhook['url']; - $signatureExpected = base64_encode(hash_hmac('sha1', $url . $payload, $signatureKey, true)); + $url = $webhook['url']; + $signatureExpected = base64_encode(hash_hmac('sha1', $url.$payload, $signatureKey, true)); $this->assertEquals($webhook['method'], 'POST'); $this->assertEquals($webhook['headers']['Content-Type'], 'application/json'); @@ -885,7 +884,7 @@ class WebhooksCustomClientTest extends Scope /** * Test for SUCCESS */ - $team = $this->client->call(Client::METHOD_PATCH, '/teams/' . $teamUid . '/memberships/' . $membershipUid . '/status', array_merge([ + $team = $this->client->call(Client::METHOD_PATCH, '/teams/'.$teamUid.'/memberships/'.$membershipUid.'/status', array_merge([ 'origin' => 'http://localhost', 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], @@ -900,8 +899,8 @@ class WebhooksCustomClientTest extends Scope $webhook = $this->getLastRequest(); $signatureKey = $this->getProject()['signatureKey']; $payload = json_encode($webhook['data']); - $url = $webhook['url']; - $signatureExpected = base64_encode(hash_hmac('sha1', $url . $payload, $signatureKey, true)); + $url = $webhook['url']; + $signatureExpected = base64_encode(hash_hmac('sha1', $url.$payload, $signatureKey, true)); $this->assertEquals($webhook['method'], 'POST'); $this->assertEquals($webhook['headers']['Content-Type'], 'application/json'); diff --git a/tests/e2e/Services/Webhooks/WebhooksCustomServerTest.php b/tests/e2e/Services/Webhooks/WebhooksCustomServerTest.php index 0ccb138d44..d841b3a7e0 100644 --- a/tests/e2e/Services/Webhooks/WebhooksCustomServerTest.php +++ b/tests/e2e/Services/Webhooks/WebhooksCustomServerTest.php @@ -30,10 +30,10 @@ class WebhooksCustomServerTest extends Scope /** * Test for SUCCESS */ - $actors = $this->client->call(Client::METHOD_PUT, '/databases/' . $databaseId . '/collections/' . $id, array_merge([ + $actors = $this->client->call(Client::METHOD_PUT, '/databases/'.$databaseId.'/collections/'.$id, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'name' => 'Actors1', 'documentSecurity' => true, @@ -48,8 +48,8 @@ class WebhooksCustomServerTest extends Scope $this->assertEquals($webhook['method'], 'POST'); $this->assertEquals($webhook['headers']['Content-Type'], 'application/json'); $this->assertEquals($webhook['headers']['User-Agent'], 'Appwrite-Server vdev. Please report abuse at security@appwrite.io'); - $this->assertStringContainsString('databases.' . $databaseId . '.collections.*', $webhook['headers']['X-Appwrite-Webhook-Events']); - $this->assertStringContainsString('databases.' . $databaseId . '.collections.*.update', $webhook['headers']['X-Appwrite-Webhook-Events']); + $this->assertStringContainsString('databases.'.$databaseId.'.collections.*', $webhook['headers']['X-Appwrite-Webhook-Events']); + $this->assertStringContainsString('databases.'.$databaseId.'.collections.*.update', $webhook['headers']['X-Appwrite-Webhook-Events']); $this->assertStringContainsString("databases.{$databaseId}.collections.{$id}", $webhook['headers']['X-Appwrite-Webhook-Events']); $this->assertStringContainsString("databases.{$databaseId}.collections.{$id}.update", $webhook['headers']['X-Appwrite-Webhook-Events']); $this->assertEquals($webhook['headers']['X-Appwrite-Webhook-Signature'], $signatureExpected); @@ -72,10 +72,10 @@ class WebhooksCustomServerTest extends Scope $actorsId = $data['actorsId']; $databaseId = $data['databaseId']; - $index = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections/' . $data['actorsId'] . '/indexes', array_merge([ + $index = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections/'.$data['actorsId'].'/indexes', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'key' => 'fullname', 'type' => 'key', @@ -96,9 +96,9 @@ class WebhooksCustomServerTest extends Scope $this->assertEquals($webhook['method'], 'POST'); $this->assertEquals($webhook['headers']['Content-Type'], 'application/json'); $this->assertEquals($webhook['headers']['User-Agent'], 'Appwrite-Server vdev. Please report abuse at security@appwrite.io'); - $this->assertStringContainsString('databases.' . $databaseId . '.collections.*', $webhook['headers']['X-Appwrite-Webhook-Events']); - $this->assertStringContainsString('databases.' . $databaseId . '.collections.*.indexes.*', $webhook['headers']['X-Appwrite-Webhook-Events']); - $this->assertStringContainsString('databases.' . $databaseId . '.collections.*.indexes.*.create', $webhook['headers']['X-Appwrite-Webhook-Events']); + $this->assertStringContainsString('databases.'.$databaseId.'.collections.*', $webhook['headers']['X-Appwrite-Webhook-Events']); + $this->assertStringContainsString('databases.'.$databaseId.'.collections.*.indexes.*', $webhook['headers']['X-Appwrite-Webhook-Events']); + $this->assertStringContainsString('databases.'.$databaseId.'.collections.*.indexes.*.create', $webhook['headers']['X-Appwrite-Webhook-Events']); $this->assertStringContainsString("databases.{$databaseId}.collections.{$actorsId}", $webhook['headers']['X-Appwrite-Webhook-Events']); $this->assertStringContainsString("databases.{$databaseId}.collections.{$actorsId}.indexes.*", $webhook['headers']['X-Appwrite-Webhook-Events']); $this->assertStringContainsString("databases.{$databaseId}.collections.{$actorsId}.indexes.*.create", $webhook['headers']['X-Appwrite-Webhook-Events']); @@ -108,10 +108,10 @@ class WebhooksCustomServerTest extends Scope $this->assertEquals(empty($webhook['headers']['X-Appwrite-Webhook-User-Id'] ?? ''), true); // Remove index - $this->client->call(Client::METHOD_DELETE, '/databases/' . $databaseId . '/collections/' . $data['actorsId'] . '/indexes/' . $index['body']['key'], array_merge([ + $this->client->call(Client::METHOD_DELETE, '/databases/'.$databaseId.'/collections/'.$data['actorsId'].'/indexes/'.$index['body']['key'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ])); // // wait for database worker to remove index @@ -121,9 +121,9 @@ class WebhooksCustomServerTest extends Scope // $this->assertEquals($webhook['method'], 'DELETE'); $this->assertEquals($webhook['headers']['Content-Type'], 'application/json'); $this->assertEquals($webhook['headers']['User-Agent'], 'Appwrite-Server vdev. Please report abuse at security@appwrite.io'); - $this->assertStringContainsString('databases.' . $databaseId . '.collections.*', $webhook['headers']['X-Appwrite-Webhook-Events']); - $this->assertStringContainsString('databases.' . $databaseId . '.collections.*.indexes.*', $webhook['headers']['X-Appwrite-Webhook-Events']); - $this->assertStringContainsString('databases.' . $databaseId . '.collections.*.indexes.*.delete', $webhook['headers']['X-Appwrite-Webhook-Events']); + $this->assertStringContainsString('databases.'.$databaseId.'.collections.*', $webhook['headers']['X-Appwrite-Webhook-Events']); + $this->assertStringContainsString('databases.'.$databaseId.'.collections.*.indexes.*', $webhook['headers']['X-Appwrite-Webhook-Events']); + $this->assertStringContainsString('databases.'.$databaseId.'.collections.*.indexes.*.delete', $webhook['headers']['X-Appwrite-Webhook-Events']); $this->assertStringContainsString("databases.{$databaseId}.collections.{$actorsId}", $webhook['headers']['X-Appwrite-Webhook-Events']); $this->assertStringContainsString("databases.{$databaseId}.collections.{$actorsId}.indexes.*", $webhook['headers']['X-Appwrite-Webhook-Events']); $this->assertStringContainsString("databases.{$databaseId}.collections.{$actorsId}.indexes.*.delete", $webhook['headers']['X-Appwrite-Webhook-Events']); @@ -143,7 +143,7 @@ class WebhooksCustomServerTest extends Scope $database = $this->client->call(Client::METHOD_POST, '/databases', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ], $this->getHeaders()), [ 'databaseId' => ID::unique(), 'name' => 'Actors DB', @@ -154,10 +154,10 @@ class WebhooksCustomServerTest extends Scope /** * Test for SUCCESS */ - $actors = $this->client->call(Client::METHOD_POST, '/databases/' . $databaseId . '/collections', array_merge([ + $actors = $this->client->call(Client::METHOD_POST, '/databases/'.$databaseId.'/collections', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), [ 'collectionId' => ID::unique(), 'name' => 'Demo', @@ -175,10 +175,10 @@ class WebhooksCustomServerTest extends Scope $this->assertEquals($actors['headers']['status-code'], 201); $this->assertNotEmpty($actors['body']['$id']); - $actors = $this->client->call(Client::METHOD_DELETE, '/databases/' . $databaseId . '/collections/' . $actors['body']['$id'], array_merge([ + $actors = $this->client->call(Client::METHOD_DELETE, '/databases/'.$databaseId.'/collections/'.$actors['body']['$id'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], - 'x-appwrite-key' => $this->getProject()['apiKey'] + 'x-appwrite-key' => $this->getProject()['apiKey'], ]), []); $this->assertEquals($actors['headers']['status-code'], 204); @@ -189,8 +189,8 @@ class WebhooksCustomServerTest extends Scope $this->assertEquals($webhook['method'], 'POST'); $this->assertEquals($webhook['headers']['Content-Type'], 'application/json'); $this->assertEquals($webhook['headers']['User-Agent'], 'Appwrite-Server vdev. Please report abuse at security@appwrite.io'); - $this->assertStringContainsString('databases.' . $databaseId . '.collections.*', $webhook['headers']['X-Appwrite-Webhook-Events']); - $this->assertStringContainsString('databases.' . $databaseId . '.collections.*.delete', $webhook['headers']['X-Appwrite-Webhook-Events']); + $this->assertStringContainsString('databases.'.$databaseId.'.collections.*', $webhook['headers']['X-Appwrite-Webhook-Events']); + $this->assertStringContainsString('databases.'.$databaseId.'.collections.*.delete', $webhook['headers']['X-Appwrite-Webhook-Events']); $this->assertStringContainsString("databases.{$databaseId}.collections.{$id}", $webhook['headers']['X-Appwrite-Webhook-Events']); $this->assertStringContainsString("databases.{$databaseId}.collections.{$id}.delete", $webhook['headers']['X-Appwrite-Webhook-Events']); $this->assertEquals($webhook['headers']['X-Appwrite-Webhook-Signature'], $signatureExpected); @@ -207,7 +207,7 @@ class WebhooksCustomServerTest extends Scope public function testCreateUser(): array { - $email = uniqid() . 'user@localhost.test'; + $email = uniqid().'user@localhost.test'; $password = 'password'; $name = 'User Name'; @@ -268,11 +268,11 @@ class WebhooksCustomServerTest extends Scope /** * Test for SUCCESS */ - $user = $this->client->call(Client::METHOD_PATCH, '/users/' . $id . '/prefs', array_merge([ + $user = $this->client->call(Client::METHOD_PATCH, '/users/'.$id.'/prefs', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'prefs' => ['a' => 'b'] + 'prefs' => ['a' => 'b'], ]); $this->assertEquals($user['headers']['status-code'], 200); @@ -309,7 +309,7 @@ class WebhooksCustomServerTest extends Scope /** * Test for SUCCESS */ - $user = $this->client->call(Client::METHOD_PATCH, '/users/' . $data['userId'] . '/status', array_merge([ + $user = $this->client->call(Client::METHOD_PATCH, '/users/'.$data['userId'].'/status', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -357,7 +357,7 @@ class WebhooksCustomServerTest extends Scope /** * Test for SUCCESS */ - $user = $this->client->call(Client::METHOD_DELETE, '/users/' . $data['userId'], array_merge([ + $user = $this->client->call(Client::METHOD_DELETE, '/users/'.$data['userId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -444,7 +444,7 @@ class WebhooksCustomServerTest extends Scope /** * Test for SUCCESS */ - $function = $this->client->call(Client::METHOD_PUT, '/functions/' . $data['functionId'], array_merge([ + $function = $this->client->call(Client::METHOD_PUT, '/functions/'.$data['functionId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -453,14 +453,14 @@ class WebhooksCustomServerTest extends Scope 'execute' => [Role::any()->toString()], 'vars' => [ 'key1' => 'value1', - ] + ], ]); $this->assertEquals($function['headers']['status-code'], 200); $this->assertEquals($function['body']['$id'], $data['functionId']); // Create variable - $variable = $this->client->call(Client::METHOD_POST, '/functions/' . $data['functionId'] . '/variables', array_merge([ + $variable = $this->client->call(Client::METHOD_POST, '/functions/'.$data['functionId'].'/variables', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ @@ -484,12 +484,12 @@ class WebhooksCustomServerTest extends Scope $this->assertEquals($webhook['headers']['X-Appwrite-Webhook-Id'] ?? '', $this->getProject()['webhookId']); $this->assertEquals($webhook['headers']['X-Appwrite-Webhook-Project-Id'] ?? '', $this->getProject()['$id']); - $function = $this->client->call(Client::METHOD_PUT, '/functions/' . $data['functionId'], array_merge([ + $function = $this->client->call(Client::METHOD_PUT, '/functions/'.$data['functionId'], array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'name' => 'Test Failure', - 'execute' => [ 'not-valid-permission' ] + 'execute' => ['not-valid-permission'], ]); $this->assertEquals($function['headers']['status-code'], 400); @@ -508,15 +508,15 @@ class WebhooksCustomServerTest extends Scope $stderr = ''; $stdout = ''; $folder = 'timeout'; - $code = realpath(__DIR__ . '/../../../resources/functions') . "/{$folder}/code.tar.gz"; - Console::execute('cd ' . realpath(__DIR__ . "/../../../resources/functions") . "/{$folder} && tar --exclude code.tar.gz -czf code.tar.gz .", '', $stdout, $stderr); + $code = realpath(__DIR__.'/../../../resources/functions')."/{$folder}/code.tar.gz"; + Console::execute('cd '.realpath(__DIR__.'/../../../resources/functions')."/{$folder} && tar --exclude code.tar.gz -czf code.tar.gz .", '', $stdout, $stderr); - $deployment = $this->client->call(Client::METHOD_POST, '/functions/' . $data['functionId'] . '/deployments', array_merge([ + $deployment = $this->client->call(Client::METHOD_POST, '/functions/'.$data['functionId'].'/deployments', array_merge([ 'content-type' => 'multipart/form-data', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ 'entrypoint' => 'index.php', - 'code' => new CURLFile($code, 'application/x-gzip', \basename($code)) + 'code' => new CURLFile($code, 'application/x-gzip', \basename($code)), ]); $id = $data['functionId'] ?? ''; @@ -557,7 +557,7 @@ class WebhooksCustomServerTest extends Scope /** * Test for SUCCESS */ - $response = $this->client->call(Client::METHOD_PATCH, '/functions/' . $id . '/deployments/' . $deploymentId, array_merge([ + $response = $this->client->call(Client::METHOD_PATCH, '/functions/'.$id.'/deployments/'.$deploymentId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), []); @@ -605,11 +605,11 @@ class WebhooksCustomServerTest extends Scope /** * Test for SUCCESS */ - $execution = $this->client->call(Client::METHOD_POST, '/functions/' . $id . '/executions', array_merge([ + $execution = $this->client->call(Client::METHOD_POST, '/functions/'.$id.'/executions', array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders()), [ - 'async' => true + 'async' => true, ]); $executionId = $execution['body']['$id'] ?? ''; @@ -676,7 +676,7 @@ class WebhooksCustomServerTest extends Scope /** * Test for SUCCESS */ - $deployment = $this->client->call(Client::METHOD_DELETE, '/functions/' . $id . '/deployments/' . $deploymentId, array_merge([ + $deployment = $this->client->call(Client::METHOD_DELETE, '/functions/'.$id.'/deployments/'.$deploymentId, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); @@ -721,7 +721,7 @@ class WebhooksCustomServerTest extends Scope /** * Test for SUCCESS */ - $function = $this->client->call(Client::METHOD_DELETE, '/functions/' . $id, array_merge([ + $function = $this->client->call(Client::METHOD_DELETE, '/functions/'.$id, array_merge([ 'content-type' => 'application/json', 'x-appwrite-project' => $this->getProject()['$id'], ], $this->getHeaders())); diff --git a/tests/extensions/Retryable.php b/tests/extensions/Retryable.php index 61fec0ef12..aa85d22eae 100644 --- a/tests/extensions/Retryable.php +++ b/tests/extensions/Retryable.php @@ -14,6 +14,7 @@ trait Retryable * accounting for any retries configured by the {@see Retry} annotation. * * @return void + * * @throws \ReflectionException * @throws \Throwable */ @@ -21,14 +22,15 @@ trait Retryable { $retries = $this->getNumberOfRetries(); $ex = null; - for ($i = 0; $i <= $retries; ++$i) { + for ($i = 0; $i <= $retries; $i++) { try { parent::runBare(); + return; - } catch (\Throwable | \Exception $ex) { + } catch (\Throwable|\Exception $ex) { // Swallow the exception until we have exhausted our retries. if ($i !== $retries) { - echo 'Flaky test failed, retrying...' . PHP_EOL; + echo 'Flaky test failed, retrying...'.PHP_EOL; } } } @@ -39,6 +41,7 @@ trait Retryable /** * @return int + * * @throws \ReflectionException */ private function getNumberOfRetries(): int @@ -53,11 +56,12 @@ trait Retryable $attribute = $attributes[0] ?? null; $args = $attribute?->getArguments(); $retries = $args['count'] ?? 0; + return \max(0, $retries); } /** - * @param \ReflectionClass $reflection + * @param \ReflectionClass $reflection * @return \ReflectionClass */ private function getTestCaseRoot(\ReflectionClass $reflection): \ReflectionClass @@ -65,6 +69,7 @@ trait Retryable if ($reflection->getName() === TestCase::class) { return $reflection; } + return $this->getTestCaseRoot($reflection->getParentClass()); } } diff --git a/tests/extensions/TestHook.php b/tests/extensions/TestHook.php index 67c1215c4c..f6db16a227 100644 --- a/tests/extensions/TestHook.php +++ b/tests/extensions/TestHook.php @@ -3,11 +3,11 @@ namespace Appwrite\Tests; use PHPUnit\Runner\AfterTestHook; -use Exception; class TestHook implements AfterTestHook { protected const MAX_SECONDS_ALLOWED = 15; + public function executeAfterTest(string $test, float $time): void { printf( diff --git a/tests/resources/functions/php-fn/index.php b/tests/resources/functions/php-fn/index.php index 7947c4a6a6..6da31cd499 100644 --- a/tests/resources/functions/php-fn/index.php +++ b/tests/resources/functions/php-fn/index.php @@ -1,7 +1,7 @@ json([ 'APPWRITE_FUNCTION_ID' => $request['variables']['APPWRITE_FUNCTION_ID'], diff --git a/tests/resources/functions/php-large/index.php b/tests/resources/functions/php-large/index.php index 84b6a991fe..83140c27ff 100644 --- a/tests/resources/functions/php-large/index.php +++ b/tests/resources/functions/php-large/index.php @@ -10,6 +10,6 @@ return function ($request, $response) { 'APPWRITE_FUNCTION_RUNTIME_VERSION' => $request['variables']['APPWRITE_FUNCTION_RUNTIME_VERSION'], 'APPWRITE_FUNCTION_EVENT' => $request['variables']['APPWRITE_FUNCTION_EVENT'], 'APPWRITE_FUNCTION_EVENT_DATA' => $request['variables']['APPWRITE_FUNCTION_EVENT_DATA'], - 'UNICODE_TEST' => "êä" + 'UNICODE_TEST' => 'êä', ]); }; diff --git a/tests/resources/functions/php/index.php b/tests/resources/functions/php/index.php index 84b6a991fe..83140c27ff 100644 --- a/tests/resources/functions/php/index.php +++ b/tests/resources/functions/php/index.php @@ -10,6 +10,6 @@ return function ($request, $response) { 'APPWRITE_FUNCTION_RUNTIME_VERSION' => $request['variables']['APPWRITE_FUNCTION_RUNTIME_VERSION'], 'APPWRITE_FUNCTION_EVENT' => $request['variables']['APPWRITE_FUNCTION_EVENT'], 'APPWRITE_FUNCTION_EVENT_DATA' => $request['variables']['APPWRITE_FUNCTION_EVENT_DATA'], - 'UNICODE_TEST' => "êä" + 'UNICODE_TEST' => 'êä', ]); }; diff --git a/tests/unit/Auth/AuthTest.php b/tests/unit/Auth/AuthTest.php index e64ef37dfe..cec9f84161 100644 --- a/tests/unit/Auth/AuthTest.php +++ b/tests/unit/Auth/AuthTest.php @@ -3,13 +3,13 @@ namespace Tests\Unit\Auth; use Appwrite\Auth\Auth; +use PHPUnit\Framework\TestCase; +use Utopia\Database\Database; use Utopia\Database\DateTime; use Utopia\Database\Document; use Utopia\Database\Helpers\ID; use Utopia\Database\Helpers\Role; use Utopia\Database\Validator\Authorization; -use PHPUnit\Framework\TestCase; -use Utopia\Database\Database; use Utopia\Database\Validator\Roles; class AuthTest extends TestCase @@ -128,13 +128,13 @@ class AuthTest extends TestCase // Scrypt $plain = 'some-scrypt-password'; $hash = 'b448ad7ba88b653b5b56b8053a06806724932d0751988bc9cd0ef7ff059e8ba8a020e1913b7069a650d3f99a1559aba0221f2c277826919513a054e76e339028'; - $generatedHash = Auth::passwordHash($plain, 'scrypt', [ 'salt' => 'some-salt', 'length' => 64, 'costCpu' => 16384, 'costMemory' => 12, 'costParallel' => 2]); + $generatedHash = Auth::passwordHash($plain, 'scrypt', ['salt' => 'some-salt', 'length' => 64, 'costCpu' => 16384, 'costMemory' => 12, 'costParallel' => 2]); - $this->assertEquals(true, Auth::passwordVerify($plain, $generatedHash, 'scrypt', [ 'salt' => 'some-salt', 'length' => 64, 'costCpu' => 16384, 'costMemory' => 12, 'costParallel' => 2])); - $this->assertEquals(true, Auth::passwordVerify($plain, $hash, 'scrypt', [ 'salt' => 'some-salt', 'length' => 64, 'costCpu' => 16384, 'costMemory' => 12, 'costParallel' => 2])); - $this->assertEquals(false, Auth::passwordVerify($plain, $hash, 'scrypt', [ 'salt' => 'some-wrong-salt', 'length' => 64, 'costCpu' => 16384, 'costMemory' => 12, 'costParallel' => 2])); - $this->assertEquals(false, Auth::passwordVerify($plain, $hash, 'scrypt', [ 'salt' => 'some-salt', 'length' => 64, 'costCpu' => 16384, 'costMemory' => 10, 'costParallel' => 2])); - $this->assertEquals(false, Auth::passwordVerify('wrongPassword', $hash, 'scrypt', [ 'salt' => 'some-salt', 'length' => 64, 'costCpu' => 16384, 'costMemory' => 12, 'costParallel' => 2])); + $this->assertEquals(true, Auth::passwordVerify($plain, $generatedHash, 'scrypt', ['salt' => 'some-salt', 'length' => 64, 'costCpu' => 16384, 'costMemory' => 12, 'costParallel' => 2])); + $this->assertEquals(true, Auth::passwordVerify($plain, $hash, 'scrypt', ['salt' => 'some-salt', 'length' => 64, 'costCpu' => 16384, 'costMemory' => 12, 'costParallel' => 2])); + $this->assertEquals(false, Auth::passwordVerify($plain, $hash, 'scrypt', ['salt' => 'some-wrong-salt', 'length' => 64, 'costCpu' => 16384, 'costMemory' => 12, 'costParallel' => 2])); + $this->assertEquals(false, Auth::passwordVerify($plain, $hash, 'scrypt', ['salt' => 'some-salt', 'length' => 64, 'costCpu' => 16384, 'costMemory' => 10, 'costParallel' => 2])); + $this->assertEquals(false, Auth::passwordVerify('wrongPassword', $hash, 'scrypt', ['salt' => 'some-salt', 'length' => 64, 'costCpu' => 16384, 'costMemory' => 12, 'costParallel' => 2])); // ScryptModified tested are in provider-specific tests below @@ -165,7 +165,7 @@ class AuthTest extends TestCase $saltSeparator = 'Bw=='; $signerKey = 'XyEKE9RcTDeLEsL/RjwPDBv/RqDl8fb3gpYEOQaPihbxf1ZAtSOHCjuAAa7Q3oHpCYhXSN9tizHgVOwn6krflQ=='; - $options = [ 'salt' => $salt, 'saltSeparator' => $saltSeparator, 'signerKey' => $signerKey ]; + $options = ['salt' => $salt, 'saltSeparator' => $saltSeparator, 'signerKey' => $signerKey]; $generatedHash = Auth::passwordHash($plain, 'scryptMod', $options); $this->assertEquals(true, Auth::passwordVerify($plain, $generatedHash, 'scryptMod', $options)); $this->assertEquals(true, Auth::passwordVerify($plain, $hash, 'scryptMod', $options)); @@ -340,7 +340,7 @@ class AuthTest extends TestCase public function testGuestRoles(): void { $user = new Document([ - '$id' => '' + '$id' => '', ]); $roles = Auth::getRoles($user); @@ -350,7 +350,7 @@ class AuthTest extends TestCase public function testUserRoles(): void { - $user = new Document([ + $user = new Document([ '$id' => ID::custom('123'), 'emailVerification' => true, 'phoneVerification' => true, @@ -361,18 +361,18 @@ class AuthTest extends TestCase 'confirm' => true, 'roles' => [ 'administrator', - 'moderator' - ] + 'moderator', + ], ], [ '$id' => ID::custom('abc'), 'teamId' => ID::custom('def'), 'confirm' => true, 'roles' => [ - 'guest' - ] - ] - ] + 'guest', + ], + ], + ], ]); $roles = Auth::getRoles($user); @@ -409,7 +409,7 @@ class AuthTest extends TestCase public function testPrivilegedUserRoles(): void { Authorization::setRole(Auth::USER_ROLE_OWNER); - $user = new Document([ + $user = new Document([ '$id' => ID::custom('123'), 'emailVerification' => true, 'phoneVerification' => true, @@ -420,18 +420,18 @@ class AuthTest extends TestCase 'confirm' => true, 'roles' => [ 'administrator', - 'moderator' - ] + 'moderator', + ], ], [ '$id' => ID::custom('abc'), 'teamId' => ID::custom('def'), 'confirm' => true, 'roles' => [ - 'guest' - ] - ] - ] + 'guest', + ], + ], + ], ]); $roles = Auth::getRoles($user); @@ -453,7 +453,7 @@ class AuthTest extends TestCase public function testAppUserRoles(): void { Authorization::setRole(Auth::USER_ROLE_APPS); - $user = new Document([ + $user = new Document([ '$id' => ID::custom('123'), 'memberships' => [ [ @@ -462,18 +462,18 @@ class AuthTest extends TestCase 'confirm' => true, 'roles' => [ 'administrator', - 'moderator' - ] + 'moderator', + ], ], [ '$id' => ID::custom('abc'), 'teamId' => ID::custom('def'), 'confirm' => true, 'roles' => [ - 'guest' - ] - ] - ] + 'guest', + ], + ], + ], ]); $roles = Auth::getRoles($user); diff --git a/tests/unit/DSN/DSNTest.php b/tests/unit/DSN/DSNTest.php index d1f5ba1197..4055dfbc6e 100644 --- a/tests/unit/DSN/DSNTest.php +++ b/tests/unit/DSN/DSNTest.php @@ -9,65 +9,65 @@ class DSNTest extends TestCase { public function testSuccess(): void { - $dsn = new DSN("mariadb://user:password@localhost:3306/database?charset=utf8&timezone=UTC"); - $this->assertEquals("mariadb", $dsn->getScheme()); - $this->assertEquals("user", $dsn->getUser()); - $this->assertEquals("password", $dsn->getPassword()); - $this->assertEquals("localhost", $dsn->getHost()); - $this->assertEquals("3306", $dsn->getPort()); - $this->assertEquals("database", $dsn->getDatabase()); - $this->assertEquals("charset=utf8&timezone=UTC", $dsn->getQuery()); + $dsn = new DSN('mariadb://user:password@localhost:3306/database?charset=utf8&timezone=UTC'); + $this->assertEquals('mariadb', $dsn->getScheme()); + $this->assertEquals('user', $dsn->getUser()); + $this->assertEquals('password', $dsn->getPassword()); + $this->assertEquals('localhost', $dsn->getHost()); + $this->assertEquals('3306', $dsn->getPort()); + $this->assertEquals('database', $dsn->getDatabase()); + $this->assertEquals('charset=utf8&timezone=UTC', $dsn->getQuery()); - $dsn = new DSN("mariadb://user@localhost:3306/database?charset=utf8&timezone=UTC"); - $this->assertEquals("mariadb", $dsn->getScheme()); - $this->assertEquals("user", $dsn->getUser()); + $dsn = new DSN('mariadb://user@localhost:3306/database?charset=utf8&timezone=UTC'); + $this->assertEquals('mariadb', $dsn->getScheme()); + $this->assertEquals('user', $dsn->getUser()); $this->assertNull($dsn->getPassword()); - $this->assertEquals("localhost", $dsn->getHost()); - $this->assertEquals("3306", $dsn->getPort()); - $this->assertEquals("database", $dsn->getDatabase()); - $this->assertEquals("charset=utf8&timezone=UTC", $dsn->getQuery()); + $this->assertEquals('localhost', $dsn->getHost()); + $this->assertEquals('3306', $dsn->getPort()); + $this->assertEquals('database', $dsn->getDatabase()); + $this->assertEquals('charset=utf8&timezone=UTC', $dsn->getQuery()); - $dsn = new DSN("mariadb://user@localhost/database?charset=utf8&timezone=UTC"); - $this->assertEquals("mariadb", $dsn->getScheme()); - $this->assertEquals("user", $dsn->getUser()); + $dsn = new DSN('mariadb://user@localhost/database?charset=utf8&timezone=UTC'); + $this->assertEquals('mariadb', $dsn->getScheme()); + $this->assertEquals('user', $dsn->getUser()); $this->assertNull($dsn->getPassword()); - $this->assertEquals("localhost", $dsn->getHost()); + $this->assertEquals('localhost', $dsn->getHost()); $this->assertNull($dsn->getPort()); - $this->assertEquals("database", $dsn->getDatabase()); - $this->assertEquals("charset=utf8&timezone=UTC", $dsn->getQuery()); + $this->assertEquals('database', $dsn->getDatabase()); + $this->assertEquals('charset=utf8&timezone=UTC', $dsn->getQuery()); - $dsn = new DSN("mariadb://user@localhost?charset=utf8&timezone=UTC"); - $this->assertEquals("mariadb", $dsn->getScheme()); - $this->assertEquals("user", $dsn->getUser()); + $dsn = new DSN('mariadb://user@localhost?charset=utf8&timezone=UTC'); + $this->assertEquals('mariadb', $dsn->getScheme()); + $this->assertEquals('user', $dsn->getUser()); $this->assertNull($dsn->getPassword()); - $this->assertEquals("localhost", $dsn->getHost()); + $this->assertEquals('localhost', $dsn->getHost()); $this->assertNull($dsn->getPort()); $this->assertEmpty($dsn->getDatabase()); - $this->assertEquals("charset=utf8&timezone=UTC", $dsn->getQuery()); + $this->assertEquals('charset=utf8&timezone=UTC', $dsn->getQuery()); - $dsn = new DSN("mariadb://user@localhost"); - $this->assertEquals("mariadb", $dsn->getScheme()); - $this->assertEquals("user", $dsn->getUser()); + $dsn = new DSN('mariadb://user@localhost'); + $this->assertEquals('mariadb', $dsn->getScheme()); + $this->assertEquals('user', $dsn->getUser()); $this->assertNull($dsn->getPassword()); - $this->assertEquals("localhost", $dsn->getHost()); + $this->assertEquals('localhost', $dsn->getHost()); $this->assertNull($dsn->getPort()); $this->assertEmpty($dsn->getDatabase()); $this->assertNull($dsn->getQuery()); - $dsn = new DSN("mariadb://user:@localhost"); - $this->assertEquals("mariadb", $dsn->getScheme()); - $this->assertEquals("user", $dsn->getUser()); + $dsn = new DSN('mariadb://user:@localhost'); + $this->assertEquals('mariadb', $dsn->getScheme()); + $this->assertEquals('user', $dsn->getUser()); $this->assertEmpty($dsn->getPassword()); - $this->assertEquals("localhost", $dsn->getHost()); + $this->assertEquals('localhost', $dsn->getHost()); $this->assertNull($dsn->getPort()); $this->assertEmpty($dsn->getDatabase()); $this->assertNull($dsn->getQuery()); - $dsn = new DSN("mariadb://localhost"); - $this->assertEquals("mariadb", $dsn->getScheme()); + $dsn = new DSN('mariadb://localhost'); + $this->assertEquals('mariadb', $dsn->getScheme()); $this->assertNull($dsn->getUser()); $this->assertNull($dsn->getPassword()); - $this->assertEquals("localhost", $dsn->getHost()); + $this->assertEquals('localhost', $dsn->getHost()); $this->assertNull($dsn->getPort()); $this->assertEmpty($dsn->getDatabase()); $this->assertNull($dsn->getQuery()); @@ -76,6 +76,6 @@ class DSNTest extends TestCase public function testFail(): void { $this->expectException(\InvalidArgumentException::class); - new DSN("mariadb://"); + new DSN('mariadb://'); } } diff --git a/tests/unit/Docker/ComposeTest.php b/tests/unit/Docker/ComposeTest.php index 9f974b5970..42e4276b51 100644 --- a/tests/unit/Docker/ComposeTest.php +++ b/tests/unit/Docker/ComposeTest.php @@ -12,7 +12,7 @@ class ComposeTest extends TestCase public function setUp(): void { - $data = @file_get_contents(__DIR__ . '/../../resources/docker/docker-compose.yml'); + $data = @file_get_contents(__DIR__.'/../../resources/docker/docker-compose.yml'); if ($data === false) { throw new Exception('Failed to read compose file'); diff --git a/tests/unit/Docker/EnvTest.php b/tests/unit/Docker/EnvTest.php index e6c9b8cadf..b271bde504 100644 --- a/tests/unit/Docker/EnvTest.php +++ b/tests/unit/Docker/EnvTest.php @@ -12,7 +12,7 @@ class EnvTest extends TestCase public function setUp(): void { - $data = @file_get_contents(__DIR__ . '/../../resources/docker/.env'); + $data = @file_get_contents(__DIR__.'/../../resources/docker/.env'); if ($data === false) { throw new Exception('Failed to read compose file'); @@ -34,10 +34,10 @@ class EnvTest extends TestCase public function testExport(): void { - $this->assertEquals("_APP_X=value1 + $this->assertEquals('_APP_X=value1 _APP_Y=value2 _APP_Z=value3 _APP_W=value5= -", $this->object->export()); +', $this->object->export()); } } diff --git a/tests/unit/Event/EventTest.php b/tests/unit/Event/EventTest.php index dee905638f..6167d6156b 100644 --- a/tests/unit/Event/EventTest.php +++ b/tests/unit/Event/EventTest.php @@ -10,15 +10,16 @@ use Utopia\App; class EventTest extends TestCase { protected ?Event $object = null; + protected string $queue = ''; public function setUp(): void { $redisHost = App::getEnv('_APP_REDIS_HOST', ''); $redisPort = App::getEnv('_APP_REDIS_PORT', ''); - \Resque::setBackend($redisHost . ':' . $redisPort); + \Resque::setBackend($redisHost.':'.$redisPort); - $this->queue = 'v1-tests' . uniqid(); + $this->queue = 'v1-tests'.uniqid(); $this->object = new Event($this->queue, 'TestsV1'); } @@ -77,7 +78,7 @@ class EventTest extends TestCase public function testGenerateEvents(): void { $event = Event::generateEvents('users.[userId].create', [ - 'userId' => 'torsten' + 'userId' => 'torsten', ]); $this->assertCount(4, $event); $this->assertContains('users.torsten.create', $event); @@ -86,7 +87,7 @@ class EventTest extends TestCase $this->assertContains('users.*', $event); $event = Event::generateEvents('users.[userId].update.email', [ - 'userId' => 'torsten' + 'userId' => 'torsten', ]); $this->assertCount(6, $event); $this->assertContains('users.torsten.update.email', $event); @@ -143,10 +144,9 @@ class EventTest extends TestCase $this->assertContains('databases.chaptersDB.collections.*.documents.*', $event); $this->assertContains('databases.chaptersDB.collections.*.documents.*.create', $event); - try { $event = Event::generateEvents('collections.[collectionId].documents.[documentId].create', [ - 'collectionId' => 'chapters' + 'collectionId' => 'chapters', ]); $this->fail(); } catch (\Throwable $th) { diff --git a/tests/unit/General/CollectionsTest.php b/tests/unit/General/CollectionsTest.php index 1d648f93c2..3727672faa 100644 --- a/tests/unit/General/CollectionsTest.php +++ b/tests/unit/General/CollectionsTest.php @@ -10,7 +10,7 @@ class CollectionsTest extends TestCase public function setUp(): void { - $this->collections = require('app/config/collections.php'); + $this->collections = require 'app/config/collections.php'; } public function testDuplicateRules(): void diff --git a/tests/unit/Messaging/MessagingChannelsTest.php b/tests/unit/Messaging/MessagingChannelsTest.php index 6fe7dda71f..14ec84a8e6 100644 --- a/tests/unit/Messaging/MessagingChannelsTest.php +++ b/tests/unit/Messaging/MessagingChannelsTest.php @@ -3,9 +3,9 @@ namespace Tests\Unit\Messaging; use Appwrite\Auth\Auth; -use Utopia\Database\Document; use Appwrite\Messaging\Adapter\Realtime; use PHPUnit\Framework\TestCase; +use Utopia\Database\Document; use Utopia\Database\Helpers\ID; use Utopia\Database\Helpers\Role; @@ -17,10 +17,15 @@ class MessagingChannelsTest extends TestCase public $connectionsPerChannel = 10; public Realtime $realtime; + public $connectionsCount = 0; + public $connectionsAuthenticated = 0; + public $connectionsGuest = 0; + public $connectionsTotal = 0; + public $allChannels = [ 'files', 'files.1', @@ -51,19 +56,19 @@ class MessagingChannelsTest extends TestCase for ($i = 0; $i < $this->connectionsPerChannel; $i++) { foreach ($this->allChannels as $index => $channel) { $user = new Document([ - '$id' => ID::custom('user' . $this->connectionsCount), + '$id' => ID::custom('user'.$this->connectionsCount), 'memberships' => [ [ - '$id' => ID::custom('member' . $i), - 'teamId' => ID::custom('team' . $i), + '$id' => ID::custom('member'.$i), + 'teamId' => ID::custom('team'.$i), 'confirm' => true, 'roles' => [ empty($index % 2) ? Auth::USER_ROLE_ADMIN : 'member', - ] - ] - ] + ], + ], + ], ]); $roles = Auth::getRoles($user); @@ -87,7 +92,7 @@ class MessagingChannelsTest extends TestCase for ($i = 0; $i < $this->connectionsPerChannel; $i++) { foreach ($this->allChannels as $index => $channel) { $user = new Document([ - '$id' => '' + '$id' => '', ]); $roles = Auth::getRoles($user); @@ -170,8 +175,8 @@ class MessagingChannelsTest extends TestCase 'data' => [ 'channels' => [ 0 => $channel, - ] - ] + ], + ], ]; $receivers = $this->realtime->getSubscribers($event); @@ -194,7 +199,7 @@ class MessagingChannelsTest extends TestCase { $roles = [ Role::guests()->toString(), - Role::users()->toString() + Role::users()->toString(), ]; foreach ($this->allChannels as $index => $channel) { foreach ($roles as $role) { @@ -206,8 +211,8 @@ class MessagingChannelsTest extends TestCase 'data' => [ 'channels' => [ 0 => $channel, - ] - ] + ], + ], ]; $receivers = $this->realtime->getSubscribers($event); @@ -232,7 +237,7 @@ class MessagingChannelsTest extends TestCase foreach ($this->allChannels as $index => $channel) { $permissions = []; for ($i = 0; $i < $this->connectionsPerChannel; $i++) { - $permissions[] = Role::user(ID::custom('user' . (!empty($i) ? $i : '') . $index))->toString(); + $permissions[] = Role::user(ID::custom('user'.(! empty($i) ? $i : '').$index))->toString(); } $event = [ 'project' => '1', @@ -240,8 +245,8 @@ class MessagingChannelsTest extends TestCase 'data' => [ 'channels' => [ 0 => $channel, - ] - ] + ], + ], ]; $receivers = $this->realtime->getSubscribers($event); @@ -266,8 +271,8 @@ class MessagingChannelsTest extends TestCase $permissions = []; for ($i = 0; $i < $this->connectionsPerChannel; $i++) { - $permissions[] = Role::team(ID::custom('team' . $i))->toString(); - $permissions[] = Role::member(ID::custom('member' . $i))->toString(); + $permissions[] = Role::team(ID::custom('team'.$i))->toString(); + $permissions[] = Role::member(ID::custom('member'.$i))->toString(); } $event = [ 'project' => '1', @@ -275,8 +280,8 @@ class MessagingChannelsTest extends TestCase 'data' => [ 'channels' => [ 0 => $channel, - ] - ] + ], + ], ]; $receivers = $this->realtime->getSubscribers($event); @@ -298,8 +303,8 @@ class MessagingChannelsTest extends TestCase : 'member'; $permissions = [ - Role::team(ID::custom('team' . $index), $role)->toString(), - Role::member(ID::custom('member' . $index))->toString() + Role::team(ID::custom('team'.$index), $role)->toString(), + Role::member(ID::custom('member'.$index))->toString(), ]; $event = [ @@ -308,8 +313,8 @@ class MessagingChannelsTest extends TestCase 'data' => [ 'channels' => [ 0 => $channel, - ] - ] + ], + ], ]; $receivers = $this->realtime->getSubscribers($event); diff --git a/tests/unit/Messaging/MessagingGuestTest.php b/tests/unit/Messaging/MessagingGuestTest.php index 1aaa1febca..660e9519e3 100644 --- a/tests/unit/Messaging/MessagingGuestTest.php +++ b/tests/unit/Messaging/MessagingGuestTest.php @@ -27,8 +27,8 @@ class MessagingGuestTest extends TestCase 'channels' => [ 0 => 'documents', 1 => 'documents', - ] - ] + ], + ], ]; $receivers = $realtime->getSubscribers($event); diff --git a/tests/unit/Messaging/MessagingTest.php b/tests/unit/Messaging/MessagingTest.php index c2e3971945..d6ae6b095b 100644 --- a/tests/unit/Messaging/MessagingTest.php +++ b/tests/unit/Messaging/MessagingTest.php @@ -2,9 +2,9 @@ namespace Tests\Unit\Messaging; -use Utopia\Database\Document; use Appwrite\Messaging\Adapter\Realtime; use PHPUnit\Framework\TestCase; +use Utopia\Database\Document; use Utopia\Database\Helpers\ID; use Utopia\Database\Helpers\Permission; use Utopia\Database\Helpers\Role; @@ -44,8 +44,8 @@ class MessagingTest extends TestCase 'data' => [ 'channels' => [ 0 => 'account.123', - ] - ] + ], + ], ]; $receivers = $realtime->getSubscribers($event); @@ -148,7 +148,7 @@ class MessagingTest extends TestCase public function testConvertChannelsGuest(): void { $user = new Document([ - '$id' => '' + '$id' => '', ]); $channels = [ @@ -156,7 +156,7 @@ class MessagingTest extends TestCase 1 => 'documents', 2 => 'documents.789', 3 => 'account', - 4 => 'account.456' + 4 => 'account.456', ]; $channels = Realtime::convertChannels($channels, $user->getId()); @@ -170,30 +170,30 @@ class MessagingTest extends TestCase public function testConvertChannelsUser(): void { - $user = new Document([ + $user = new Document([ '$id' => ID::custom('123'), 'memberships' => [ [ 'teamId' => ID::custom('abc'), 'roles' => [ 'administrator', - 'moderator' - ] + 'moderator', + ], ], [ 'teamId' => ID::custom('def'), 'roles' => [ - 'guest' - ] - ] - ] + 'guest', + ], + ], + ], ]); $channels = [ 0 => 'files', 1 => 'documents', 2 => 'documents.789', 3 => 'account', - 4 => 'account.456' + 4 => 'account.456', ]; $channels = Realtime::convertChannels($channels, $user->getId()); @@ -321,7 +321,7 @@ class MessagingTest extends TestCase Permission::update(Role::team('123abc')), Permission::delete(Role::team('123abc')), ], - 'fileSecurity' => true + 'fileSecurity' => true, ]) ); diff --git a/tests/unit/Migration/MigrationTest.php b/tests/unit/Migration/MigrationTest.php index 13f9b9a3f5..c322cc9635 100644 --- a/tests/unit/Migration/MigrationTest.php +++ b/tests/unit/Migration/MigrationTest.php @@ -22,12 +22,12 @@ abstract class MigrationTest extends TestCase /** * Runs every document fix twice, to prevent corrupted data on multiple migrations. * - * @param Document $document + * @param Document $document */ protected function fixDocument(Document $document) { return $this->method->invokeArgs($this->migration, [ - $this->method->invokeArgs($this->migration, [$document]) + $this->method->invokeArgs($this->migration, [$document]), ]); } @@ -36,14 +36,14 @@ abstract class MigrationTest extends TestCase */ public function testMigrationVersions(): void { - require_once __DIR__ . '/../../../app/init.php'; + require_once __DIR__.'/../../../app/init.php'; foreach (Migration::$versions as $class) { - $this->assertTrue(class_exists('Appwrite\\Migration\\Version\\' . $class)); + $this->assertTrue(class_exists('Appwrite\\Migration\\Version\\'.$class)); } // Test if current version exists // Only test official releases - skip if latest is release candidate - if (!(\str_contains(APP_VERSION_STABLE, 'RC'))) { + if (! (\str_contains(APP_VERSION_STABLE, 'RC'))) { $this->assertArrayHasKey(APP_VERSION_STABLE, Migration::$versions); } } @@ -60,8 +60,8 @@ abstract class MigrationTest extends TestCase 'a' => true, 'b' => 'abc', 'c' => 123, - 'd' => ['a', 'b', 'c'] - ] + 'd' => ['a', 'b', 'c'], + ], ], [ 'bool' => true, 'string' => 'abc', @@ -71,8 +71,8 @@ abstract class MigrationTest extends TestCase 'a' => true, 'b' => 'abc', 'c' => 123, - 'd' => ['a', 'b', 'c'] - ] + 'd' => ['a', 'b', 'c'], + ], ])); $this->assertFalse(Migration::hasDifference([ 'bool' => true, @@ -83,15 +83,15 @@ abstract class MigrationTest extends TestCase 'a' => true, 'b' => 'abc', 'c' => 123, - 'd' => ['a', 'b', 'c'] - ] + 'd' => ['a', 'b', 'c'], + ], ], [ 'string' => 'abc', 'assoc' => [ 'a' => true, 'b' => 'abc', 'c' => 123, - 'd' => ['a', 'b', 'c'] + 'd' => ['a', 'b', 'c'], ], 'int' => 123, 'array' => ['a', 'b', 'c'], @@ -99,40 +99,40 @@ abstract class MigrationTest extends TestCase ])); $this->assertTrue(Migration::hasDifference([ - 'a' => true + 'a' => true, ], [ - 'b' => true + 'b' => true, ])); $this->assertTrue(Migration::hasDifference([ - 'a' => 'true' + 'a' => 'true', ], [ - 'a' => true + 'a' => true, ])); $this->assertTrue(Migration::hasDifference([ - 'a' => true + 'a' => true, ], [ - 'a' => false + 'a' => false, ])); $this->assertTrue(Migration::hasDifference([ 'nested' => [ - 'a' => true - ] + 'a' => true, + ], ], [ - 'nested' => [] + 'nested' => [], ])); $this->assertTrue(Migration::hasDifference([ 'assoc' => [ 'bool' => true, 'string' => 'abc', 'int' => 123, - 'array' => ['a', 'b', 'c'] - ] + 'array' => ['a', 'b', 'c'], + ], ], [ 'nested' => [ 'a' => true, 'int' => '123', - 'array' => ['a', 'b', 'c'] - ] + 'array' => ['a', 'b', 'c'], + ], ])); } } diff --git a/tests/unit/Network/Validators/EmailTest.php b/tests/unit/Network/Validators/EmailTest.php index f629ed6ddc..d74f2c30fc 100755 --- a/tests/unit/Network/Validators/EmailTest.php +++ b/tests/unit/Network/Validators/EmailTest.php @@ -3,12 +3,13 @@ /** * Utopia PHP Framework * - * @package Framework - * @subpackage Tests * * @link https://github.com/utopia-php/framework + * * @author Appwrite Team + * * @version 1.0 RC4 + * * @license The MIT License (MIT) */ diff --git a/tests/unit/Template/TemplateTest.php b/tests/unit/Template/TemplateTest.php index 1ca1595ca3..ab4cb49742 100644 --- a/tests/unit/Template/TemplateTest.php +++ b/tests/unit/Template/TemplateTest.php @@ -14,10 +14,9 @@ class TemplateTest extends TestCase public function setUp(): void { - $this->object = new Template(__DIR__ . '/../../resources/template.tpl'); + $this->object = new Template(__DIR__.'/../../resources/template.tpl'); $this->object - ->setParam('{{world}}', 'WORLD') - ; + ->setParam('{{world}}', 'WORLD'); } public function tearDown(): void diff --git a/tests/unit/Usage/StatsTest.php b/tests/unit/Usage/StatsTest.php index f021841396..28309dfc4a 100644 --- a/tests/unit/Usage/StatsTest.php +++ b/tests/unit/Usage/StatsTest.php @@ -39,8 +39,7 @@ class StatsTest extends TestCase $this->object ->setParam('projectId', 'appwrite_test') ->setParam('projectInternalId', 1) - ->setParam('networkRequestSize', 100) - ; + ->setParam('networkRequestSize', 100); $this->assertEquals('appwrite_test', $this->object->getParam('projectId')); $this->assertEquals(1, $this->object->getParam('projectInternalId')); @@ -56,8 +55,7 @@ class StatsTest extends TestCase { $this->object ->setParam('projectId', 'appwrite_test') - ->setParam('networkRequestSize', 100) - ; + ->setParam('networkRequestSize', 100); $this->assertEquals('appwrite_test', $this->object->getParam('projectId')); $this->assertEquals(100, $this->object->getParam('networkRequestSize')); diff --git a/tests/unit/Utopia/Database/Validator/IndexedQueriesTest.php b/tests/unit/Utopia/Database/Validator/IndexedQueriesTest.php index 52375004ca..a9909eb9ce 100644 --- a/tests/unit/Utopia/Database/Validator/IndexedQueriesTest.php +++ b/tests/unit/Utopia/Database/Validator/IndexedQueriesTest.php @@ -33,7 +33,7 @@ class IndexedQueriesTest extends TestCase { $validator = new IndexedQueries(); - $this->assertEquals(false, $validator->isValid(["this.is.invalid"])); + $this->assertEquals(false, $validator->isValid(['this.is.invalid'])); } public function testInvalidMethod(): void diff --git a/tests/unit/Utopia/Database/Validator/QueriesTest.php b/tests/unit/Utopia/Database/Validator/QueriesTest.php index 55e04c2b84..54e16fe42e 100644 --- a/tests/unit/Utopia/Database/Validator/QueriesTest.php +++ b/tests/unit/Utopia/Database/Validator/QueriesTest.php @@ -33,7 +33,7 @@ class QueriesTest extends TestCase { $validator = new Queries(); - $this->assertEquals(false, $validator->isValid(["this.is.invalid"])); + $this->assertEquals(false, $validator->isValid(['this.is.invalid'])); } public function testInvalidMethod(): void @@ -58,7 +58,7 @@ class QueriesTest extends TestCase 'key' => 'name', 'type' => Database::VAR_STRING, 'array' => false, - ]) + ]), ]; $validator = new Queries( new Cursor(), diff --git a/tests/unit/Utopia/Database/Validator/Query/CursorTest.php b/tests/unit/Utopia/Database/Validator/Query/CursorTest.php index 0afc8baddd..09995f357e 100644 --- a/tests/unit/Utopia/Database/Validator/Query/CursorTest.php +++ b/tests/unit/Utopia/Database/Validator/Query/CursorTest.php @@ -4,8 +4,8 @@ namespace Tests\Unit\Utopia\Database\Validator\Query; use Appwrite\Utopia\Database\Validator\Query\Base; use Appwrite\Utopia\Database\Validator\Query\Cursor; -use Utopia\Database\Query; use PHPUnit\Framework\TestCase; +use Utopia\Database\Query; class CursorTest extends TestCase { diff --git a/tests/unit/Utopia/Database/Validator/Query/FilterTest.php b/tests/unit/Utopia/Database/Validator/Query/FilterTest.php index 8f2f1d44ba..b321a71542 100644 --- a/tests/unit/Utopia/Database/Validator/Query/FilterTest.php +++ b/tests/unit/Utopia/Database/Validator/Query/FilterTest.php @@ -4,10 +4,10 @@ namespace Tests\Unit\Utopia\Database\Validator\Query; use Appwrite\Utopia\Database\Validator\Query\Base; use Appwrite\Utopia\Database\Validator\Query\Filter; +use PHPUnit\Framework\TestCase; use Utopia\Database\Database; use Utopia\Database\Document; use Utopia\Database\Query; -use PHPUnit\Framework\TestCase; class FilterTest extends TestCase { diff --git a/tests/unit/Utopia/Database/Validator/Query/LimitTest.php b/tests/unit/Utopia/Database/Validator/Query/LimitTest.php index 1594d0db1f..cfb7a42823 100644 --- a/tests/unit/Utopia/Database/Validator/Query/LimitTest.php +++ b/tests/unit/Utopia/Database/Validator/Query/LimitTest.php @@ -4,8 +4,8 @@ namespace Tests\Unit\Utopia\Database\Validator\Query; use Appwrite\Utopia\Database\Validator\Query\Base; use Appwrite\Utopia\Database\Validator\Query\Limit; -use Utopia\Database\Query; use PHPUnit\Framework\TestCase; +use Utopia\Database\Query; class LimitTest extends TestCase { diff --git a/tests/unit/Utopia/Database/Validator/Query/OffsetTest.php b/tests/unit/Utopia/Database/Validator/Query/OffsetTest.php index 4a29117e83..756e5523b5 100644 --- a/tests/unit/Utopia/Database/Validator/Query/OffsetTest.php +++ b/tests/unit/Utopia/Database/Validator/Query/OffsetTest.php @@ -4,8 +4,8 @@ namespace Tests\Unit\Utopia\Database\Validator\Query; use Appwrite\Utopia\Database\Validator\Query\Base; use Appwrite\Utopia\Database\Validator\Query\Offset; -use Utopia\Database\Query; use PHPUnit\Framework\TestCase; +use Utopia\Database\Query; class OffsetTest extends TestCase { diff --git a/tests/unit/Utopia/Database/Validator/Query/OrderTest.php b/tests/unit/Utopia/Database/Validator/Query/OrderTest.php index fe1b42d5c1..bb353b15e5 100644 --- a/tests/unit/Utopia/Database/Validator/Query/OrderTest.php +++ b/tests/unit/Utopia/Database/Validator/Query/OrderTest.php @@ -4,10 +4,10 @@ namespace Tests\Unit\Utopia\Database\Validator\Query; use Appwrite\Utopia\Database\Validator\Query\Base; use Appwrite\Utopia\Database\Validator\Query\Order; +use PHPUnit\Framework\TestCase; use Utopia\Database\Database; use Utopia\Database\Document; use Utopia\Database\Query; -use PHPUnit\Framework\TestCase; class OrderTest extends TestCase { diff --git a/tests/unit/Utopia/Lists.php b/tests/unit/Utopia/Lists.php index 8f003cc2ae..ac54a293a5 100644 --- a/tests/unit/Utopia/Lists.php +++ b/tests/unit/Utopia/Lists.php @@ -12,7 +12,7 @@ class Lists extends Model ->addRule('singles', [ 'type' => 'single', 'default' => '', - 'array' => true + 'array' => true, ]); } diff --git a/tests/unit/Utopia/Nested.php b/tests/unit/Utopia/Nested.php index 2be0e85762..b18f73977e 100644 --- a/tests/unit/Utopia/Nested.php +++ b/tests/unit/Utopia/Nested.php @@ -15,7 +15,7 @@ class Nested extends Model ]) ->addRule('single', [ 'type' => 'single', - 'default' => '' + 'default' => '', ]); } diff --git a/tests/unit/Utopia/Request/Filters/V15Test.php b/tests/unit/Utopia/Request/Filters/V15Test.php index 70bf71d4cb..7a37213d44 100644 --- a/tests/unit/Utopia/Request/Filters/V15Test.php +++ b/tests/unit/Utopia/Request/Filters/V15Test.php @@ -28,7 +28,7 @@ class V15Test extends TestCase return [ 'basic test' => [ ['limit' => '12', 'offset' => '0'], - ['queries' => ['limit(12)', 'offset(0)']] + ['queries' => ['limit(12)', 'offset(0)']], ], ]; } @@ -72,8 +72,8 @@ class V15Test extends TestCase 'limit(12)', 'offset(0)', 'cursorBefore("abcd")', - 'orderAsc("")' - ] + 'orderAsc("")', + ], ], ], ]; @@ -90,7 +90,7 @@ class V15Test extends TestCase [ 'queries' => [ 'cursorAfter("abcd")', - ] + ], ], ], 'cursorDirection invalid' => [ @@ -101,7 +101,7 @@ class V15Test extends TestCase [ 'queries' => [ 'cursorAfter("abcd")', - ] + ], ], ], ]; @@ -117,7 +117,7 @@ class V15Test extends TestCase [ 'queries' => [ 'orderDesc("")', - ] + ], ], ], 'orderType invalid' => [ @@ -127,7 +127,7 @@ class V15Test extends TestCase [ 'queries' => [ 'orderAsc("")', - ] + ], ], ], ]; @@ -239,7 +239,7 @@ class V15Test extends TestCase 'write invalid' => [ ['write' => ['invalid', 'invalid:a']], ['permissions' => ['write("invalid:a")']], - ] + ], ]; } @@ -320,7 +320,7 @@ class V15Test extends TestCase 'queries' => [ 'orderDesc("lastName")', 'orderAsc("firstName")', - ] + ], ], ], 'orderType only' => [ @@ -330,7 +330,7 @@ class V15Test extends TestCase [ 'queries' => [ 'orderDesc("")', - ] + ], ], ], 'orderType invalid' => [ @@ -341,7 +341,7 @@ class V15Test extends TestCase [ 'queries' => [ 'orderAsc("lastName")', - ] + ], ], ], ]; @@ -371,7 +371,7 @@ class V15Test extends TestCase 'greaterThan("age", [20])', 'greaterThanEqual("age", [21])', 'search("address", ["pla"])', - ] + ], ], ], ]; @@ -439,7 +439,7 @@ class V15Test extends TestCase 'team:b', 'team:c/member', 'member:z', - ] + ], ], ], ]; diff --git a/tests/unit/Utopia/Response/Filters/V15Test.php b/tests/unit/Utopia/Response/Filters/V15Test.php index ab3a0b06ed..cf08d9bb70 100644 --- a/tests/unit/Utopia/Response/Filters/V15Test.php +++ b/tests/unit/Utopia/Response/Filters/V15Test.php @@ -2,12 +2,11 @@ namespace Tests\Unit\Utopia\Response\Filters; -use Appwrite\Utopia\Response\Filters\V15; use Appwrite\Utopia\Response; +use Appwrite\Utopia\Response\Filters\V15; +use PHPUnit\Framework\TestCase; use Utopia\Database\Helpers\Permission; use Utopia\Database\Helpers\Role; -use PHPUnit\Framework\TestCase; -use stdClass; class V15Test extends TestCase { @@ -197,7 +196,7 @@ class V15Test extends TestCase 'maximumFileSize' => 100, 'allowedFileExtensions' => [ 'jpg', - 'png' + 'png', ], 'encryption' => false, 'antivirus' => false, @@ -214,7 +213,7 @@ class V15Test extends TestCase 'maximumFileSize' => 100, 'allowedFileExtensions' => [ 'jpg', - 'png' + 'png', ], 'encryption' => false, 'antivirus' => false, @@ -276,8 +275,8 @@ class V15Test extends TestCase [ 'startTime' => 1592981250, 'endTime' => 1592981250, - ] - ] + ], + ], ]; } @@ -347,14 +346,14 @@ class V15Test extends TestCase 'status' => 'available', 'required' => true, 'array' => false, - 'default' => false + 'default' => false, ], 'indexes' => [ 'key' => 'index1', 'type' => 'primary', 'status' => 'available', 'attributes' => [], - 'orders' => [] + 'orders' => [], ], ], [ @@ -362,10 +361,10 @@ class V15Test extends TestCase '$createdAt' => 1592981250, '$updatedAt' => 1592981250, '$read' => [ - 'role:all' + 'role:all', ], '$write' => [ - 'user:608f9da25e7e1' + 'user:608f9da25e7e1', ], 'databaseId' => '5e5ea5c16897e', 'name' => 'My Collection', @@ -377,14 +376,14 @@ class V15Test extends TestCase 'status' => 'available', 'required' => true, 'array' => false, - 'default' => false + 'default' => false, ], 'indexes' => [ 'key' => 'index1', 'type' => 'primary', 'status' => 'available', 'attributes' => [], - 'orders' => [] + 'orders' => [], ], ], ], @@ -512,7 +511,7 @@ class V15Test extends TestCase '$databaseId' => '5e5ea5c15117e', '$createdAt' => '2020-06-24T06:47:30.000Z', '$updatedAt' => '2020-06-24T06:47:30.000Z', - '$permissions' => [Permission::read(Role::any())] + '$permissions' => [Permission::read(Role::any())], ], [ '$id' => '5e5ea5c16897e', @@ -606,7 +605,7 @@ class V15Test extends TestCase '$createdAt' => '2020-06-24T06:47:30.000Z', '$updatedAt' => '2020-06-24T06:47:30.000Z', '$permissions' => [ - "any" + 'any', ], 'functionId' => '5e5ea6g16897e', 'trigger' => 'http', @@ -615,14 +614,14 @@ class V15Test extends TestCase 'response' => '', 'stdout' => '', 'stderr' => '', - 'duration' => 0.4 + 'duration' => 0.4, ], [ '$id' => '5e5ea5c16897e', '$createdAt' => 1592981250, '$updatedAt' => 1592981250, '$read' => [ - "role:all" + 'role:all', ], 'functionId' => '5e5ea6g16897e', 'trigger' => 'http', @@ -630,7 +629,7 @@ class V15Test extends TestCase 'statusCode' => 0, 'response' => '', 'stderr' => '', - 'time' => 0.4 + 'time' => 0.4, ], ], ]; @@ -731,37 +730,37 @@ class V15Test extends TestCase 'key' => 'key', 'value' => 'value', 'functionId' => '5e5ea5c16897e', - ] + ], ], 'events' => [ - 'account.create' + 'account.create', ], 'schedule' => '5 4 * * *', 'scheduleNext' => '2020-06-24T06:48:12.000Z', 'schedulePrevious' => '2020-06-24T06:47:17.000Z', - 'timeout' => 1592981237 + 'timeout' => 1592981237, ], [ '$id' => '5e5ea5c16897e', '$createdAt' => 1592981250, '$updatedAt' => 1592981250, 'execute' => [ - 'role:member' + 'role:member', ], 'name' => 'My Function', 'status' => 'enabled', 'runtime' => 'python-3.8', 'deployment' => '5e5ea5c16897e', 'vars' => [ - 'key' => 'value' + 'key' => 'value', ], 'events' => [ - 'account.create' + 'account.create', ], 'schedule' => '5 4 * * *', 'scheduleNext' => 1592981292, 'schedulePrevious' => 1592981237, - 'timeout' => 1592981237 + 'timeout' => 1592981237, ], ], 'enabled false' => [ @@ -878,7 +877,7 @@ class V15Test extends TestCase 'deviceBrand' => 'Google', 'deviceModel' => 'Nexus 5', 'countryCode' => 'US', - 'countryName' => 'United States' + 'countryName' => 'United States', ], [ 'event' => 'account.sessions.create', @@ -901,8 +900,8 @@ class V15Test extends TestCase 'deviceBrand' => 'Google', 'deviceModel' => 'Nexus 5', 'countryCode' => 'US', - 'countryName' => 'United States' - ] + 'countryName' => 'United States', + ], ], ]; } diff --git a/tests/unit/Utopia/ResponseTest.php b/tests/unit/Utopia/ResponseTest.php index e4389b3953..f7be5a03a4 100644 --- a/tests/unit/Utopia/ResponseTest.php +++ b/tests/unit/Utopia/ResponseTest.php @@ -2,9 +2,9 @@ namespace Tests\Unit\Utopia; -use Exception; use Appwrite\Utopia\Response; use Appwrite\Utopia\Response\Filters\V11; +use Exception; use PHPUnit\Framework\TestCase; use Swoole\Http\Response as SwooleResponse; use Utopia\Database\Document; @@ -80,8 +80,8 @@ class ResponseTest extends TestCase 'string' => 'lorem ipsum', 'integer' => 123, 'boolean' => true, - 'hidden' => 'secret' - ]) + 'hidden' => 'secret', + ]), ], 'hidden' => 'secret', ]), 'lists'); @@ -107,8 +107,8 @@ class ResponseTest extends TestCase 'string' => 'lorem ipsum', 'integer' => 123, 'boolean' => true, - 'hidden' => 'secret' - ]) + 'hidden' => 'secret', + ]), ], 'hidden' => 'secret', ]), @@ -116,7 +116,7 @@ class ResponseTest extends TestCase 'string' => 'lorem ipsum', 'integer' => 123, 'boolean' => true, - 'hidden' => 'secret' + 'hidden' => 'secret', ]), 'hidden' => 'secret', ]), 'nested'); @@ -126,7 +126,6 @@ class ResponseTest extends TestCase $this->assertArrayNotHasKey('hidden', $output); $this->assertCount(1, $output['lists']['singles']); - $single = $output['single']; $this->assertArrayHasKey('string', $single); $this->assertArrayHasKey('integer', $single); diff --git a/tests/unit/Utopia/Single.php b/tests/unit/Utopia/Single.php index 3bd09ef6da..6e9fd3c9ec 100644 --- a/tests/unit/Utopia/Single.php +++ b/tests/unit/Utopia/Single.php @@ -12,7 +12,7 @@ class Single extends Model ->addRule('string', [ 'type' => self::TYPE_STRING, 'example' => '5e5ea5c16897e', - 'required' => true + 'required' => true, ]) ->addRule('integer', [ 'type' => self::TYPE_INTEGER, @@ -27,7 +27,7 @@ class Single extends Model ->addRule('required', [ 'type' => self::TYPE_STRING, 'default' => 'default', - 'required' => true + 'required' => true, ]); }