From fcc9e7a818f7ae7ac24a6e2f93d7350609d35e00 Mon Sep 17 00:00:00 2001 From: Rijk van Zanten Date: Tue, 24 Sep 2019 09:40:58 -0400 Subject: [PATCH] Release v2.6.0 (#1305) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Issue Fix #1180 (#1183) * Issue fix #1191 (#1192) * Issue fix #1196 (#1197) * Add 2fa authentication (#1031) * Parent + Nested validation changes (#1138) * Add migration schema for 2FA Secret user field * Add 2fa_secret field to FieldsSeeder * Create Missing 2FA Password Exception * Add googleauthenticator dependency * Add getter for User's 2FA secret * Check for otp param in login request, and login with it * Add enforce_2fa parameter to directus_settings * Create Utils endpoint and service method to generate 2fa secret * Add enforce_2fa field to roles * Add enforce_2fa field to FieldsSeeder * Change Missing2FAPasswordException error code to 111 * Change 2FA Library * Change 2fa_secret interface in FieldsSeeder * Created exception for invalid otp * Changed findUserWithCredentials to through an InvalidOTPException on otp check * Created new exception if 2fa is enforced but not enabled by user * Added function to check if 2fa is enforced for a user * Check in AuthenticationMiddleware whether 2fa is enforced and enabled for user * Add optional needs2FA field to auth token and on token refresh * Catch error if enforce_2fa column doesn't exist Fixes crash when has2FAEnforced is called on a DB that hasn't been migrated * Use relative positions for target path array to check user edit * Fix unset on payload_arr instead of payload * Change 2FA activation on login to use activate2FA endpoint * Update ItemsService.php * Issue Fix #1194 (#1195) * Issue Fix #1194 * Update comment * Valildation issue of O2M/M2O at insertion (#1198) * Fox #1201 (#1202) * Fix #1203 (#1204) * Update collections() method in types.php (#1184) There are cases when $type is not a string but an object that inherits from ObjectType. In that situation array_key_exists failing because it should get only integers or strings as a first parameter. So in order to avoid that the 'name' property of the object is used as a key. * Improve YouTube Embed Provider (#1210) Adds in detection and parsing for youtu.be shorthand URLs. * Add check for environment on bootstrap (#1215) * Fix #1186 [Create new error code for invalid login entity] (#1218) * Fix #1217 (Changing password over the CLI doesn't work) (#1220) * Feature/audio video upload (#1214) * added file meta data for audio/video * updates as per PR feedback * Fix #1207 [Permission denied issue when using translation interface] (#1221) * Fix for smtp send mail issue #1205 (#1223) * Fix for smtp send mail issue #1205 Missing additional config settings https://github.com/directus/api/issues/1205 * Update Schema.php * Fix 1232[Auth token is not refreshed] (#1233) * Change Authencation Error code to 114 from 109 (#1231) * Fix issue while update item. (#1224) * #1227 : Ignore all the alias fields except file interface (#1240) * Fix #1224 [Deletion of m2o/o2m field error for enabled cache] (#1241) * Fix 845 (#1244) * Change namespace for PHPUnit. * Removing old tests. * Fix #1238 [PDF support for Embedded URL] (#1245) * Fix #1238[PDF support for Embedded URL] * Add array support * Update comment * Update Files.php * Fix #1243[Dynamic charset for DB] (#1246) * Fix #1249[saveData: height is set to width] (#1251) * Fix #2017[Renaming `Public` role gives `unauthorized` error on API calls] (#1253) * Revert "Fix #2017[Renaming `Public` role gives `unauthorized` error on API calls] (#1253)" (#1254) This reverts commit 7fe9056f401f937d4863252f0e604c2deff8c3bf. * FIX/core/Directus/Files.php: return $height instead of $width (#1250) * Fix #1255 [Add support of batch Create/Update/Delete for user] (#1257) * Fix #1255 [Support batch create/update/delete for user] * Add exception * Fix directus/app#2017 (#1256) * Fix #2017[Renaming `Public` role gives `unauthorized` error on API calls] * src * Remove unwanted file from use * Fix #729 [Can't properly query nested fields on Files field] (#1260) * #1216 : Solved issue in O2M relationship of table itself (#1259) * Fix #1209 [M2M relation with directus_collections cant be saved] (#1261) * Fix #1209[M2M relation with directus_collections cant be saved] * Implement condition on update * Define variable * Fix #1209[M2M relation with directus_collections cant be saved] * 🙆🏻‍♂️ * Fix #1266 (#1267) * Fix Warning: Cannot use a scalar value as an array in /src/core/Directus/Config/StatusMapping.php on line 103 (#1268) * Fix Notice: Undefined variable: filterFields in src/core/Directus/Database/TableGateway/RelationalTableGateway.php on line 2125 (#1270) * Fix #1237 (#1265) * Project name fix (#1272) * Adds support for environment variables in CLI (#1276) * Cleans up some unused/deprecated files in the repository (#1277) * Fix #1248 [API cannot go into deeper on user data] (#1282) * Add proper exit codes for CLI (#1281) * Fix cache.enabled not respected in cache service (#1273) This fixes an issue where cache.enabled is false but caching is still working. * Add CLI cache:clear (#1274) * Fix #1284[Broken user related fields] (#1287) * Fix #1279 [wysiwyg-full - add image - Call to a member function isOneToMany() on null] (#1288) * fixed bug with incorrect height (#1293) * Bump version --- .gitignore | 3 + README.md | 2 +- benchmarks/api/Config/SourceBench.php | 37 - bin/directus | 1 + composer.json | 4 - package.json | 25 - phpbench.json | 20 - phpunit.php | 192 -- phpunit.xml.dist | 24 - src/core/Directus/Application/Application.php | 2 +- .../Application/CoreServicesProvider.php | 26 +- .../Middleware/AuthenticationMiddleware.php | 22 +- src/core/Directus/Authentication/Provider.php | 24 +- src/core/Directus/Config/Schema/Schema.php | 9 +- src/core/Directus/Config/StatusMapping.php | 16 +- src/core/Directus/Console/Cli.php | 20 +- src/core/Directus/Console/Common/Setting.php | 7 +- src/core/Directus/Console/Common/User.php | 12 +- .../Directus/Console/Modules/CacheModule.php | 60 + .../Console/Modules/InstallModule.php | 2 +- .../Directus/Database/Schema/DataTypes.php | 3 + .../TableGateway/BaseTableGateway.php | 37 +- .../TableGateway/RelationalTableGateway.php | 47 +- src/core/Directus/Filesystem/Files.php | 41 +- .../Directus/Services/AbstractService.php | 40 +- src/core/Directus/Services/AuthService.php | 2 +- .../Directus/Services/RelationsService.php | 21 + src/core/Directus/Services/RolesService.php | 13 +- src/core/Directus/Services/TablesService.php | 4 +- src/core/Directus/Services/UsersService.php | 117 ++ src/core/Directus/Util/DateTimeUtils.php | 8 +- .../Util/Installation/InstallerUtils.php | 70 +- src/endpoints/Roles.php | 2 + src/endpoints/Users.php | 64 +- src/helpers/all.php | 2 +- src/helpers/app.php | 2 +- tests/api/AclTest.php | 669 ------- tests/api/Application/ApplicationTest.php | 148 -- tests/api/Authentication/ProviderTest.php | 543 ------ tests/api/Collection/CollectionTest.php | 68 - tests/api/Config/ConfigTest.php | 60 - tests/api/Config/ContextTest.php | 131 -- tests/api/Config/GroupTest.php | 60 - tests/api/Config/SchemaTest.php | 141 -- tests/api/Config/ValueTest.php | 50 - tests/api/Config/sources/source.json | 13 - tests/api/Config/sources/source.php | 13 - tests/api/ContainerTest.php | 35 - tests/api/Database/ConnectionTest.php | 53 - tests/api/Database/Ddl/ColumnBooleanTest.php | 14 - .../Exception/DuplicateEntryExceptionTest.php | 14 - tests/api/Database/Query/BuilderTest.php | 114 -- .../RowGateway/BaseRowGatewayTest.php | 207 -- tests/api/Database/SchemaTest.php | 212 -- .../api/Database/Schemas/MySQLSchemaTest.php | 193 -- .../Schemas/Object/CollectionTest.php | 56 - .../Schemas/Object/FieldRelationshipTest.php | 30 - .../api/Database/Schemas/Object/FieldTest.php | 124 -- .../TableGateway/AclAwareTableGatewayTest.php | 27 - tests/api/Embed/EmbedManagerTest.php | 48 - tests/api/Embed/VimeoProviderTest.php | 51 - tests/api/Embed/YoutubeProviderTest.php | 51 - tests/api/Hook/EmitterTest.php | 137 -- tests/api/Session/SessionStorageTest.php | 89 - tests/api/Session/SessionTest.php | 24 - tests/api/Twig/TwigTest.php | 17 - tests/api/Util/ArrayUtilsTest.php | 333 ---- tests/api/Util/DateTimeUtilsTest.php | 76 - tests/api/Util/FormattingTest.php | 28 - tests/api/Util/GitUtilsTest.php | 45 - .../Util/Installation/InstallerUtilsTest.php | 88 - tests/api/Util/Installation/config/.gitkeep | 0 .../Util/Installation/mock/config.sample.php | 153 -- .../Util/Installation/mock/config.sample2.php | 153 -- tests/api/Util/JWTTest.php | 39 - tests/api/Util/SchemaUtilTest.php | 34 - tests/api/Util/StringUtilsTest.php | 157 -- tests/api/Validator/ValidatorTest.php | 64 - tests/api/functionsTest.php | 566 ------ tests/assets/image.jpeg | Bin 407 -> 0 bytes tests/assets/travis-ci-apache | 21 - tests/db.sql | 797 -------- tests/io/ActivityCommentTest.php | 475 ----- tests/io/ActivitySkipTest.php | 111 -- tests/io/ActivityTest.php | 275 --- tests/io/AuthenticationTest.php | 226 --- tests/io/CollectionPresetsTest.php | 169 -- tests/io/CollectionsTest.php | 322 ---- tests/io/FieldsTest.php | 430 ----- tests/io/FilesTest.php | 345 ---- tests/io/GeneralTest.php | 21 - tests/io/ItemsBatchTest.php | 322 ---- tests/io/ItemsTest.php | 1143 ----------- tests/io/PermissionsTest.php | 1713 ----------------- tests/io/RevisionsTest.php | 144 -- tests/io/RolesTest.php | 84 - tests/io/SettingsTest.php | 93 - tests/io/UsersTest.php | 171 -- tests/io/UtilsTest.php | 174 -- tests/utils/assert.php | 208 -- tests/utils/database.php | 224 --- tests/utils/helper.php | 58 - tests/utils/io_functions.php | 6 - tests/utils/request.php | 168 -- 104 files changed, 521 insertions(+), 13288 deletions(-) delete mode 100644 benchmarks/api/Config/SourceBench.php delete mode 100644 package.json delete mode 100644 phpbench.json delete mode 100644 phpunit.php delete mode 100644 phpunit.xml.dist create mode 100644 src/core/Directus/Console/Modules/CacheModule.php delete mode 100644 tests/api/AclTest.php delete mode 100644 tests/api/Application/ApplicationTest.php delete mode 100644 tests/api/Authentication/ProviderTest.php delete mode 100644 tests/api/Collection/CollectionTest.php delete mode 100644 tests/api/Config/ConfigTest.php delete mode 100644 tests/api/Config/ContextTest.php delete mode 100644 tests/api/Config/GroupTest.php delete mode 100644 tests/api/Config/SchemaTest.php delete mode 100644 tests/api/Config/ValueTest.php delete mode 100644 tests/api/Config/sources/source.json delete mode 100644 tests/api/Config/sources/source.php delete mode 100644 tests/api/ContainerTest.php delete mode 100644 tests/api/Database/ConnectionTest.php delete mode 100644 tests/api/Database/Ddl/ColumnBooleanTest.php delete mode 100644 tests/api/Database/Exception/DuplicateEntryExceptionTest.php delete mode 100644 tests/api/Database/Query/BuilderTest.php delete mode 100644 tests/api/Database/RowGateway/BaseRowGatewayTest.php delete mode 100644 tests/api/Database/SchemaTest.php delete mode 100644 tests/api/Database/Schemas/MySQLSchemaTest.php delete mode 100644 tests/api/Database/Schemas/Object/CollectionTest.php delete mode 100644 tests/api/Database/Schemas/Object/FieldRelationshipTest.php delete mode 100644 tests/api/Database/Schemas/Object/FieldTest.php delete mode 100644 tests/api/Database/TableGateway/AclAwareTableGatewayTest.php delete mode 100644 tests/api/Embed/EmbedManagerTest.php delete mode 100644 tests/api/Embed/VimeoProviderTest.php delete mode 100644 tests/api/Embed/YoutubeProviderTest.php delete mode 100644 tests/api/Hook/EmitterTest.php delete mode 100644 tests/api/Session/SessionStorageTest.php delete mode 100644 tests/api/Session/SessionTest.php delete mode 100644 tests/api/Twig/TwigTest.php delete mode 100644 tests/api/Util/ArrayUtilsTest.php delete mode 100644 tests/api/Util/DateTimeUtilsTest.php delete mode 100644 tests/api/Util/FormattingTest.php delete mode 100644 tests/api/Util/GitUtilsTest.php delete mode 100644 tests/api/Util/Installation/InstallerUtilsTest.php delete mode 100644 tests/api/Util/Installation/config/.gitkeep delete mode 100644 tests/api/Util/Installation/mock/config.sample.php delete mode 100644 tests/api/Util/Installation/mock/config.sample2.php delete mode 100644 tests/api/Util/JWTTest.php delete mode 100644 tests/api/Util/SchemaUtilTest.php delete mode 100644 tests/api/Util/StringUtilsTest.php delete mode 100644 tests/api/Validator/ValidatorTest.php delete mode 100644 tests/api/functionsTest.php delete mode 100644 tests/assets/image.jpeg delete mode 100644 tests/assets/travis-ci-apache delete mode 100644 tests/db.sql delete mode 100644 tests/io/ActivityCommentTest.php delete mode 100644 tests/io/ActivitySkipTest.php delete mode 100644 tests/io/ActivityTest.php delete mode 100644 tests/io/AuthenticationTest.php delete mode 100644 tests/io/CollectionPresetsTest.php delete mode 100644 tests/io/CollectionsTest.php delete mode 100644 tests/io/FieldsTest.php delete mode 100644 tests/io/FilesTest.php delete mode 100644 tests/io/GeneralTest.php delete mode 100644 tests/io/ItemsBatchTest.php delete mode 100644 tests/io/ItemsTest.php delete mode 100644 tests/io/PermissionsTest.php delete mode 100644 tests/io/RevisionsTest.php delete mode 100644 tests/io/RolesTest.php delete mode 100644 tests/io/SettingsTest.php delete mode 100644 tests/io/UsersTest.php delete mode 100644 tests/io/UtilsTest.php delete mode 100644 tests/utils/assert.php delete mode 100644 tests/utils/database.php delete mode 100644 tests/utils/helper.php delete mode 100644 tests/utils/io_functions.php delete mode 100644 tests/utils/request.php diff --git a/.gitignore b/.gitignore index 731ff47a3a..88407ef86f 100644 --- a/.gitignore +++ b/.gitignore @@ -67,3 +67,6 @@ deploy.* #See https://github.com/slimphp/Slim/issues/1829 #php -S localhost:8000 cliserver.php public/cliserver.php + +# Cache generated while filesystem adapter +/cache/* \ No newline at end of file diff --git a/README.md b/README.md index d85e274c09..1504f05856 100644 --- a/README.md +++ b/README.md @@ -150,7 +150,7 @@ We love pull-requests! To work on Directus you'll need to install it locally fro Project Lead -
+

Rijk van Zanten

App Lead diff --git a/benchmarks/api/Config/SourceBench.php b/benchmarks/api/Config/SourceBench.php deleted file mode 100644 index 89f6f3f741..0000000000 --- a/benchmarks/api/Config/SourceBench.php +++ /dev/null @@ -1,37 +0,0 @@ - 1 - ]; - Context::from_env(); - } - - /** - * @Revs(10000) - * @Iterations(3) - */ - public function benchFile() - { - Context::from_file(__DIR__ . "/../../../tests/api/Config/sources/source.php"); - } - - /** - * @Revs(10000) - * @Iterations(3) - */ - public function benchJson() - { - Context::from_json(__DIR__ . "/../../../tests/api/Config/sources/source.json"); - } -} diff --git a/bin/directus b/bin/directus index a4735c38ca..3fa390d9c3 100755 --- a/bin/directus +++ b/bin/directus @@ -10,6 +10,7 @@ try { $cli->run(); } catch (\Exception $e) { echo $e->getMessage() . PHP_EOL; + exit(1); } ?> diff --git a/composer.json b/composer.json index b49277a916..730fbe4d93 100644 --- a/composer.json +++ b/composer.json @@ -43,10 +43,6 @@ "char0n/ffmpeg-php": "^3.0.0", "pragmarx/google2fa": "^5.0" }, - "require-dev": { - "phpunit/phpunit": "^5.7.25", - "phpbench/phpbench": "@dev" - }, "suggest": { "paragonie/random_compat": "Generates cryptographically more secure pseudo-random bytes", "league/flysystem-aws-s3-v3": "Enables the usage of Amazon S3 adapter for storage", diff --git a/package.json b/package.json deleted file mode 100644 index aafa3e4c59..0000000000 --- a/package.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "name": "@directus/api", - "private": true, - "version": "2.5.0", - "description": "Directus API", - "main": "index.js", - "repository": "directus/api", - "keywords": [ - "directus", - "api" - ], - "scripts": { - "docs:dev": "vuepress dev docs", - "docs:build": "vuepress build docs" - }, - "author": "Welling Guzman ", - "license": "GPL-3.0", - "bugs": { - "url": "https://github.com/directus/api/issues" - }, - "homepage": "https://github.com/directus/api#readme", - "devDependencies": { - "vuepress": "^0.14.10" - } -} diff --git a/phpbench.json b/phpbench.json deleted file mode 100644 index 1c7d72e418..0000000000 --- a/phpbench.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "bootstrap": "vendor/autoload.php", - "path": "benchmarks", - "time_unit": "milliseconds", - "outputs": { - "directus": { - "extends": "html", - "file": "benchmark.html", - "title": "Directus Benchmarks" - } - }, - "reports": { - "directus": { - "extends": "aggregate" - } - }, - "php_config": { - "variables_order": "EGPCS" - } -} diff --git a/phpunit.php b/phpunit.php deleted file mode 100644 index 6ed8485f8c..0000000000 --- a/phpunit.php +++ /dev/null @@ -1,192 +0,0 @@ - 0) { - $builder->setMethods($methods); - } - - if (is_array($arguments) && count($arguments) > 0) { - $builder->setConstructorArgs($arguments); - } - - return $builder->disableOriginalConstructor() - ->disableOriginalClone() - ->disableArgumentCloning() - ->disallowMockingUnknownTypes() - ->getMock(); -} - -/** - * @param \PHPUnit\Framework\TestCase $testCase - * @param $attributes - mock attributes - * - * @return \Zend\Db\Adapter\Adapter - */ -function get_mock_adapter($testCase, $attributes = []) -{ - $mockDriver = get_mock_driver($testCase, $attributes); - - // setup mock adapter - $methods = ['getDriver', 'getConnection', 'getCurrentSchema', 'getPlatform']; - $mockAdapter = create_mock($testCase, 'Zend\Db\Adapter\Adapter', $methods, [$mockDriver]); - $mockAdapter->expects($testCase->any())->method('getDriver')->will($testCase->returnValue($mockDriver)); - $mockAdapter->expects($testCase->any())->method('getConnection')->will($testCase->returnValue(get_mock_adapter_connection($testCase))); - $mockAdapter->expects($testCase->any())->method('getCurrentSchema')->will($testCase->returnValue('directus')); - $mockAdapter->expects($testCase->any())->method('getPlatform')->will($testCase->returnValue(get_mock_platform($testCase))); - - return $mockAdapter; -} - -/** - * @param PHPUnit_Framework_TestCase $testCase - * @param array $attributes - * - * @return PHPUnit_Framework_MockObject_MockObject - */ -function get_mock_connection($testCase, $attributes = []) -{ - $mockDriver = get_mock_driver($testCase, $attributes); - - // setup mock connection adapter - $mockConnectionAdapter = create_mock($testCase, '\Directus\Database\Connection', null, [$mockDriver]); - - $platform = get_mock_platform($testCase, $attributes); - - $mockConnectionAdapter->expects($testCase->any())->method('getPlatform')->will($testCase->returnValue($platform)); - $mockConnectionAdapter->expects($testCase->any())->method('getDriver')->will($testCase->returnValue($mockDriver)); - - return $mockConnectionAdapter; -} - -function get_connection($test) -{ - -} - -function get_mock_platform($testCase, array $attributes = []) -{ - // Platform - $platformName = isset($attributes['platform_name']) ? $attributes['platform_name'] : 'Mysql'; - $platform = create_mock($testCase, \Zend\Db\Adapter\Platform\Mysql::class); - $platform->expects($testCase->any())->method('getIdentifierSeparator')->will($testCase->returnValue('.')); - $platform->expects($testCase->any())->method('getName')->will($testCase->returnValue($platformName)); - - return $platform; -} - -function get_mock_adapter_connection($testCase) -{ - $mockConnection = create_mock($testCase, 'Zend\Db\Adapter\Driver\ConnectionInterface'); - $mockConnection->expects($testCase->any())->method('getCurrentSchema')->will($testCase->returnValue('directus_schema')); - $mockConnection->expects($testCase->any())->method('connect'); - // $mockConnection->expects($testCase->any())->method('getDatabasePlatformName')->will($testCase->returnValue($platformName)); - // $mockConnection->expects($testCase->any())->method('getDriverName')->will($testCase->returnValue($platformName)); - - return $mockConnection; -} - -/** - * @param PHPUnit_Framework_TestCase $testCase - * @param array $attributes - * - * @return PHPUnit_Framework_MockObject_MockObject - */ -function get_mock_driver($testCase, $attributes = []) -{ - $resultCount = 0; - if (isset($attributes['result_count'])) { - $resultCount = (int)$attributes['result_count']; - } - - $resultData = null; - if (isset($attributes['result_data'])) { - $resultData = $attributes['result_data']; - } - - $platformName = 'Mysql'; - if (isset($attributes['platform_name'])) { - $platformName = $attributes['platform_name']; - } - - // mock the adapter, driver, and parts - $mockResult = create_mock($testCase, 'Zend\Db\Adapter\Driver\ResultInterface'); - $mockResult->expects($testCase->any())->method('count')->will($testCase->returnValue($resultCount)); - $mockResult->expects($testCase->any())->method('current')->will($testCase->returnValue($resultData)); - $mockStatement = create_mock($testCase, 'Zend\Db\Adapter\Driver\StatementInterface'); - $mockStatement->expects($testCase->any())->method('execute')->will($testCase->returnValue($mockResult)); - - // Connection - $mockAdapterConnection = get_mock_adapter_connection($testCase); - - $mockDriver = create_mock($testCase,'Zend\Db\Adapter\Driver\DriverInterface'); - $mockDriver->expects($testCase->any())->method('createStatement')->will($testCase->returnValue($mockStatement)); - $mockDriver->expects($testCase->any())->method('getConnection')->will($testCase->returnValue($mockAdapterConnection)); - $mockDriver->expects($testCase->any())->method('getDatabasePlatformName')->will($testCase->returnValue($platformName)); - - return $mockDriver; -} - -function get_mysql_schema($testCase, $attributes = []) -{ - $mockAdapter = get_mock_adapter($testCase, $attributes); - - return new \Directus\Database\Schemas\Sources\MySQLSchema($mockAdapter); -} - -/** - * @param \PHPUnit\Framework\TestCase $testCase - * @param array $methods - * - * @return mixed - */ -function get_mock_mysql_schema($testCase, $methods = []) -{ - $mockAdapter = get_mock_adapter($testCase); - $mockSchema = $testCase->getMockBuilder('\Directus\Database\Schemas\Sources\MySQLSchema') - ->setConstructorArgs([$mockAdapter]) - ->setMethods($methods) - ->getMock(); - - return $mockSchema; -} - -function get_array_session() -{ - $storage = new \Directus\Session\Storage\ArraySessionStorage(); - - return new \Directus\Session\Session($storage); -} - -/** - * @param string $url - * @param array $params - * - * @return string - */ -function add_query_params($url, array $params) -{ - $urlParts = parse_url($url); - if (is_array($urlParts) && isset($urlParts['query'])) { - $urlParts['query'] = array_merge($urlParts['query'], $params); - } - - return unparse_url($urlParts); -} diff --git a/phpunit.xml.dist b/phpunit.xml.dist deleted file mode 100644 index ce52f0ffbc..0000000000 --- a/phpunit.xml.dist +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - ./tests - - - - - ./src/core - - - diff --git a/src/core/Directus/Application/Application.php b/src/core/Directus/Application/Application.php index ea57c7454b..63d7c3bcf6 100644 --- a/src/core/Directus/Application/Application.php +++ b/src/core/Directus/Application/Application.php @@ -13,7 +13,7 @@ class Application extends App * * @var string */ - const DIRECTUS_VERSION = '2.5.0'; + const DIRECTUS_VERSION = '2.6.0'; /** * NOT USED diff --git a/src/core/Directus/Application/CoreServicesProvider.php b/src/core/Directus/Application/CoreServicesProvider.php index c55f3ea680..525f3b3285 100644 --- a/src/core/Directus/Application/CoreServicesProvider.php +++ b/src/core/Directus/Application/CoreServicesProvider.php @@ -69,6 +69,7 @@ use Monolog\Logger; use Slim\Views\Twig; use Zend\Db\TableGateway\TableGateway; +use Directus\Api\Routes\Roles; class CoreServicesProvider { @@ -213,15 +214,6 @@ protected function getEmitter() $emitter->addAction($action, $cacheTableTagInvalidator); } - $cacheEntityTagInvalidator = function ($tableName, $ids) use ($cachePool) { - foreach ($ids as $id) { - $cachePool->invalidateTags(['entity_' . $tableName . '_' . $id]); - } - }; - foreach (['item.delete:after', 'item.update:after'] as $action) { - $emitter->addAction($action, $cacheEntityTagInvalidator); - } - $emitter->addAction('item.update.directus_permissions:after', function ($data) use ($container, $cachePool) { $acl = $container->get('acl'); $dbConnection = $container->get('database'); @@ -328,7 +320,7 @@ protected function getEmitter() // Set the URL payload data $payload['data'] = ArrayUtils::get($dataInfo, 'data'); $payload['filename'] = ArrayUtils::get($dataInfo, 'filename'); - } else if(!is_object($fileData)) { + } else if (!is_object($fileData)) { $dataInfo = $files->getDataInfo($fileData); } @@ -686,6 +678,7 @@ protected function getEmitter() $emitter->addFilter('item.update:before', $onInsertOrUpdate); $preventUsePublicGroup = function (Payload $payload) use ($container) { $data = $payload->getData(); + if (!ArrayUtils::has($data, 'role')) { return $payload; } @@ -699,11 +692,7 @@ protected function getEmitter() return $payload; } - $zendDb = $container->get('database'); - $acl = $container->get('acl'); - $tableGateway = new BaseTableGateway(SchemaManager::COLLECTION_ROLES, $zendDb, $acl); - $row = $tableGateway->select(['id' => $roleId])->current(); - if (strtolower($row->name) === 'public') { + if ($roleId == ROLES::PUBLIC) { throw new ForbiddenException('Users cannot be added into the public group'); } @@ -918,6 +907,11 @@ protected function getCache() $poolConfig = ['adapter' => 'void']; } + $pool = new VoidCachePool(); + + if(!$config->get('cache.enabled')) + return $pool; + if (is_object($poolConfig) && $poolConfig instanceof PhpCachePool) { $pool = $poolConfig; } else { @@ -925,8 +919,6 @@ protected function getCache() throw new InvalidCacheAdapterException(); } - $pool = new VoidCachePool(); - $adapter = $poolConfig['adapter']; if ($adapter == 'apc') { diff --git a/src/core/Directus/Application/Http/Middleware/AuthenticationMiddleware.php b/src/core/Directus/Application/Http/Middleware/AuthenticationMiddleware.php index ecacbc5494..2a0788ba24 100644 --- a/src/core/Directus/Application/Http/Middleware/AuthenticationMiddleware.php +++ b/src/core/Directus/Application/Http/Middleware/AuthenticationMiddleware.php @@ -16,6 +16,7 @@ use Directus\Services\UsersService; use Zend\Db\Sql\Select; use Zend\Db\TableGateway\TableGateway; +use Directus\Api\Routes\Roles; class AuthenticationMiddleware extends AbstractMiddleware { @@ -38,7 +39,7 @@ public function __invoke(Request $request, Response $response, callable $next) $dbConnection = $this->container->get('database'); $permissionsTable = new DirectusPermissionsTableGateway($dbConnection, null); - $publicRoleId = $this->getPublicRoleId(); + $publicRoleId = ROLES::PUBLIC; $rolesIpWhitelist = []; $permissionsByCollection = []; @@ -154,25 +155,6 @@ protected function getAuthToken(Request $request) return get_request_authorization_token($request); } - /** - * Gets the public role id if exists - * - * @return int|null - */ - protected function getPublicRoleId() - { - $dbConnection = $this->container->get('database'); - $directusGroupsTableGateway = new TableGateway('directus_roles', $dbConnection); - $publicRole = $directusGroupsTableGateway->select(['name' => 'public'])->current(); - - $roleId = null; - if ($publicRole) { - $roleId = $publicRole['id']; - } - - return $roleId; - } - /** * Gets IP whitelist * diff --git a/src/core/Directus/Authentication/Provider.php b/src/core/Directus/Authentication/Provider.php index e72e2f0e84..6321ea285a 100644 --- a/src/core/Directus/Authentication/Provider.php +++ b/src/core/Directus/Authentication/Provider.php @@ -171,7 +171,7 @@ public function findUserWithCredentials($email, $password, $otp=null) // Verify that the user has an id (exists), it returns empty user object otherwise if (!password_verify($password, $user->get('password'))) { - + $this->recordActivityAndCheckLoginAttempt($user); throw new InvalidUserCredentialsException(); } @@ -207,7 +207,7 @@ public function recordActivityAndCheckLoginAttempt($user) $activityTableGateway->recordAction($userId, SchemaManager::COLLECTION_USERS, DirectusActivityTableGateway::ACTION_INVALID_CREDENTIALS); $loginAttemptsAllowed = get_directus_setting('login_attempts_allowed'); - + if(!empty($loginAttemptsAllowed)){ // We added 'Invalid credentials' entry before this condition so need to increase this counter with 1 @@ -217,11 +217,11 @@ public function recordActivityAndCheckLoginAttempt($user) if(!empty($invalidLoginAttempts)){ $lastInvalidCredentialsEntry = current($invalidLoginAttempts); $firstInvalidCredentialsEntry = end($invalidLoginAttempts); - + $lastLoginAttempt = $activityTableGateway->getLastLoginOrStatusUpdateAttempt($userId); - + if(!empty($lastLoginAttempt) && !in_array($lastLoginAttempt['id'], range($firstInvalidCredentialsEntry['id'], $lastInvalidCredentialsEntry['id'])) && count($invalidLoginAttempts) > $loginAttemptsAllowed){ - + $tableGateway = TableGatewayFactory::create(SchemaManager::COLLECTION_USERS, ['acl' => false]); $update = [ 'status' => DirectusUsersTableGateway::STATUS_SUSPENDED @@ -534,15 +534,7 @@ public function refreshToken($token, $needs2FA = false) $payload->exp = $this->getNewExpirationTime(); - $payload_arr = json_decode($payload); - - if ($needs2FA == true) { - $payload_arr['needs2FA'] = true; - } else { - unset($payload_arr['needs2FA']); - } - - $payload = json_encode($payload_arr); + $payload->needs2FA = $needs2FA; return JWTUtils::encode($payload, $this->getSecretKey(), $this->getTokenAlgorithm()); } @@ -613,11 +605,11 @@ public function hashPassword($password) /** * Authentication secret key * - * @param string|null $project + * @param string $project * * @return string */ - public function getSecretKey($project = null) + public function getSecretKey($project = '_') { if ($project) { $config = get_project_config($project); diff --git a/src/core/Directus/Config/Schema/Schema.php b/src/core/Directus/Config/Schema/Schema.php index f26566f75e..a1fd43ba13 100644 --- a/src/core/Directus/Config/Schema/Schema.php +++ b/src/core/Directus/Config/Schema/Schema.php @@ -36,7 +36,7 @@ public static function get() { new Value('username', Types::STRING, 'root'), new Value('password', Types::STRING, 'root'), new Value('engine', Types::STRING, 'InnoDB'), - new Value('chartset', Types::STRING, 'utf8mb4'), + new Value('charset', Types::STRING, 'utf8mb4'), new Value('socket', Types::STRING, ''), ]), new Group('cache', [ @@ -72,7 +72,12 @@ public static function get() { new Group('mail', [ new Group('default', [ new Value('transport', Types::STRING, 'sendmail'), - new Value('from', Types::STRING, 'admin@example.com') + new Value('from', Types::STRING, 'admin@example.com'), + new Value('host?', Types::STRING, ''), + new Value('port?', Types::STRING, ''), + new Value('username?', Types::STRING, ''), + new Value('password?', Types::STRING, ''), + new Value('encryption?', Types::STRING, '') ]), ]), new Group('cors', [ diff --git a/src/core/Directus/Config/StatusMapping.php b/src/core/Directus/Config/StatusMapping.php index fb697fa5c6..436bef773d 100644 --- a/src/core/Directus/Config/StatusMapping.php +++ b/src/core/Directus/Config/StatusMapping.php @@ -52,6 +52,15 @@ public function getByValue($value) } } + /** + * Returns a list of required status values + * + * @return array + */ + public function getRequiredStatusesValue() + { + return $this->getStatusesValue('required_fields', true); + } /** * Returns a list of soft delete status values * @@ -69,7 +78,7 @@ public function getSoftDeleteStatusesValue() */ public function getNonSoftDeleteStatusesValue() { - return $this->getStatusesValue('soft_delete', false); + return $this->getStatusesValue('soft_delete', [false,null]); } /** @@ -99,8 +108,11 @@ public function getAllStatusesValue() protected function getStatusesValue($type, $value) { $statuses = []; + if(!is_array($value)){ + $value = [$value]; + } foreach ($this->items as $status) { - if ($status->getAttribute($type) === $value) { + if (in_array($status->getAttribute($type),$value)) { $statuses[] = $status->getValue(); } } diff --git a/src/core/Directus/Console/Cli.php b/src/core/Directus/Console/Cli.php index 9663488af2..ec42f40292 100644 --- a/src/core/Directus/Console/Cli.php +++ b/src/core/Directus/Console/Cli.php @@ -75,37 +75,41 @@ private function cmd() echo 'Command are executed as follows:' . PHP_EOL; echo "\tdirectus : " . PHP_EOL . PHP_EOL; echo "Example: " . PHP_EOL . "\tdirectus install:help database" . PHP_EOL . PHP_EOL; - return; + exit(1); } if (!array_key_exists($module, $this->cmd_modules)) { echo PHP_EOL . PHP_EOL . 'Module ' . $module . ': does not exist!' . PHP_EOL . PHP_EOL; - return; + exit(1); } try { $options = $this->parseOptions($this->arguments, $this->cmd_modules[$module]->getOptions($command)); $this->cmd_modules[$module]->runCommand($command, $options, $this->extra); + return; } catch (WrongArgumentsException $e) { echo PHP_EOL . PHP_EOL . 'Module ' . $module . ' error: ' . $e->getMessage() . PHP_EOL . PHP_EOL; + exit(1); } catch (UnsupportedCommandException $e) { echo PHP_EOL . PHP_EOL . 'Module ' . $module . ' error: ' . $e->getMessage() . PHP_EOL . PHP_EOL; - } catch(\PDOException $e) { + exit(1); + } catch (\PDOException $e) { $this->handlePdoException($e); } } - private function handlePdoException(\PDOException $e) { + private function handlePdoException(\PDOException $e) + { $expected = "Duplicate entry 'directus_activity-id' for key 'idx_collection_field'"; - if((int) $e->errorInfo[0] == 23000 && $e->errorInfo[2] == $expected) { - echo "The Database for ".$this->directusPath." had already been deployed.\n"; + if ((int) $e->errorInfo[0] == 23000 && $e->errorInfo[2] == $expected) { + echo "The Database for " . $this->directusPath . " had already been deployed.\n"; echo "You may use option -f to enforce the overwriting of existing data."; } else { - throw($e); + throw ($e); } exit(1); } - + private function showHelp() { echo PHP_EOL . 'Directus CLI Modules: ' . PHP_EOL . PHP_EOL; diff --git a/src/core/Directus/Console/Common/Setting.php b/src/core/Directus/Console/Common/Setting.php index c93908b7a8..a1515d95dc 100644 --- a/src/core/Directus/Console/Common/Setting.php +++ b/src/core/Directus/Console/Common/Setting.php @@ -20,8 +20,8 @@ public function __construct($base_path, $projectName = null) } $this->directus_path = $base_path; - $configPath = InstallerUtils::createConfigPath($this->directus_path, $projectName); - $app = new Application($base_path, require $configPath); + + $app = InstallerUtils::createApp($base_path, $config); $this->db = $app->getContainer()->get('database'); $this->settingsTableGateway = new TableGateway('directus_settings', $this->db); @@ -45,7 +45,7 @@ public function isConfigured() return true; } return false; - } catch (PDOException $ex) { + } catch (\Exception $ex) { return false; } } @@ -138,5 +138,4 @@ public function setSetting($setting, $value) throw new SettingUpdateException('Could not change setting ' . $setting . ': ' . 'PDO Error: ' . $ex->getMessage()); } } - } diff --git a/src/core/Directus/Console/Common/User.php b/src/core/Directus/Console/Common/User.php index af10b02049..825c6010a3 100644 --- a/src/core/Directus/Console/Common/User.php +++ b/src/core/Directus/Console/Common/User.php @@ -22,10 +22,8 @@ public function __construct($base_path, $projectName = null) $base_path = \Directus\base_path(); } - $config = require InstallerUtils::createConfigPath($base_path, $projectName); - $this->directus_path = $base_path; - $this->app = new Application($base_path, $config); + $this->app = InstallerUtils::createApp($base_path, $projectName); $this->db = $this->app->getContainer()->get('database'); $this->usersTableGateway = new TableGateway('directus_users', $this->db); @@ -33,8 +31,8 @@ public function __construct($base_path, $projectName = null) /** * Check the existance of user in the system - * - * The function will check the user of given their e-mail address exist in + * + * The function will check the user of given their e-mail address exist in * the system or not. */ public function userExists($email) @@ -77,8 +75,8 @@ public function changePassword($email, $password) $auth = $this->app->getContainer()->get('auth'); $passwordValidation = get_directus_setting('password_policy'); - if(!empty($passwordValidation)){ - if(!preg_match($passwordValidation, $password, $match)){ + if (!empty($passwordValidation)) { + if (!preg_match($passwordValidation, $password, $match)) { throw new PasswordChangeException('Password is not valid.'); } } diff --git a/src/core/Directus/Console/Modules/CacheModule.php b/src/core/Directus/Console/Modules/CacheModule.php new file mode 100644 index 0000000000..19c1dcc914 --- /dev/null +++ b/src/core/Directus/Console/Modules/CacheModule.php @@ -0,0 +1,60 @@ + 'Clear all objects from cache.' + ]; + $this->help = $this->commands_help = $commands; + } + + public function cmdHelp($args, $extra) + { + echo PHP_EOL . 'Cache Command ' . $this->__module_name . ':' . $extra[0] . ' help' . PHP_EOL . PHP_EOL; + echo "\t" . $this->commands_help[$extra[0]] . PHP_EOL; + echo PHP_EOL . PHP_EOL; + } + + public function cmdClear($args, $extra) + { + $project = null; + + foreach ($args as $key => $value) { + switch ($key) { + case 'N': + $project = $value; + break; + } + } + + /** @var Application $app */ + $app = \Directus\create_app_with_project_name($this->getBasePath(), $project); + + /** @var AbstractCachePool $cache */ + $cache = $app->getContainer()->get('cache'); + $cache->clear(); + + echo "Successfully cleared cache!\n"; + } +} diff --git a/src/core/Directus/Console/Modules/InstallModule.php b/src/core/Directus/Console/Modules/InstallModule.php index f5890b6f9f..d1ef957bf3 100644 --- a/src/core/Directus/Console/Modules/InstallModule.php +++ b/src/core/Directus/Console/Modules/InstallModule.php @@ -204,7 +204,7 @@ public function cmdInstall($args, $extra) if ($hasEmail && !$user->userExists($data['user_email'])) { InstallerUtils::addDefaultUser($directus_path, $data, $projectName); } else { - //TODO: Verify this method is required or not! + //TODO: Verify this method is required or not! if ($hasEmail) { $user->changeEmail(1, $data['user_email']); } diff --git a/src/core/Directus/Database/Schema/DataTypes.php b/src/core/Directus/Database/Schema/DataTypes.php index ea774ac284..18825501a3 100644 --- a/src/core/Directus/Database/Schema/DataTypes.php +++ b/src/core/Directus/Database/Schema/DataTypes.php @@ -30,6 +30,7 @@ final class DataTypes const TYPE_DATETIME_UPDATED = 'datetime_updated'; const TYPE_USER_CREATED = 'user_created'; const TYPE_USER_UPDATED = 'user_updated'; + const TYPE_USER = 'user'; /** * Returns a list all data types @@ -65,6 +66,7 @@ public static function getAllTypes() static::TYPE_DATETIME_UPDATED, static::TYPE_USER_CREATED, static::TYPE_USER_UPDATED, + static::TYPE_USER, ]; } @@ -412,6 +414,7 @@ public static function getUsersType() return [ static::TYPE_USER_CREATED, static::TYPE_USER_UPDATED, + static::TYPE_USER, ]; } diff --git a/src/core/Directus/Database/TableGateway/BaseTableGateway.php b/src/core/Directus/Database/TableGateway/BaseTableGateway.php index e7a82680bb..df39de568e 100644 --- a/src/core/Directus/Database/TableGateway/BaseTableGateway.php +++ b/src/core/Directus/Database/TableGateway/BaseTableGateway.php @@ -674,7 +674,7 @@ protected function addVirtualColumn($tableName, $columnData) public function castFloatIfNumeric(&$value, $key) { if ($key != 'table_name') { - $value = is_numeric($value) && preg_match('/^-?(?:\d+|\d*\.\d+)$/', $value) ? (float)$value : $value; + $value = is_numeric($value) && preg_match('/^-?(?:\d+|\d*\.\d+)$/', $value) ? (float) $value : $value; } } @@ -878,6 +878,13 @@ protected function executeUpdate(Update $update) $this->runAfterUpdateHooks($updateTable, $updateData); } + //Invalidate individual cache + $config = static::$container->get('config'); + if ($config->get('cache.enabled')) { + $cachePool = static::$container->get('cache'); + $cachePool->invalidateTags(['entity_' . $updateTable . '_' . $result[$this->primaryKeyFieldName]]); + } + return $result; } @@ -898,7 +905,7 @@ protected function executeDelete(Delete $delete) $deleteState = $delete->getRawState(); $deleteTable = $this->getRawTableNameFromQueryStateTable($deleteState['table']); - + // Runs select PK with passed delete's $where before deleting, to use those for the even hook if ($pk = $this->primaryKeyFieldName) { $select = $this->sql->select(); @@ -917,7 +924,7 @@ protected function executeDelete(Delete $delete) $delete = $this->sql->delete(); $expression = new In($pk, $ids); $delete->where($expression); - + foreach ($ids as $id) { $deleteData = [$this->primaryKeyFieldName => $id]; $this->runHook('item.delete:before', [$deleteTable, $deleteData]); @@ -933,14 +940,24 @@ protected function executeDelete(Delete $delete) ); } + + //Invalidate individual cache + $config = static::$container->get('config'); + foreach ($ids as $id) { $deleteData = $deletedObject[$id]; $this->runHook('item.delete', [$deleteTable, $deleteData]); $this->runHook('item.delete:after', [$deleteTable, $deleteData]); $this->runHook('item.delete.' . $deleteTable, [$deleteData]); $this->runHook('item.delete.' . $deleteTable . ':after', [$deleteData]); + if ($config->get('cache.enabled')) { + $cachePool = static::$container->get('cache'); + $cachePool->invalidateTags(['entity_' . $deleteTable . '_' . $deleteData[$this->primaryKeyFieldName]]); + } } + + return $result; } } @@ -1238,12 +1255,12 @@ protected function enforceReadPermission(Builder $builder) * @throws \Exception */ public function enforceUpdatePermission(Update $update) - { + { $collectionObject = $this->getTableSchema(); $statusField = $collectionObject->getStatusField(); - $updateState = $update->getRawState(); + $updateState = $update->getRawState(); $updateData = $updateState['set']; - + //If a collection has status field then records are not actually deleting, they are soft deleting //Check delete permission for soft delete if ( @@ -1253,13 +1270,13 @@ public function enforceUpdatePermission(Update $update) ArrayUtils::get($updateData, $collectionObject->getStatusField()->getName()), $this->getStatusMapping()->getSoftDeleteStatusesValue() ) - ) { + ) { $delete = $this->sql->delete(); - $delete->where($updateState['where']); + $delete->where($updateState['where']); $this->enforceDeletePermission($delete); return; } - + if ($this->acl->canUpdateAll($this->table) && $this->acl->isAdmin()) { return; } @@ -1843,7 +1860,7 @@ protected function afterAddOrUpdate(array $record, $replace = false) */ protected function shouldNullSortedLast() { - return (bool)get_directus_setting('sort_null_last', true); + return (bool) get_directus_setting('sort_null_last', true); } /** diff --git a/src/core/Directus/Database/TableGateway/RelationalTableGateway.php b/src/core/Directus/Database/TableGateway/RelationalTableGateway.php index 354afb2c7f..837a38a0a1 100644 --- a/src/core/Directus/Database/TableGateway/RelationalTableGateway.php +++ b/src/core/Directus/Database/TableGateway/RelationalTableGateway.php @@ -174,7 +174,8 @@ public function manageRecordUpdate($tableName, $recordData, array $params = [], $column = $tableSchema->getField($key); // NOTE: Each interface or the API should handle the `alias` type - if ($column && $column->isOneToMany()) { + //Ignore all the alias fields except file interface > data + if ($column && (($column->isAlias() && $this->getTable() !== SchemaManager::COLLECTION_FILES)) || $column->isOneToMany()) { continue; } @@ -400,7 +401,8 @@ public function createRecord($recordData, array $params = []) $column = $tableSchema->getField($key); // NOTE: Each interface or the API should handle the `alias` type - if ($column && $column->isOneToMany()) { + //Ignore all the alias fields except file interface > data + if ($column && (($column->isAlias() && $this->getTable() !== SchemaManager::COLLECTION_FILES)) || ($column && $column->isOneToMany())) { continue; } @@ -1872,20 +1874,37 @@ protected function processQ(Builder $query, $search) $relatedTable = $relationship->getCollectionMany(); $relatedRightColumn = $relationship->getFieldMany(); $relatedTableColumns = SchemaService::getAllCollectionFields($relatedTable); - - $query->from($table); - // TODO: Test here it may be not setting the proper primary key name - // TODO: Only make this condition if it actually have conditions in the sub query - $query->orWhereRelational($this->primaryKeyFieldName, $relatedTable, null, $relatedRightColumn, function (Builder $query) use ($column, $relatedTable, $relatedTableColumns, $search) { - foreach ($relatedTableColumns as $column) { + + //Condition for table related to same table with O2M, to avoid right join of same tables + if($relatedTable == $table){ + $relatedQuery = new Builder($this->getAdapter()); + $relatedQuery->columns([$relatedRightColumn]); + $relatedQuery->from($relatedTable); + + foreach ($relatedTableColumns as $relatedColumn) { // NOTE: Only search numeric or string type columns - $isNumeric = $this->getSchemaManager()->getSource()->isNumericType($column->getType()); - $isString = $this->getSchemaManager()->getSource()->isStringType($column->getType()); - if (!$column->isAlias() && ($isNumeric || $isString)) { - $query->orWhereLike($column->getName(), $search, false); + $isNumeric = $this->getSchemaManager()->isFieldNumericType($relatedColumn); + $isString = $this->getSchemaManager()->isFieldStringType($relatedColumn); + if (!$relatedColumn->isAlias() && ($isNumeric || $isString)) { + $relatedQuery->orWhereLike($relatedColumn->getName(), $search, false); } } - }); + $query->orWhereIn($this->primaryKeyFieldName, $relatedQuery); + }else{ + $query->from($table); + // TODO: Test here it may be not setting the proper primary key name + // TODO: Only make this condition if it actually have conditions in the sub query + $query->orWhereRelational($this->primaryKeyFieldName, $relatedTable, null, $relatedRightColumn, function (Builder $query) use ($column, $relatedTable, $relatedTableColumns, $search) { + foreach ($relatedTableColumns as $relatedColumn) { + // NOTE: Only search numeric or string type columns + $isNumeric = $this->getSchemaManager()->isFieldNumericType($relatedColumn); + $isString = $this->getSchemaManager()->isFieldStringType($relatedColumn); + if (!$relatedColumn->isAlias() && ($isNumeric || $isString)) { + $query->orWhereLike($relatedColumn->getName(), $search, false); + } + } + }); + } } else if (!$column->isAlias()) { $query->orWhereLike($column->getName(), $search); } @@ -2056,6 +2075,8 @@ public function loadOneToManyRelationships($entries, $columns, array $params = [ continue; } + $filterFields = []; + // Only select the fields not on the currently authenticated user group's read field blacklist $relationalColumnName = $alias->getRelationship()->getFieldMany(); $tableGateway = new RelationalTableGateway($relatedTableName, $this->adapter, $this->acl); diff --git a/src/core/Directus/Filesystem/Files.php b/src/core/Directus/Filesystem/Files.php index 2f9dd5495e..d5ee351c0c 100644 --- a/src/core/Directus/Filesystem/Files.php +++ b/src/core/Directus/Filesystem/Files.php @@ -164,6 +164,22 @@ protected function getMimeTypeFromContentType($contentType) return $contentType; } + /** + * Check strpos in array + * + * @param string $haystack - The string to search in. + * @param array $needle - Array to search from string + * + * @return boolean + */ + function strposarray($haystack, $needle) { + if(!is_array($needle)) $needle = array($needle); + foreach($needle as $query) { + if(strpos($haystack, $query) !== false) return true; + } + return false; + } + /** * Get Image from URL * @@ -194,8 +210,8 @@ protected function getImageFromURL($url) } $contentType = $this->getMimeTypeFromContentType($contentType); - - if (strpos($contentType, 'image/') === false) { + $comparableContentType = ['image/', 'pdf']; + if (!$this->strposarray($contentType, $comparableContentType)) { return $info; } @@ -260,7 +276,7 @@ public function saveData($fileData, $fileName, $replace = false) // When file is uploaded via multipart form data then We will get object of Slim\Http\UploadFile // When file is uploaded via URL (Youtube, Vimeo, or image link) then we will get base64 encode string. $size = null; - + $title = $fileName; if (is_object($fileData)) { @@ -281,9 +297,11 @@ public function saveData($fileData, $fileName, $replace = false) $this->emitter->run('file.save:after', ['name' => $fileName, 'size' => $size]); #open local tmp file since s3 bucket is private - $handle = fopen($fileData->file, 'rb'); - $tmp = tempnam(sys_get_temp_dir(), $fileName); - file_put_contents($tmp, $handle); + if(isset($fileData->file)){ + $handle = fopen($fileData->file, 'rb'); + $tmp = tempnam(sys_get_temp_dir(), $fileName); + file_put_contents($tmp, $handle); + } unset($fileData); @@ -309,8 +327,9 @@ public function saveData($fileData, $fileName, $replace = false) $media = json_decode($output); $duration = $media->format->duration; } - - fclose($handle); + if(isset($handle)){ + fclose($handle); + } unset($tmpData); return [ @@ -324,7 +343,7 @@ public function saveData($fileData, $fileName, $replace = false) 'charset' => $fileData['charset'], 'filesize' => $fileData['size'], 'width' => isset($width) ? $width : $fileData['width'], - 'height' => isset($height) ? $width : $fileData['height'], + 'height' => isset($height) ? $height : $fileData['height'], 'storage' => $fileData['storage'], 'checksum' => $checksum, 'duration' => isset($duration) ? $duration : 0 @@ -379,7 +398,7 @@ public function getFileInfo($path, $outside = false) public function getFileInfoFromPath($path) { - + $mime = $this->filesystem->getAdapter()->getMimetype($path); $typeTokens = explode('/', $mime); @@ -703,7 +722,7 @@ private function get_string_between($string, $start, $end) } /** * Get a file size and type info from base64 data , URL ,multipart form data - * + * * @param string $data * * @return array file size and type diff --git a/src/core/Directus/Services/AbstractService.php b/src/core/Directus/Services/AbstractService.php index 305ba568ad..705533a6db 100644 --- a/src/core/Directus/Services/AbstractService.php +++ b/src/core/Directus/Services/AbstractService.php @@ -372,7 +372,7 @@ protected function getCRUDParams(array $params) protected function validatePayload($collectionName, $fields, array $payload, array $params, $skipRelatedCollectionField = '') { $columnsToValidate = []; - + // TODO: Validate empty request // If the user PATCH, POST or PUT with empty body, must throw an exception to avoid continue the execution // with the exception of POST, that can use the default value instead @@ -381,12 +381,15 @@ protected function validatePayload($collectionName, $fields, array $payload, arr $columnsToValidate = $fields; } - $this->validatePayloadFields($collectionName, $payload); - // TODO: Ideally this should be part of the validator constraints - // we need to accept options for the constraint builder - $this->validatePayloadWithFieldsValidation($collectionName, $payload); - - $this->validate($payload, $this->createConstraintFor($collectionName, $columnsToValidate, $skipRelatedCollectionField,$params)); + if($this->validationRequired($collectionName,$payload)){ + $this->validatePayloadFields($collectionName, $payload); + // TODO: Ideally this should be part of the validator constraints + // we need to accept options for the constraint builder + $this->validatePayloadWithFieldsValidation($collectionName, $payload); + + $this->validate($payload, $this->createConstraintFor($collectionName, $columnsToValidate, $skipRelatedCollectionField,$params)); + } + } /** @@ -407,6 +410,29 @@ protected function validatePayloadHasPrimaryKey($collectionName, array $payload) } } + /** + * Validate collection only if required for given status + * + * @param string $collectionName + * @param array $payload + * + * @throws UnprocessableEntityException + */ + protected function validationRequired($collectionName, array $payload) + { + $collection = $this->getSchemaManager()->getCollection($collectionName); + $statusField = $collection->getStatusField(); + if($statusField){ + $statusName = $statusField->getName(); + $statusMapping = $collection->getStatusMapping(); + $requiredStatus = $statusMapping->getRequiredStatusesValue(); + if(ArrayUtils::get($payload, $statusName) && $requiredStatus && !in_array(ArrayUtils::get($payload, $statusName),$requiredStatus)){ + return false; + } + } + return true; + } + /** * Throws an exception when the payload has one or more unknown fields * diff --git a/src/core/Directus/Services/AuthService.php b/src/core/Directus/Services/AuthService.php index aefb53b522..654ee6f8b0 100644 --- a/src/core/Directus/Services/AuthService.php +++ b/src/core/Directus/Services/AuthService.php @@ -24,7 +24,7 @@ class AuthService extends AbstractService { - const AUTH_VALIDATION_ERROR_CODE = 109; + const AUTH_VALIDATION_ERROR_CODE = 114; /** * Gets the user token using the authentication email/password combination diff --git a/src/core/Directus/Services/RelationsService.php b/src/core/Directus/Services/RelationsService.php index 37564ea73f..babbdb8b10 100644 --- a/src/core/Directus/Services/RelationsService.php +++ b/src/core/Directus/Services/RelationsService.php @@ -4,6 +4,7 @@ use Directus\Application\Container; use Directus\Database\Schema\SchemaManager; +use Directus\Database\Exception\ForbiddenSystemTableDirectAccessException; class RelationsService extends AbstractService { @@ -17,6 +18,16 @@ class RelationsService extends AbstractService */ protected $itemsService; + /** + * @var array + */ + public $restrictedTables = [ + SchemaManager::COLLECTION_ACTIVITY, + SchemaManager::COLLECTION_COLLECTIONS, + SchemaManager::COLLECTION_FIELDS, + SchemaManager::COLLECTION_RELATIONS + ]; + public function __construct(Container $container) { parent::__construct($container); @@ -25,8 +36,17 @@ public function __construct(Container $container) $this->itemsService = new ItemsService($this->container); } + public function throwErrorIfRestrictedTable($name) + { + if (in_array($name, $this->restrictedTables)) { + throw new ForbiddenSystemTableDirectAccessException($name); + } + } + + public function create(array $data, array $params = []) { + $this->throwErrorIfRestrictedTable($data['collection_one']); return $this->itemsService->createItem($this->collection, $data, $params); } @@ -42,6 +62,7 @@ public function findByIds($id, array $params = []) public function update($id, array $data, array $params = []) { + $this->throwErrorIfRestrictedTable($data['collection_one']); return $this->itemsService->update($this->collection, $id, $data, $params); } diff --git a/src/core/Directus/Services/RolesService.php b/src/core/Directus/Services/RolesService.php index 6bf4941826..61c2d824f1 100644 --- a/src/core/Directus/Services/RolesService.php +++ b/src/core/Directus/Services/RolesService.php @@ -8,6 +8,7 @@ use Directus\Database\TableGateway\DirectusRolesTableGateway; use Directus\Exception\UnauthorizedException; use Directus\Util\ArrayUtils; +use Directus\Api\Routes\Roles; class RolesService extends AbstractService { @@ -64,9 +65,7 @@ public function create(array $data, array $params = []) public function find($id, array $params = []) { $tableGateway = $this->getTableGateway(); - $params['id'] = $id; - - return $this->getItemsAndSetResponseCacheTags($tableGateway, $params); + return $this->getItemsByIdsAndSetResponseCacheTags($tableGateway, $id, $params); } /** @@ -151,13 +150,13 @@ public function delete($id, array $params = []) public function canDelete($id, $fetchNew = false) { if (!$this->lastGroup || $fetchNew === true) { - $group = $this->find($id); + $groupObject = $this->find($id); + $group = $groupObject ? $groupObject['data'] : null; } else { $group = $this->lastGroup; } - - // TODO: RowGateWay should parse values against their column type - return !(!$group || $group->id == 1 || strtolower($group->name) === 'public'); + + return !(!$group || $group['id'] == ROLES::ADMIN || $group['id'] == ROLES::PUBLIC); } /** diff --git a/src/core/Directus/Services/TablesService.php b/src/core/Directus/Services/TablesService.php index c6580334c8..266b86ba10 100644 --- a/src/core/Directus/Services/TablesService.php +++ b/src/core/Directus/Services/TablesService.php @@ -752,7 +752,7 @@ public function dropColumn($collectionName, $fieldName, array $params = []) } } - if ($columnObject->hasRelationship()) { + if ($columnObject->hasRelationship() && !in_array($columnObject->getType(),DataTypes::getUsersType())) { $this->removeColumnRelationship($columnObject,$params); } @@ -760,7 +760,7 @@ public function dropColumn($collectionName, $fieldName, array $params = []) /** * Remove O2M field if M2O interface deleted as O2M will only work if M2O exist */ - if($columnObject->isManyToOne()){ + if($columnObject->isManyToOne() && !in_array($columnObject->getType(),DataTypes::getUsersType())){ $this->removeRelatedColumnInfo($columnObject); } $this->removeColumnInfo($collectionName, $fieldName); diff --git a/src/core/Directus/Services/UsersService.php b/src/core/Directus/Services/UsersService.php index 84ca5cd5d7..c44caf5335 100644 --- a/src/core/Directus/Services/UsersService.php +++ b/src/core/Directus/Services/UsersService.php @@ -24,6 +24,7 @@ use Zend\Db\Sql\Delete; use Zend\Db\Sql\Select; use function Directus\get_directus_setting; +use Directus\Validator\Exception\InvalidRequestException; class UsersService extends AbstractService { @@ -440,4 +441,120 @@ public function activate2FA($id, $tfa_secret, $otp) return $this->update($id, ['2fa_secret' => $tfa_secret]); } + + /** + * @param $collection + * @param array $items + * @param array $params + * + * @return array + * + * @throws InvalidRequestException + */ + public function batchCreate(array $items, array $params = []) + { + if (!isset($items[0]) || !is_array($items[0])) { + throw new InvalidRequestException('batch create expect an array of items'); + } + + foreach ($items as $data) { + $this->enforceCreatePermissions($this->collection, $data, $params); + $this->validatePayload($this->collection, null, $data, $params); + } + + $allItems = []; + foreach ($items as $data) { + $item = $this->create($data, $params); + if (!is_null($item)) { + $allItems[] = $item['data']; + } + } + + if (!empty($allItems)) { + $allItems = ['data' => $allItems]; + } + + return $allItems; + } + + /** + * @param $collection + * @param array $items + * @param array $params + * + * @return array + * + * @throws InvalidRequestException + */ + public function batchUpdate(array $items, array $params = []) + { + if (!isset($items[0]) || !is_array($items[0])) { + throw new InvalidRequestException('batch update expect an array of items'); + } + + foreach ($items as $data) { + $this->enforceCreatePermissions($this->collection, $data, $params); + $this->validatePayload($this->collection, array_keys($data), $data, $params); + $this->validatePayloadHasPrimaryKey($this->collection, $data); + } + + $collectionObject = $this->getSchemaManager()->getCollection($this->collection); + $allItems = []; + foreach ($items as $data) { + $id = $data[$collectionObject->getPrimaryKeyName()]; + $item = $this->update($id, $data, $params); + + if (!is_null($item)) { + $allItems[] = $item['data']; + } + } + + if (!empty($allItems)) { + $allItems = ['data' => $allItems]; + } + + return $allItems; + } + + /** + * @param $collection + * @param array $ids + * @param array $payload + * @param array $params + * + * @return array + */ + public function batchUpdateWithIds(array $ids, array $payload, array $params = []) + { + $this->enforceUpdatePermissions($this->collection, $payload, $params); + $this->validatePayload($this->collection, array_keys($payload), $payload, $params); + + $allItems = []; + foreach ($ids as $id) { + $item = $this->update($id, $payload, $params); + if (!empty($item)) { + $allItems[] = $item['data']; + } + } + + if (!empty($allItems)) { + $allItems = ['data' => $allItems]; + } + + return $allItems; + } + + /** + * @param $collection + * @param array $ids + * @param array $params + * + * @throws ForbiddenException + */ + public function batchDeleteWithIds(array $ids, array $params = []) + { + foreach ($ids as $id) { + $this->delete($id, $params); + } + } } diff --git a/src/core/Directus/Util/DateTimeUtils.php b/src/core/Directus/Util/DateTimeUtils.php index dd80353684..08caf2fb39 100644 --- a/src/core/Directus/Util/DateTimeUtils.php +++ b/src/core/Directus/Util/DateTimeUtils.php @@ -83,7 +83,7 @@ public function __construct($time = null, $timezone = null) if ($timezone) { $timezone = $this->createTimeZone($timezone); } - + parent::__construct($time, $timezone); if ($time === null) { $this->setTimestamp(time()); @@ -109,7 +109,7 @@ public static function nowInUTC() public static function nowInTimezone() { - $config = get_project_config();; + $config = get_project_config(); return static::now($config->get('app.timezone')); } @@ -182,11 +182,11 @@ public static function createTimeZone($timezone) if ($timezone instanceof DateTimeZone) { return $timezone; } - + if ($timezone === null) { return new DateTimeZone(date_default_timezone_get()); } - + try { $timezone = new DateTimeZone($timezone); } catch (\Exception $e) { diff --git a/src/core/Directus/Util/Installation/InstallerUtils.php b/src/core/Directus/Util/Installation/InstallerUtils.php index d80be3e47f..66f2f98a59 100644 --- a/src/core/Directus/Util/Installation/InstallerUtils.php +++ b/src/core/Directus/Util/Installation/InstallerUtils.php @@ -3,6 +3,8 @@ namespace Directus\Util\Installation; use Directus\Application\Application; +use Directus\Config\Context; +use Directus\Config\Schema\Schema; use Directus\Database\Connection; use Directus\Database\Exception\ConnectionFailedException; use Directus\Database\Schema\SchemaManager; @@ -26,6 +28,33 @@ class InstallerUtils { + /** + * Check if environment is using files or environment variables + * + * @return boolean + */ + public static function isUsingFiles() + { + return getenv("DIRECTUS_USE_ENV") !== "1"; + } + + /** + * Undocumented function + * + * @param string $basePath + * @param string $projectName + * @return \Directus\Application\Application + */ + public static function createApp($basePath, $projectName) + { + if (static::isUsingFiles()) { + $config = require static::createConfigPath($basePath, $projectName); + } else { + $config = Schema::get()->value(Context::from_env()); + } + return new Application($basePath, $config); + } + /** * Create a config and configuration file into $path * @@ -224,8 +253,7 @@ public static function addDefaultSettings($basePath, array $data, $projectName = $basePath = rtrim($basePath, '/'); static::ensureConfigFileExists($basePath, $projectName); - $configPath = static::createConfigPath($basePath, $projectName); - $app = new Application($basePath, require $configPath); + $app = static::createApp($basePath, $projectName); $db = $app->getContainer()->get('database'); $defaultSettings = static::getDefaultSettings($data); @@ -247,8 +275,7 @@ public static function addDefaultSettings($basePath, array $data, $projectName = */ public static function addDefaultUser($basePath, array $data, $projectName = null) { - $configPath = static::createConfigPath($basePath, $projectName); - $app = new Application($basePath, require $configPath); + $app = static::createApp($basePath, $projectName); $db = $app->getContainer()->get('database'); $auth = $app->getContainer()->get('auth'); $tableGateway = new TableGateway('directus_users', $db); @@ -399,11 +426,11 @@ public static function ensureCanCreateConfig($path, array $data, $force = false) } /** - * Deletes the given config file - * - * @param string $path - * @param string|null $projectName - */ + * Deletes the given config file + * + * @param string $path + * @param string|null $projectName + */ public static function deleteConfigFile($path, $projectName = null) { $filePath = static::createConfigPath($path, $projectName); @@ -593,6 +620,10 @@ public static function getDefaultPermissions() */ public static function ensureConfigFileExists($basePath, $projectName = null) { + if (!self::isUsingFiles()) { + return; + } + $basePath = rtrim($basePath, '/'); $configName = static::getConfigName($projectName); $configPath = static::createConfigPath($basePath, $projectName); @@ -653,7 +684,11 @@ private static function getMigrationConfig($basePath, $projectName = null, $migr $configPath = static::createConfigPath($basePath, $projectName); $migrationPath = $basePath . '/migrations/' . $migrationName; - $apiConfig = ArrayUtils::get(require $configPath, 'database', []); + if (self::isUsingFiles()) { + $apiConfig = ArrayUtils::get(require $configPath, 'database', []); + } else { + $apiConfig = ArrayUtils::get(Schema::get()->value(Context::from_env()), 'database', []); + } // Rename directus configuration to phinx configuration ArrayUtils::rename($apiConfig, 'type', 'adapter'); @@ -724,12 +759,12 @@ private static function ensureDirectoryIsWritable($path) } /** - * Throws an exception when the given file path cannot be deleted - * - * @param string $path - * - * @throws InvalidPathException - */ + * Throws an exception when the given file path cannot be deleted + * + * @param string $path + * + * @throws InvalidPathException + */ private static function ensureFileCanBeDeleted($path) { if (!is_writable($path) || !is_file($path)) { @@ -847,8 +882,7 @@ private static function createSchemaManagerFromData(array $data, Connection $db */ private static function dropTables($basePath, $projectName) { - $configPath = static::createConfigPath($basePath, $projectName); - $app = new Application($basePath, require $configPath); + $app = static::createApp($basePath, $config); /** @var Connection $db */ $db = $app->getContainer()->get('database'); /** @var SchemaManager $schemaManager */ diff --git a/src/endpoints/Roles.php b/src/endpoints/Roles.php index cb1edbb4be..c7fc22eebf 100644 --- a/src/endpoints/Roles.php +++ b/src/endpoints/Roles.php @@ -11,6 +11,8 @@ class Roles extends Route { + const ADMIN = 1; + const PUBLIC = 2; /** * @param Application $app */ diff --git a/src/endpoints/Users.php b/src/endpoints/Users.php index 66bb249dde..fec442e805 100644 --- a/src/endpoints/Users.php +++ b/src/endpoints/Users.php @@ -65,9 +65,13 @@ public function all(Request $request, Response $response) public function create(Request $request, Response $response) { $this->validateRequestPayload($request); + $payload = $request->getParsedBody(); + if (isset($payload[0]) && is_array($payload[0])) { + return $this->batch($request, $response); + } $service = new UsersService($this->container); $responseData = $service->create( - $request->getParsedBody(), + $payload, $request->getQueryParams() ); @@ -120,9 +124,21 @@ public function update(Request $request, Response $response) { $this->validateRequestPayload($request); $service = new UsersService($this->container); + + $payload = $request->getParsedBody(); + if (isset($payload[0]) && is_array($payload[0])) { + return $this->batch($request, $response); + } + + $id = $request->getAttribute('id'); + + if (strpos($id, ',') !== false) { + return $this->batch($request, $response); + } + $responseData = $service->update( - $request->getAttribute('id'), - $request->getParsedBody(), + $id, + $payload, $request->getQueryParams() ); @@ -138,14 +154,54 @@ public function update(Request $request, Response $response) public function delete(Request $request, Response $response) { $service = new UsersService($this->container); + + $id = $request->getAttribute('id'); + if (strpos($id, ',') !== false) { + return $this->batch($request, $response); + } + $service->delete( - $request->getAttribute('id'), + $id, $request->getQueryParams() ); return $this->responseWithData($request, $response, []); } + /** + * @param Request $request + * @param Response $response + * + * @return Response + * + * @throws \Exception + */ + protected function batch(Request $request, Response $response) + { + $service = new UsersService($this->container); + + $payload = $request->getParsedBody(); + $params = $request->getQueryParams(); + + $responseData = null; + if ($request->isPost()) { + $responseData = $service->batchCreate($payload, $params); + } else if ($request->isPatch()) { + if ($request->getAttribute('id')) { + $ids = explode(',', $request->getAttribute('id')); + $responseData = $service->batchUpdateWithIds( $ids, $payload, $params); + } else { + $responseData = $service->batchUpdate($payload, $params); + } + } else if ($request->isDelete()) { + $ids = explode(',', $request->getAttribute('id')); + $service->batchDeleteWithIds($ids, $params); + } + + return $this->responseWithData($request, $response, $responseData); + } + + /** * @param Request $request * @param Response $response diff --git a/src/helpers/all.php b/src/helpers/all.php index 08846638b0..a8b222822c 100644 --- a/src/helpers/all.php +++ b/src/helpers/all.php @@ -1519,7 +1519,7 @@ function get_unflat_columns($columns) $child = get_unflat_columns($parts[1]); if (isset($names[$parts[0]][key($child)])) { - $childValue = array_merge($names[$parts[0]][key($child)], current($child)); + $childValue = array_merge_recursive($names[$parts[0]][key($child)], current($child)); } else { $childValue = current($child); } diff --git a/src/helpers/app.php b/src/helpers/app.php index dea3dc3de2..82d3eebfe3 100644 --- a/src/helpers/app.php +++ b/src/helpers/app.php @@ -67,7 +67,7 @@ function create_app_with_project_name($basePath, $name, array $values = []) * * @throws Exception */ - function get_project_config($name = null, $basePath = null) + function get_project_config($name = '_', $basePath = null) { static $configs = []; diff --git a/tests/api/AclTest.php b/tests/api/AclTest.php deleted file mode 100644 index f59dd2e7b1..0000000000 --- a/tests/api/AclTest.php +++ /dev/null @@ -1,669 +0,0 @@ -acl = new Acl(); - $this->permissions = [ - 'directus_files' => [ - [ - 'id' => 1, - 'collection' => 'directus_files', - 'group' => 2, - 'status' => null, - 'read_field_blacklist' => ['date_uploaded'], - 'write_field_blacklist' => ['type'], - 'read' => 3, - 'create' => 1, - 'update' => 3, - 'delete' => 3, - 'explain' => 0 - ] - ], - 'products' => [ - [ - 'id' => 2, - 'collection' => 'products', - 'group' => 2, - 'read_field_blacklist' => null, - 'write_field_blacklist' => null, - 'status' => null, - 'create' => 1, - 'read' => 1, - 'update' => 1, - 'delete' => 0 - ], - [ - 'id' => 20, - 'collection' => 'products', - 'group' => 2, - 'read_field_blacklist' => ['read'], - 'write_field_blacklist' => ['write'], - 'status' => 1, - 'create' => 0, - 'read' => 2, - 'update' => 0, - 'delete' => 0, - 'explain' => 1 - ], - [ - 'id' => 21, - 'collection' => 'products', - 'group' => 2, - 'read_field_blacklist' => ['read_draft'], - 'write_field_blacklist' => ['write_draft'], - 'status' => 2, - 'create' => 1, - 'read' => 2, - 'update' => 0, - 'delete' => 0 - ] - ], - 'test_table' => [ - [ - 'id' => 2, - 'collection' => 'test_table', - 'group' => 2, - 'read_field_blacklist' => null, - 'write_field_blacklist' => null, - 'status' => null, - 'create' => 1, - 'read' => 1, - 'update' => 1, - 'delete' => 0 - ] - ], - 'forbid' => [ - [ - 'id' => 3, - 'collection' => 'test_table', - 'group' => 2, - 'read_field_blacklist' => null, - 'write_field_blacklist' => null, - 'status' => 0, - 'create' => 0, - 'read' => 0, - 'update' => 0, - 'delete' => 0, - 'explain' => 1 - ] - ], - 'directus_collection_presets' => [ - [ - 'create' => 1, - 'read' => 1, - 'update' => 1 - ] - ], - 'odd_collection' => [[]] - ]; - - $this->acl->setPermissions($this->permissions); - $this->acl->setUserId(2); - $this->acl->setGroupId(2); - } - - public function testPublic() - { - $acl = new Acl(); - - $acl->setPublic(true); - $this->assertTrue($acl->isPublic()); - - $acl->setPublic(false); - $this->assertFalse($acl->isPublic()); - - $acl->setPublic(1); - $this->assertTrue($acl->isPublic()); - - $acl->setPublic(0); - $this->assertFalse($acl->isPublic()); - } - - public function testIsAdmin() - { - $acl = new Acl(); - - $acl->setGroupId(1); - $this->assertTrue($acl->isAdmin()); - - $acl->setGroupId(2); - $this->assertFalse($acl->isAdmin()); - } - - public function testUser() - { - $this->assertSame(2, $this->acl->getUserId()); - $this->assertSame(2, $this->acl->getGroupId()); - - $acl = new Acl(); - - $this->assertNull($acl->getUserId()); - $this->assertNull($acl->getGroupId()); - - $acl->setUserId(2); - $acl->setGroupId(1); - $this->assertSame(2, $acl->getUserId()); - $this->assertSame(1, $acl->getGroupId()); - } - - public function testSetCollectionPermissions() - { - $acl = new Acl(); - $acl->setCollectionPermission('test', [ - $acl::ACTION_UPDATE => 1 - ]); - - $this->assertTrue($acl->canUpdateMine('test')); - $this->assertFalse($acl->canUpdateFromRole('test')); - $this->assertFalse($acl->canUpdateAll('test')); - } - - public function testSettingPermissions() - { - $acl = new Acl($this->permissions); - $permissions = $acl->getPermissions(); - - $this->assertTrue(count($acl->getPermissions()) > 0); - $this->assertEquals(count($permissions), count($this->permissions)); - $this->assertNotEmpty($acl->getCollectionPermissions('directus_files')); - $this->assertEmpty($acl->getCollectionPermissions('directus_users')); - - $collectionPermission = $acl->getCollectionPermissions('odd_collection'); - $this->assertEmpty($collectionPermission); - } - - /** - * @expectedException \Directus\Permissions\Exception\ForbiddenFieldReadException - */ - public function testEnforceReadBlacklist() - { - $this->acl->enforceReadField('directus_files', ['name', 'type', 'date_uploaded']); - } - - /** - * @expectedException \Directus\Permissions\Exception\ForbiddenFieldWriteException - */ - public function testEnforceWriteBlacklist() - { - $this->acl->enforceWriteField('directus_files', ['name', 'type', 'date_uploaded']); - } - - /** - * @expectedException \Directus\Permissions\Exception\ForbiddenFieldReadException - */ - public function testEnforceReadBlacklistString() - { - $this->acl->enforceReadField('directus_files', 'date_uploaded'); - } - - /** - * @expectedException \Directus\Permissions\Exception\ForbiddenFieldWriteException - */ - public function testEnforceWriteBlacklistString() - { - $this->acl->enforceWriteField('directus_files', 'type'); - } - - public function testEnforceBlacklist() - { - // Nothing happens here - $this->acl->enforceReadField('directus_files', ['name', 'title', 'size']); - $this->acl->enforceWriteField('directus_files', ['name', 'title', 'size']); - } - - public function testUnknownBlacklistType() - { - $fields = $this->acl->getFieldBlacklist('unknown', 'directus_files'); - $this->assertInternalType('array', $fields); - $this->assertEmpty($fields); - } - - public function testGetPrivilegeListPermissions() - { - $permissions = $this->acl->getCollectionPermissions('directus_files'); - $this->assertInternalType('array', $permissions); - $this->assertNotEmpty($permissions); - - // table that does not exists in the privilege list - $permissions = $this->acl->getCollectionPermissions('directus_users'); - $this->assertInternalType('array', $permissions); - $this->assertEmpty($permissions); - } - - public function testHasPermission() - { - $this->assertTrue($this->acl->canUpdateAll('directus_files')); - - // Test table: all - $this->assertTrue($this->acl->canCreate('test_table')); - - $this->assertTrue($this->acl->canReadMine('test_table')); - $this->assertFalse($this->acl->canReadFromRole('test_table')); - $this->assertFalse($this->acl->canReadAll('test_table')); - - $this->assertTrue($this->acl->canUpdateMine('test_table')); - $this->assertFalse($this->acl->canUpdateFromRole('test_table')); - $this->assertFalse($this->acl->canUpdateAll('test_table')); - - $this->assertFalse($this->acl->canDeleteMine('test_table')); - $this->assertFalse($this->acl->canDeleteFromRole('test_table')); - $this->assertFalse($this->acl->canDeleteAll('test_table')); - - // Test table: status 1 - $this->assertFalse($this->acl->canCreate('products', 1)); - - $this->assertTrue($this->acl->canReadMine('products', 1)); - $this->assertTrue($this->acl->canReadFromRole('products', 1)); - $this->assertFalse($this->acl->canReadAll('products', 1)); - - $this->assertFalse($this->acl->canUpdateMine('products', 1)); - $this->assertFalse($this->acl->canUpdateFromRole('products', 1)); - $this->assertFalse($this->acl->canUpdateAll('products', 1)); - - $this->assertFalse($this->acl->canDeleteMine('products', 1)); - $this->assertFalse($this->acl->canDeleteFromRole('products', 1)); - $this->assertFalse($this->acl->canDeleteAll('products', 1)); - } - - public function testCanDo() - { - $this->assertFalse($this->acl->canCreate('forbid')); - $this->assertTrue($this->acl->canCreate('directus_files')); - - $this->assertFalse($this->acl->canRead('forbid')); - $this->assertTrue($this->acl->canRead('directus_files')); - - $this->assertFalse($this->acl->canUpdate('forbid')); - $this->assertTrue($this->acl->canUpdate('directus_files')); - - $this->assertFalse($this->acl->canDelete('forbid')); - $this->assertTrue($this->acl->canDelete('directus_files')); - - $this->assertFalse($this->acl->canAlter('forbid')); - $this->assertFalse($this->acl->canAlter('directus_files')); - - $acl = new Acl(); - $acl->setGroupId(1); - $this->assertTrue($acl->canAlter('directus_files')); - $this->assertTrue($acl->canCreate('forbid')); - } - - public function testRequireMessageActivity() - { - $this->assertFalse($this->acl->requireExplain('directus_files')); - $this->assertFalse($this->acl->requireExplain('test_table')); - $this->assertTrue($this->acl->requireExplain('products', 1)); - $this->assertFalse($this->acl->requireExplain('products', 2)); - $this->assertTrue($this->acl->requireExplain('forbid', 0)); - } - - /** - * @expectedException \Directus\Permissions\Exception\ForbiddenCollectionAlterException - */ - public function testEnforceCanAlterFails() - { - $this->acl->enforceAlter('directus_files'); - } - - public function testEnforceCanAlterPassed() - { - $acl = new Acl(); - $acl->setGroupId(1); - $acl->enforceAlter('directus_files'); - } - - /** - * @expectedException \Directus\Permissions\Exception\ForbiddenCollectionCreateException - */ - public function testEnforceCanCreateFails() - { - $this->acl->enforceCreate('forbid'); - } - - public function testEnforceCanCreatePassed() - { - $this->acl->enforceCreate('directus_files'); - } - - public function testEnforceCanReadPasses() - { - $this->acl->enforceReadMine('directus_files'); - $this->acl->enforceReadFromRole('directus_files'); - $this->acl->enforceReadAll('directus_files'); - $this->acl->enforceRead('directus_files'); - } - - public function testEnforceCanUpdatePasses() - { - $this->acl->enforceUpdateMine('directus_files'); - $this->acl->enforceUpdateFromRole('directus_files'); - $this->acl->enforceUpdateAll('directus_files'); - $this->acl->enforceUpdate('directus_files'); - } - - public function testEnforceCanDeletePasses() - { - $this->acl->enforceDeleteMine('directus_files'); - $this->acl->enforceDeleteFromRole('directus_files'); - $this->acl->enforceDeleteAll('directus_files'); - $this->acl->enforceDelete('directus_files'); - } - - /** - * @expectedException \Directus\Permissions\Exception\ForbiddenCollectionReadException - */ - public function testEnforceCanReadMineFails() - { - $this->acl->enforceReadMine('forbid'); - } - - /** - * @expectedException \Directus\Permissions\Exception\ForbiddenCollectionReadException - */ - public function testEnforceCanReadFromGroupFails() - { - $this->acl->enforceReadFromRole('forbid'); - } - - /** - * @expectedException \Directus\Permissions\Exception\ForbiddenCollectionReadException - */ - public function testEnforceCanReadAllFails() - { - $this->acl->enforceReadAll('forbid'); - } - - /** - * @expectedException \Directus\Permissions\Exception\ForbiddenCollectionReadException - */ - public function testEnforceCanReadFails() - { - $this->acl->enforceRead('forbid'); - } - - /** - * @expectedException \Directus\Permissions\Exception\ForbiddenCollectionUpdateException - */ - public function testEnforceCanUpdateFails() - { - $this->acl->enforceUpdate('forbid'); - } - - /** - * @expectedException \Directus\Permissions\Exception\ForbiddenCollectionUpdateException - */ - public function testEnforceCanUpdateMineFails() - { - $this->acl->enforceUpdateMine('forbid'); - } - - /** - * @expectedException \Directus\Permissions\Exception\ForbiddenCollectionUpdateException - */ - public function testEnforceCanUpdateFromGroupFails() - { - $this->acl->enforceUpdateFromRole('forbid'); - } - - /** - * @expectedException \Directus\Permissions\Exception\ForbiddenCollectionUpdateException - */ - public function testEnforceCanUpdateAllFails() - { - $this->acl->enforceUpdateAll('forbid'); - } - - /** - * @expectedException \Directus\Permissions\Exception\ForbiddenCollectionDeleteException - */ - public function testEnforceCanDeleteFails() - { - $this->acl->enforceDelete('forbid'); - } - - /** - * @expectedException \Directus\Permissions\Exception\ForbiddenCollectionDeleteException - */ - public function testEnforceCanDeleteMineFails() - { - $this->acl->enforceDeleteMine('forbid'); - } - - /** - * @expectedException \Directus\Permissions\Exception\ForbiddenCollectionDeleteException - */ - public function testEnforceCanDeleteFromGroupFails() - { - $this->acl->enforceDeleteFromRole('forbid'); - } - - /** - * @expectedException \Directus\Permissions\Exception\ForbiddenCollectionDeleteException - */ - public function testEnforceCanDeleteAllFails() - { - $this->acl->enforceDeleteAll('forbid'); - } - - public function testStatusPermission() - { - $acl = new Acl(); - $acl->setUserId(2); - $acl->setGroupId(2); - - $acl->setCollectionPermissions('articles', [ - [ - 'id' => 1, - 'collection' => 'articles', - 'group' => 2, - 'read_field_blacklist' => null, - 'write_field_blacklist' => null, - 'status' => null, - 'create' => 1, - 'read' => 3, - 'update' => 3, - 'delete' => 3, - 'explain' => 1 - ], - [ - 'id' => 2, - 'collection' => 'articles', - 'group' => 2, - 'read_field_blacklist' => ['read'], - 'write_field_blacklist' => ['write'], - 'status' => 1, - 'create' => 0, - 'read' => 3, - 'update' => 0, - 'delete' => 0 - ], - [ - 'id' => 3, - 'collection' => 'articles', - 'group' => 2, - 'read_field_blacklist' => ['read_draft'], - 'write_field_blacklist' => ['write_draft'], - 'status' => 2, - 'create' => 1, - 'read' => 2, - 'update' => 1, - 'delete' => 1 - ] - ]); - - $this->assertFalse($acl->canCreate('articles', 1)); - $this->assertFalse($acl->canCreate('articles')); - $this->assertFalse($acl->canCreate('articles', '*')); - $this->assertFalse($acl->canCreate('articles', null)); - - $this->assertTrue($acl->canReadAll('articles', 1)); - $this->assertTrue($acl->canReadFromRole('articles', 1)); - $this->assertTrue($acl->canReadMine('articles', 1)); - $this->assertTrue($acl->canRead('articles', 1)); - - $this->assertFalse($acl->canUpdateAll('articles', 1)); - $this->assertFalse($acl->canUpdateFromRole('articles', 1)); - $this->assertFalse($acl->canUpdateMine('articles', 1)); - $this->assertFalse($acl->canUpdate('articles', 1)); - - $this->assertFalse($acl->canDeleteAll('articles', 1)); - $this->assertFalse($acl->canDeleteFromRole('articles', 1)); - $this->assertFalse($acl->canDeleteMine('articles', 1)); - $this->assertFalse($acl->canDelete('articles', 1)); - } - - public function testReadOnceAdmin() - { - $acl = new Acl(); - - $acl->setCollectionPermission('test', [ - 'collection' => 'test', - 'read' => 1 - ]); - - $acl->enforceReadOnce('test'); - } - - public function testReadOnceGlobal() - { - $acl = new Acl(); - $acl->setGroupId(1); - $acl->enforceReadOnce('test'); - } - - public function testReadOnce() - { - $acl = new Acl(); - - $acl->setCollectionPermission('test', [ - 'collection' => 'test', - 'status' => 2, - 'read' => 1 - ]); - - $acl->enforceReadOnce('test'); - } - - /** - * @expectedException \Directus\Permissions\Exception\ForbiddenCollectionReadException - */ - public function testReadOnceFails() - { - $acl = new Acl(); - - $acl->setCollectionPermission('test', [ - 'collection' => 'test', - 'status' => 2 - ]); - - $acl->enforceReadOnce('test'); - } - - public function testReadStatusPermission() - { - $acl = new Acl(); - $this->assertFalse($acl->getCollectionStatusesReadPermission('test')); - - $acl->setCollectionPermission('test', [ - 'status' => null, - 'collection' => 'test' - ]); - - $this->assertFalse($acl->getCollectionStatusesReadPermission('test')); - - // ---------------------------------------------------------------------------- - $acl = new Acl(); - $acl->setCollectionPermission('test', [ - 'status' => null, - 'collection' => 'test', - 'read' => 1 - ]); - - $this->assertNull($acl->getCollectionStatusesReadPermission('test')); - - // ---------------------------------------------------------------------------- - $acl = new Acl(); - $acl->setCollectionPermission('test', [ - 'status' => 1, - 'collection' => 'test', - 'read' => 1 - ]); - - $statuses = $acl->getCollectionStatusesReadPermission('test'); - $this->assertInternalType('array', $statuses); - $this->assertCount(1, $statuses); - $this->assertTrue(in_array(1, $statuses)); - - // ---------------------------------------------------------------------------- - $acl = new Acl(); - $acl->setCollectionPermission('test', [ - 'status' => 1, - 'collection' => 'test', - 'read' => 1 - ]); - - $acl->setCollectionPermission('test', [ - 'status' => 2, - 'collection' => 'test', - 'read' => 1 - ]); - - $statuses = $acl->getCollectionStatusesReadPermission('test'); - $this->assertInternalType('array', $statuses); - $this->assertCount(2, $statuses); - $this->assertTrue(in_array(1, $statuses)); - $this->assertTrue(in_array(2, $statuses)); - - // ---------------------------------------------------------------------------- - $acl = new Acl(); - $acl->setCollectionPermission('test', [ - 'status' => 1, - 'collection' => 'test', - 'read' => 1 - ]); - - $acl->setCollectionPermission('test', [ - 'status' => 2, - 'collection' => 'test', - 'read' => 1 - ]); - - $acl->setCollectionPermission('test', [ - 'status' => 3, - 'collection' => 'test', - 'read' => 0 - ]); - - $statuses = $acl->getCollectionStatusesReadPermission('test'); - $this->assertInternalType('array', $statuses); - $this->assertCount(2, $statuses); - $this->assertTrue(in_array(1, $statuses)); - $this->assertTrue(in_array(2, $statuses)); - - // ---------------------------------------------------------------------------- - $acl = new Acl(); - $acl->setGroupId(1); - $this->assertNull($acl->getCollectionStatusesReadPermission('test')); - } - - public function testCollectionStatuses() - { - $this->assertNull($this->acl->getCollectionStatuses('directus_files')); - - $productStatuses = $this->acl->getCollectionStatuses('products'); - $this->assertInternalType('array', $productStatuses); - $this->assertCount(2, $productStatuses); - $this->assertTrue(in_array(1, $productStatuses)); - $this->assertTrue(in_array(2, $productStatuses)); - } -} diff --git a/tests/api/Application/ApplicationTest.php b/tests/api/Application/ApplicationTest.php deleted file mode 100644 index 21121815f6..0000000000 --- a/tests/api/Application/ApplicationTest.php +++ /dev/null @@ -1,148 +0,0 @@ -booted = true; -// } -// -// public function register(\Directus\Application\Application $app) -// { -// $this->app = $app; -// } -// -// public function getApp() -// { -// return $this->app; -// } -// -// public function isBooted() -// { -// return $this->booted; -// } -// -// public function setBooted($booted) -// { -// return $this->booted = (bool) $booted; -// } -// } - -class ApplicationTests extends PHPUnit_Framework_TestCase -{ - public function setUp() - { - \Slim\Http\Environment::mock(array( - 'SERVER_NAME' => 'getdirectus.com', - 'REQUEST_METHOD' => 'GET', - 'SCRIPT_NAME' => '/foo', //<-- Physical - 'PATH_INFO' => '/bar', //<-- Virtual - 'QUERY_STRING' => 'one=foo&two=bar', - )); - } - - public function testApplicationContainer() - { - // callable class:method combination - $app = new \Directus\Application\Application(__DIR__); - $this->assertInstanceOf(\Directus\Application\Container::class, $app->getContainer()); - - $app = new \Directus\Application\Application(__DIR__, ['something' => 2]); - $config = $app->getConfig(); - $this->assertSame(2, $config->get('something')); - } - - public function testApp() - { - $app = new \Directus\Application\Application(__DIR__); - $this->assertSame($app, \Directus\Application\Application::getInstance()); - - $this->assertInternalType('string', $app->getVersion()); - } - - public function testRun() - { - $app = new \Directus\Application\Application(__DIR__); - // Prepare request and response objects - $env = \Slim\Http\Environment::mock([ - 'SCRIPT_NAME' => '/index.php', - 'REQUEST_URI' => '/foo', - 'REQUEST_METHOD' => 'GET', - ]); - $uri = \Slim\Http\Uri::createFromEnvironment($env); - $headers = \Slim\Http\Headers::createFromEnvironment($env); - $cookies = []; - $serverParams = $env->all(); - $body = new \Slim\Http\Body(fopen('php://temp', 'r+')); - $req = new \Slim\Http\Request('GET', $uri, $headers, $cookies, $serverParams, $body); - $res = new \Slim\Http\Response(); - $app->getContainer()['request'] = $req; - $app->getContainer()['response'] = $res; - $app->get('/foo', function ($req, $res) { - echo 'bar'; - }); - ob_start(); - $app->run(); - $resOut = ob_get_clean(); - $this->assertEquals('bar', (string)$resOut); - } - - public function testHooks() - { - $app = new \Directus\Application\Application(__DIR__); - $object = (object)['called' => false]; - $data = ['updated' => false]; - - /** @var \Directus\Hook\Emitter $emitter */ - $emitter = $app->getContainer()->get('hook_emitter'); - $emitter->addAction('test', function ($object) { - $object->called = true; - }); - - $emitter->addFilter('test', function (\Directus\Hook\Payload $payload) { - $payload->set('updated', true); - - return $payload; - }); - - $app->triggerAction('test', $object); - $data = $app->triggerFilter('test', $data); - - $this->assertSame(true, $object->called); - $this->assertArrayHasKey('updated', $data); - $this->assertTrue($data['updated']); - } - - public function testMissingRequirements() - { - $app = new \Directus\Application\Application(__DIR__); - $data = (object)['called' => false]; - $app->setCheckRequirementsFunction(function () { - return ['error']; - }); - $app->onMissingRequirements(function () use ($data) { - $data->called = true; - }); - - $this->assertTrue($data->called); - } -} diff --git a/tests/api/Authentication/ProviderTest.php b/tests/api/Authentication/ProviderTest.php deleted file mode 100644 index c34df8bdf8..0000000000 --- a/tests/api/Authentication/ProviderTest.php +++ /dev/null @@ -1,543 +0,0 @@ -adapter = get_mock_adapter($this, ['id' => 1, 'email' => 'admin@getdirectus.com']); - $this->table = $this->getTableGateway($this->adapter); - $this->userProvider = $this->getUserProvider($this->table); - - $this->provider = new Auth($this->userProvider, $this->secretKey); - } - - public function tearUp() - { - $this->adapter = $this->table = $this->userProvider = $this->provider = null; - } - - /** - * @expectedException \Directus\Exception\Exception - */ - public function testInvalidSecretKey() - { - new Auth($this->userProvider, 123); - } - - public function testSecretKey() - { - $auth = $this->provider; - - $this->assertSame($this->secretKey, $auth->getSecretKey()); - } - - /** - * @expectedException \Directus\Authentication\Exception\UserNotAuthenticatedException - */ - public function testAuthenticationEnforcement() - { - $this->provider->getUserAttributes(); - } - - /** - * @expectedException \Directus\Authentication\Exception\UserNotAuthenticatedException - */ - public function testAuthenticationEnforcement2() - { - $this->provider->getUserAttributes('email'); - } - - /** - * @expectedException \Directus\Authentication\Exception\UserInactiveException - */ - public function testInactiveUser() - { - $auth = $this->getAuth(static::DATA_USER_INACTIVE); - - $auth->login(['email' => 'admin@getdirectus.com', 'password' => 'secret-password']); - } - - /** - * @expectedException \Directus\Authentication\Exception\InvalidUserCredentialsException - */ - public function testInvalidCredentials() - { - $auth = $this->provider; - $result = $auth->login(['email' => 'admin@getdirectus.com', 'password' => 'password']); - } - - public function testSuccessfulLogin() - { - $email = 'admin@getdirectus.com'; - $password = 'secret-password'; - $auth = $this->provider; - $result = $auth->login(['email' => $email, 'password' => $password]); - - $this->assertInstanceOf(\Directus\Authentication\User\UserInterface::class, $result); - $this->assertInstanceOf(\Directus\Authentication\User\UserInterface::class, $auth->getUser()); - } - - public function testAttributes() - { - $email = 'admin@getdirectus.com'; - $password = 'secret-password'; - $auth = $this->provider; - $result = $auth->login(['email' => $email, 'password' => $password]); - - $this->assertSame(1, $auth->getUserAttributes('id')); - - $data = $auth->getUserAttributes(); - $this->assertSame(1, $data['id']); - $this->assertSame($auth->getUserAttributes('id'), $data['id']); - } - - public function testUserObject() - { - $email = 'admin@getdirectus.com'; - $password = 'secret-password'; - $auth = $this->provider; - $result = $auth->login(['email' => $email, 'password' => $password]); - - $this->assertSame($result, $auth->getuser()); - $this->assertSame($email, $auth->getUserAttributes('email')); - $this->assertSame($email, $result->getEmail()); - $this->assertSame(1, $result->getId()); - $this->assertSame($email, $result->get('email')); - } - - /** - * @expectedException \Directus\Authentication\Exception\UnknownUserAttributeException - */ - public function testUnknownUserProperty() - { - $email = 'admin@getdirectus.com'; - $password = 'secret-password'; - $auth = $this->provider; - $result = $auth->login(['email' => $email, 'password' => $password]); - - $fullName = $result->full_name; - } - - public function testAuthenticateWithToken() - { - $email = 'admin@getdirectus.com'; - $password = 'secret-password'; - $user = $this->provider->login(['email' => $email, 'password' => $password]); - - $token = $this->provider->generateAuthToken($user); - - $auth = $this->getAuth(); - $result = $auth->authenticateWithToken($token); - - $this->assertSame($email, $result->getEmail()); - } - - /** - * @expectedException \Directus\Authentication\Exception\InvalidTokenException - */ - public function testAuthenticateWithInvalidToken() - { - $token = $this->generateInvalidPayloadToken(); - $userProvider = $this->getMockUserProvider($this->table); - $this->addEmptyUserToMockUserProvider($userProvider); - - $auth = new Auth($userProvider, $this->secretKey); - $result = $auth->authenticateWithToken($token); - } - - /** - * @expectedException \Firebase\JWT\ExpiredException - */ - public function testAuthenticateWithExpiredToken() - { - $token = $this->generateExpiredToken(); - - // $auth = new Auth($this->getMockUserProvider($this->table), $this->secretKey); - $this->provider->authenticateWithToken($token); - } - - public function testRefreshToken() - { - $token = $this->generateAuthToken(); - $payload = $this->decodeToken($token); - - $newToken = $this->provider->refreshToken($token); - $newPayload = $this->decodeToken($newToken); - - $this->assertTrue($newPayload->exp > $payload->exp); - } - - /** - * @expectedException \Firebase\JWT\ExpiredException - */ - public function testRefreshTokenWithExpiredToken() - { - $token = $this->generateExpiredToken(); - $newToken = $this->provider->refreshToken($token); - } - - public function testPassword() - { - $hashedPassword = $this->provider->hashPassword('secret-password'); - - $this->assertTrue(password_verify('secret-password', $hashedPassword)); - } - - public function testForceUserLogin() - { - $user = new \Directus\Authentication\User\User($this->getData()); - - $auth = $this->getAuth(); - $auth->forceUserLogin($user); - - $this->assertTrue($auth->check()); - $this->assertSame($user, $auth->getUser()); - $this->assertSame($user->getEmail(), $auth->getUserAttributes('email')); - } - - /** - * @expectedException \Directus\Authentication\Exception\UserNotFoundException - */ - public function testMissingIdForceUserLogin() - { - $user = new \Directus\Authentication\User\User(); - - $auth = $this->getAuth(); - $auth->forceUserLogin($user); - } - - public function testInvitationToken() - { - $token = 'invitation-token'; - - $auth = $this->getAuth(); - - $user = $auth->authenticateWithInvitation($token); - - $this->assertInstanceOf(\Directus\Authentication\User\UserInterface::class, $user); - $this->assertSame(1, $user->getId()); - } - - /** - * @expectedException \Directus\Authentication\Exception\InvalidInvitationCodeException - */ - public function testInvalidInvitationToken() - { - $token = 'invalid-token'; - - $userProvider = $this->getMockUserProvider($this->table); - $this->addNotFoundUserToMockUserProvider($userProvider); - - $auth = new Auth($userProvider, $this->secretKey); - - $user = $auth->authenticateWithInvitation($token); - } - - // - // public function testLogin() - // { - // $auth = $this->provider; - // $password = '123456'; - // $salt = 'salt'; - // - // $passwordHashed = $auth->hashPassword($password, $salt); - // $result = $auth->login(1, $passwordHashed, $salt, $password, true); - // $this->assertTrue($result); - // } - // - // public function testSuccessAuthenticationByUser() - // { - // $password = '123456'; - // $salt = 'salt'; - // - // $adapter = get_mock_adapter($this, ['result_data' => [ - // 'password' => $this->provider->hashPassword($password, $salt) - // ]]); - // - // $table = $this->getTableGateway($adapter); - // $auth = new \Directus\Authentication\Provider($table, $this->session); - // - // $user = $auth->getUserByAuthentication('email@mail.com', '123456'); - // $this->assertNotEquals($user, false); - // - // $this->assertTrue($auth->verify('email@mail.com', '123456')); - // } - // - // public function testFailAuthenticationByUser() - // { - // $password = 'secret'; - // $salt = 'salt'; - // - // $adapter = get_mock_adapter($this, ['result_data' => [ - // 'password' => $this->provider->hashPassword($password, $salt) - // ]]); - // - // $table = $this->getTableGateway($adapter); - // $auth = new \Directus\Authentication\Provider($table, $this->session); - // - // $user = $auth->getUserByAuthentication('email@mail.com', '123456'); - // $this->assertFalse($user); - // - // $this->assertFalse($auth->verify('email@mail.com', '123456')); - // } - // - // /** - // * @expectedException \Directus\Authentication\Exception\UserAlreadyLoggedInException - // */ - // public function testLoginSuccessfulTwice() - // { - // $this->testLogin(); - // $this->testLoginLegacyPassword(); - // } - // - // /** - // * @expectedException \InvalidArgumentException - // */ - // public function testRefreshCallable() - // { - // $this->provider->setUserCacheRefreshProvider(true); - // } - // - // /** - // * @expectedException \RuntimeException - // */ - // public function testGetUserRecordException() - // { - // $this->testLogin(); - // $this->provider->getUserRecord(); - // } - // - // public function testGetUserRecord() - // { - // $this->testLogin(); - // - // $userData = [ - // 'id' => 1, - // 'email' => 'admin@demo.local' - // ]; - // - // $this->provider->setUserCacheRefreshProvider(function($id) use ($userData) { - // return $userData; - // }); - // - // $data = $this->provider->getUserRecord(); - // $this->assertSame($data, $userData); - // } - // - // public function testExpireCachedUserRecord() - // { - // $auth = $this->provider; - // $auth->expireCachedUserRecord(); - // $this->assertNull($this->session->get($auth::USER_RECORD_CACHE_SESSION_KEY)); - // } - // - // /** - // * @expectedException \Directus\Authentication\Exception\UserIsntLoggedInException - // */ - // public function testGetUserInfoException() - // { - // $session = get_array_session(); - // $provider = new Auth($this->table, $session, $this->prefix); - // - // $provider->getUserInfo(); - // } - // - // public function testGetUserInfo() - // { - // $this->testLogin(); - // $this->assertInternalType('array', $this->provider->getUserInfo()); - // - // $this->assertSame(1, $this->provider->getUserInfo('id')); - // } - // - // public function testLoggedIn() - // { - // $this->assertFalse($this->provider->loggedIn()); - // $this->testLogin(); - // $this->assertTrue($this->provider->loggedIn()); - // - // $adapter = get_mock_adapter($this, ['result_count' => 1]); - // $table = $this->getTableGateway($adapter); - // $session = get_array_session(); - // - // $provider = new Auth($table, $session, $this->prefix); - // - // $session->set($this->prefix . $provider->getSessionKey(), [ - // 'id' => 1, - // 'access_token' => 'accessTokenTest' - // ]); - // - // $this->assertTrue($provider->loggedIn()); - // } - // - // public function testSetLoggedUser() - // { - // $this->provider->setLoggedUser(2, true); - // - // $this->assertSame(2, $this->provider->getUserInfo('id')); - // $this->assertTrue($this->provider->loggedIn()); - // } - // - // /** - // * @expectedException \Directus\Authentication\Exception\UserIsntLoggedInException - // */ - // public function testLogoutException() - // { - // $session = get_array_session(); - // $provider = new Auth($this->table, $session, $this->prefix); - // - // $provider->logout(true); - // } - // - // public function testLogout() - // { - // $this->testLogin(); - // $this->provider->logout(true); - // $session = $this->session->get($this->provider->getSessionKey()); - // $this->assertEmpty($session); - // } - // - - protected function generateAuthToken() - { - return \Firebase\JWT\JWT::encode(['id' => 10, 'group' => 2, 'exp' => time() + 60], $this->secretKey, 'HS256'); - } - - protected function generateInvalidPayloadToken() - { - return \Firebase\JWT\JWT::encode(['id' => 10, 'group' => 2, 'exp' => time() * 2], $this->secretKey, 'HS256'); - } - - protected function generateExpiredToken() - { - return \Firebase\JWT\JWT::encode(['id' => 10, 'group' => 2, 'exp' => time() - 2], $this->secretKey, 'HS256'); - } - - protected function decodeToken($token) - { - return \Firebase\JWT\JWT::decode($token, $this->secretKey, ['HS256']); - } - - /** - * @param null $type - * - * @return Auth - */ - protected function getAuth($type = null) - { - return new Auth( - new \Directus\Authentication\User\Provider\UserTableGatewayProvider( - $this->getTableGateway($this->adapter, $type) - ), - $this->secretKey - ); - } - - protected function getUserProvider(\Directus\Database\TableGateway\BaseTableGateway $tableGateway) - { - return new \Directus\Authentication\User\Provider\UserTableGatewayProvider($tableGateway); - } - - /** - * @param \Directus\Database\TableGateway\BaseTableGateway $tableGateway - * - * @return PHPUnit_Framework_MockObject_MockObject|\Directus\Authentication\User\Provider\UserProviderInterface - */ - protected function getMockUserProvider(\Directus\Database\TableGateway\BaseTableGateway $tableGateway) - { - $userProvider = create_mock( - $this, - \Directus\Authentication\User\Provider\UserTableGatewayProvider::class, - ['findWhere'], - [$tableGateway] - ); - - return $userProvider; - } - - protected function addEmptyUserToMockUserProvider(PHPUnit_Framework_MockObject_MockObject &$mock) - { - $mock - ->expects($this->any()) - ->method('findWhere') - ->will($this->returnValue(new \Directus\Authentication\User\User())); - } - - protected function addNotFoundUserToMockUserProvider(PHPUnit_Framework_MockObject_MockObject &$mock) - { - $mock - ->expects($this->atMost(1)) - ->method('findWhere') - ->with( - ['invite_token' => 'invalid-token'] - ) - ->will($this->returnValue(null)); - } - - /** - * @param $adapter - * @param int|null $type User type (valid, inactive) - * - * @return \Directus\Database\TableGateway\DirectusUsersTableGateway - */ - protected function getTableGateway($adapter, $type = null) - { - $data = $this->getData($type); - - $mock = create_mock($this, 'Directus\Database\TableGateway\DirectusUsersTableGateway', ['selectWith'], [$adapter]); - - $row = new \Directus\Database\RowGateway\BaseRowGateway('id', 'directus_users', $adapter); - $row->populate($data, true); - - $resultSetMock = create_mock($this, 'Zend\Db\ResultSet\ResultSet', ['current']); - $resultSetMock->expects($this->any())->method('current')->will($this->returnValue($row)); - $mock->expects($this->any())->method('selectWith')->will($this->returnValue($resultSetMock)); - - return $mock; - } - - protected function getData($type = null) - { - $data = [ - 'id' => 1, - 'email' => 'admin@getdirectus.com', - 'password' => password_hash('secret-password', PASSWORD_DEFAULT, ['cost' => 12]), - 'group' => 1, - 'invite_token' => 'invitation-token' - ]; - - if ($type !== static::DATA_USER_INACTIVE) { - $data['status'] = 1; - } - - return $data; - } -} diff --git a/tests/api/Collection/CollectionTest.php b/tests/api/Collection/CollectionTest.php deleted file mode 100644 index 58b15f59ff..0000000000 --- a/tests/api/Collection/CollectionTest.php +++ /dev/null @@ -1,68 +0,0 @@ -assertEmpty($collection->toArray()); - $this->assertTrue($collection->isEmpty()); - $this->assertSame(0, $collection->count()); - } - - public function testCollection() - { - $collection = new \Directus\Collection\Collection([ - 'name' => 'john', - 'best_friend' => 'joseph', - 'age' => 37 - ]); - - $this->assertSame(3, $collection->count()); - - $this->assertTrue($collection->has('name')); - $this->assertTrue(isset($collection['name'])); - $this->assertFalse($collection->has('location')); - $this->assertFalse(isset($collection['location'])); - - $this->assertSame(37, $collection->get('age')); - $this->assertNull($collection->get('location')); - $this->assertNull($collection['location']); - $this->assertSame('unknown', $collection->get('location', 'unknown')); - - $collection->set('location', 'unknown'); - $collection['pet'] = 'fish'; - $this->assertTrue($collection->has('location')); - $this->assertTrue($collection->has('pet')); - $this->assertSame('unknown', $collection->get('location')); - $this->assertSame('fish', $collection['pet']); - - $collection->remove('location'); - unset($collection['pet']); - $this->assertFalse($collection->has('location')); - $this->assertFalse($collection->has('pet')); - - $collection->appendArray(['hair_color' => 'black', 'eye_color' => 'green']); - - $this->assertSame('black', $collection->get('hair_color')); - $this->assertSame('green', $collection->get('eye_color')); - - $anotherCollection = new \Directus\Collection\Collection(['language' => 'English']); - $collection->appendCollection($anotherCollection); - $this->assertTrue($collection->has('language')); - - $collection->replace([ - 'product_name' => 'Product 1', - 'product_cost' => 99 - ]); - - $this->assertSame(2, $collection->count()); - $this->assertSame('Product 1', $collection->get('product_name')); - $this->assertSame(99, $collection->get('product_cost')); - - $collection->clear(); - $this->assertSame(0, $collection->count()); - $this->assertTrue($collection->isEmpty()); - $this->assertEmpty($collection->toArray()); - } -} diff --git a/tests/api/Config/ConfigTest.php b/tests/api/Config/ConfigTest.php deleted file mode 100644 index 649e70e893..0000000000 --- a/tests/api/Config/ConfigTest.php +++ /dev/null @@ -1,60 +0,0 @@ - 1 - ]); - - $this->assertSame(1, $config->get("option")); - } - - public function testItemsUsingSchema() - { - // Get the configuration schema - $schema = Schema::get(); - - // Load context from somewhere (file, env, json, etc.) - $context = Context::from_file(__DIR__ . "/../../../config/api_sample.php"); - - // Load context into schema to get normalized/default/converted values - $values = $schema->value([ - // We pass the context inside a "directus" key because it's the root group - // because it makes every environment variable begin with DIRECTUS_ prefix - "directus" => $context - ]); - - // Pass values to the Config class exactly as it is today - $config = new Config($values); - - // Fetch a value from config - $this->assertEquals("admin@example.com", $config->get("mail.default.from")); - } - - public function testSchemaUsingEnvironement() - { - // Simulate an environment variable - $_ENV["DIRECTUS_MAIL_DEFAULT_FROM"] = "wolfulus@directus.com"; - - // Get the configuration schema - $schema = Schema::get(); - $context = Context::from_env(); - - // We don't need to put it inside directus key in env - $values = $schema->value($context); - - // Fetch values - $config = new Config($values); - $this->assertEquals("wolfulus@directus.com", $config->get("mail.default.from")); - } -} diff --git a/tests/api/Config/ContextTest.php b/tests/api/Config/ContextTest.php deleted file mode 100644 index 28343298e8..0000000000 --- a/tests/api/Config/ContextTest.php +++ /dev/null @@ -1,131 +0,0 @@ - "value1", - "HELLO_WORLD_2" => "value2", - ]); - - $expected = [ - "hello" => [ - "world" => [ - "value1", - "value2" - ], - ], - ]; - - // Should map keys to complex objects - $this->assertEquals($expected, $source); - } - - public function testOverwrites() - { - $source = Context::from_map([ - "HELLO" => "value1", - "HELLO_WORLD" => "value2", - ]); - - $expected = [ - "hello" => [ - "world" => "value2", - ], - ]; - - // Bigger keys wins the trade and should overwrite already set values - $this->assertEquals($expected, $source); - - $source = Context::from_map([ - "HELLO_WORLD" => "value2", - "HELLO" => "value1", - ]); - - // Array order should not be a problem - $this->assertEquals($expected, $source); - } - - public function testSourceEnv() - { - $_ENV['HELLO_WORLD_A'] = "1"; - $_ENV['HELLO_WORLD_B'] = "2"; - $_ENV['HELLO_ARRAY_10_A'] = "3"; - $_ENV['HELLO_ARRAY_10_B'] = "4"; - $_ENV['HELLO_ARRAY_15_A'] = "5"; - $_ENV['HELLO_ARRAY_15_B'] = "6"; - - $source = Context::from_env(); - - $expected = [ - "hello" => [ - "world" => [ - "a" => "1", - "b" => "2", - ], - "array" => [ - [ - "a" => "3", - "b" => "4", - ], - [ - "a" => "5", - "b" => "6", - ] - ] - ], - ]; - - // Should read values from environment variables - $this->assertArraySubset($expected, $source); - } - - public function testArray() - { - $context = Context::from_array([ - "hello" => [ - "world" => [ - "a" => "1", - "b" => "2" - ], - ], - ]); - - $expected = [ - "hello" => [ - "world" => [ - "a" => "1", - "b" => "2" - ], - ], - ]; - - // Should load values from php associative array - $this->assertEquals($expected, $context); - } - - public function testContextFile() - { - $context = Context::from_file(__DIR__ . "/sources/source.php"); - - $expected = [ - "hello" => [ - "world" => [ - "a" => "1", - "b" => "2" - ], - ], - 'arrayval' => [ - 'some' => 'array' - ] - ]; - - // Should load values from php source file - $this->assertEquals($expected, $context); - } -} diff --git a/tests/api/Config/GroupTest.php b/tests/api/Config/GroupTest.php deleted file mode 100644 index 7cf12c02d4..0000000000 --- a/tests/api/Config/GroupTest.php +++ /dev/null @@ -1,60 +0,0 @@ -assertEquals("group", $group->key()); - - // Name should remain the same - $this->assertEquals("GrOuP", $group->name()); - - // Optional should be false - $this->assertEquals(false, $group->optional()); - - $group = new Group("Some_Group?", []); - - // Key should remove underscores - $this->assertEquals("somegroup", $group->key()); - - // Name should remain the same - $this->assertEquals("Some_Group", $group->name()); - - // Optional should be true because of question mark - $this->assertTrue($group->optional()); - } - - public function testGroupChildren() - { - $group = new Group("parent", [ - new Group("child", []) - ]); - - // Should contain a child - $this->assertCount(1, $group->children()); - } - - public function testGroupParent() - { - $group = new Group("parent", [ - new Group("child", []) - ]); - - $children = $group->children(); - - // Should contain a child - $this->assertEquals("child", $children[0]->name()); - $this->assertEquals("parent", $children[0]->parent()->name()); - } -} diff --git a/tests/api/Config/SchemaTest.php b/tests/api/Config/SchemaTest.php deleted file mode 100644 index 97e28c8e65..0000000000 --- a/tests/api/Config/SchemaTest.php +++ /dev/null @@ -1,141 +0,0 @@ -value([]); - - $this->assertArraySubset([ - 'app' => - [ - 'env' => 'production', - 'timezone' => 'America/New_York', - ], - 'settings' => - [ - 'logger' => - [ - ] - ], - 'database' => - [ - 'type' => 'mysql', - 'host' => 'localhost', - 'port' => 3306, - 'name' => 'directus', - 'username' => 'root', - 'password' => 'root', - 'engine' => 'InnoDB', - 'chartset' => 'utf8mb4', - 'socket' => '', - ], - 'cache' => - [ - 'enabled' => false, - 'response_ttl' => 3600, - ], - 'storage' => - [ - 'adapter' => 'local', - 'root' => 'public/uploads/_/originals', - 'root_url' => '/uploads/_/originals', - 'thumb_root' => 'public/uploads/_/thumbnails', - 'options' => [ - 'ACL' => 'public-read', - 'Cache-Control' => 'max-age=604800', - ], - ], - 'mail' => - [ - 'default' => - [ - 'transport' => 'sendmail', - 'from' => 'admin@example.com', - ], - ], - 'cors' => - [ - 'enabled' => true, - 'origin' => - [ - 0 => '*', - ], - 'methods' => - [ - 0 => 'GET', - 1 => 'POST', - 2 => 'PUT', - 3 => 'PATCH', - 4 => 'DELETE', - 5 => 'HEAD', - ], - 'headers' => - [], - 'exposed_headers' => - [], - 'max_age' => NULL, - 'credentials' => false, - ], - 'rate_limit' => - [ - 'enabled' => false, - 'limit' => 100, - 'interval' => 60, - 'adapter' => 'redis', - 'host' => '127.0.0.1', - 'port' => 6379, - 'timeout' => 10, - ], - 'hooks' => - [ - 'actions' => - [], - 'filters' => - [], - ], - 'feedback' => - [ - 'token' => 'a-kind-of-unique-token', - 'login' => true, - ], - 'tableBlacklist' => - [], - 'auth' => - [ - 'secret_key' => '', - 'public_key' => '', - 'social_providers' => - [], - ], - 'ext' => [] - ], $data); - - } - - public function testNonDefaults() - { - $schema = Schema::get(); - - $values = $schema->value([ - "directus" => [ - "storage" => [ - "adapter" => "xxxxxxxxx", - "root" => "xxxxxxxxx", - "root_url" => "xxxxxxxxx", - "thumb_root" => "xxxxxxxxx", - ], - ] - ]); - - $config = new Config($values); - $this->assertEquals($config->get("storage.root_url"), "xxxxxxxxx"); - } -} diff --git a/tests/api/Config/ValueTest.php b/tests/api/Config/ValueTest.php deleted file mode 100644 index c4675b4bc0..0000000000 --- a/tests/api/Config/ValueTest.php +++ /dev/null @@ -1,50 +0,0 @@ - [ - "value" => "12345" - ] - ]); - - $group = new Group("group", [ - new Value("value", Types::INTEGER) - ]); - - $value = $group->value($context); - - $this->assertInternalType("int", $value["value"]); - } - - public function testOptionalValue() - { - $context = Context::from_array([ - "group" => [ - "optional" => "2222" - ] - ]); - - $group = new Group("group", [ - new Value("value", Types::INTEGER, 1111), - new Value("optional?", Types::INTEGER), - new Value("optional2?", Types::INTEGER) - ]); - - $values = $group->value($context); - - $this->assertEquals(1111, $values["value"]); - $this->assertEquals(2222, $values["optional"]); - $this->assertEquals(null, @$values["optional2"]); - } -} diff --git a/tests/api/Config/sources/source.json b/tests/api/Config/sources/source.json deleted file mode 100644 index 1ab116fa24..0000000000 --- a/tests/api/Config/sources/source.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "hello": { - "world": { - "a": 1, - "b": 2 - } - }, - "arrayval": [ - { - "some": "object", - } - ] -} diff --git a/tests/api/Config/sources/source.php b/tests/api/Config/sources/source.php deleted file mode 100644 index 6de17fe03b..0000000000 --- a/tests/api/Config/sources/source.php +++ /dev/null @@ -1,13 +0,0 @@ - [ - "world" => [ - "a" => 1, - "b" => 2, - ], - ], - 'arrayval' => [ - 'some' => 'array' - ] -]; diff --git a/tests/api/ContainerTest.php b/tests/api/ContainerTest.php deleted file mode 100644 index 3b3b3c93da..0000000000 --- a/tests/api/ContainerTest.php +++ /dev/null @@ -1,35 +0,0 @@ - 'john']); - - $this->assertSame('john', $container->get('name')); - $this->assertTrue($container->has('name')); - - $container->set('age', 10); - $this->assertSame(10, $container->get('age')); - - $container->set('country', function () { - return 'us'; - }); - - $this->assertSame('us', $container->get('country')); - } - - /** - * @expectedException \Directus\Container\Exception\ValueNotFoundException - */ - public function testNotFoundValue() - { - $container = new Container(); - - $name = $container->get('name'); - } -} diff --git a/tests/api/Database/ConnectionTest.php b/tests/api/Database/ConnectionTest.php deleted file mode 100644 index 2359a513f1..0000000000 --- a/tests/api/Database/ConnectionTest.php +++ /dev/null @@ -1,53 +0,0 @@ -getDriver()->getConnection(); - $adapterConnection->expects($this->once()) - ->method('connect'); - - $connection->connect(); - } - - public function testStrictMode() - { - // $connection = get_mock_connection($this, [ - // 'result_data' => ['modes' => 'NOTHING,HERE'] - // ]); - - $mockDriver = get_mock_driver($this, [ - 'result_data' => ['modes' => 'NOTHING,HERE'] - ]); - $connection = new \Directus\Database\Connection($mockDriver); - - $this->assertFalse($connection->isStrictModeEnabled()); - - // $connection = get_mock_connection($this, [ - // 'platform_name' => 'sqlite' - // ]); - $mockDriver = get_mock_driver($this, [ - 'platform_name' => 'sqlite' - ]); - $connection = new \Directus\Database\Connection($mockDriver); - - $this->assertFalse($connection->isStrictModeEnabled()); - - // $connection = get_mock_connection($this, [ - // 'platform_name' => 'mysql', - // 'result_data' => ['modes' => 'STRICT_ALL_TABLES,NOTHING'] - // ]); - - $mockDriver = get_mock_driver($this, [ - 'platform_name' => 'mysql', - 'result_data' => ['modes' => 'STRICT_ALL_TABLES,NOTHING'] - ]); - $connection = new \Directus\Database\Connection($mockDriver); - - $this->assertTrue($connection->isStrictModeEnabled()); - } -} diff --git a/tests/api/Database/Ddl/ColumnBooleanTest.php b/tests/api/Database/Ddl/ColumnBooleanTest.php deleted file mode 100644 index f5ba4a0e9e..0000000000 --- a/tests/api/Database/Ddl/ColumnBooleanTest.php +++ /dev/null @@ -1,14 +0,0 @@ -assertSame('foo', $column->getName()); - $this->assertFalse($column->isNullable()); - $this->assertSame(2, $column->getDefault()); - } -} \ No newline at end of file diff --git a/tests/api/Database/Exception/DuplicateEntryExceptionTest.php b/tests/api/Database/Exception/DuplicateEntryExceptionTest.php deleted file mode 100644 index 3ba89ea806..0000000000 --- a/tests/api/Database/Exception/DuplicateEntryExceptionTest.php +++ /dev/null @@ -1,14 +0,0 @@ -(unique_email)'; - - $exception = new \Directus\Database\Exception\DuplicateItemException($message); - - $this->assertSame($expected, $exception->getMessage()); - } -} diff --git a/tests/api/Database/Query/BuilderTest.php b/tests/api/Database/Query/BuilderTest.php deleted file mode 100644 index f4baeba8d3..0000000000 --- a/tests/api/Database/Query/BuilderTest.php +++ /dev/null @@ -1,114 +0,0 @@ -createQueryBuilder(); - $this->assertInstanceOf('\Directus\Database\Connection', $query->getConnection()); - } - - public function testOrder() - { - $query = $this->createQueryBuilder(); - $this->assertEmpty($query->getOrder()); - - $query->orderBy('title'); - $this->assertArrayHasKey('title', $query->getOrder()); - - $query->orderBy('published_at', 'DESC'); - $this->assertArrayHasKey('published_at', $query->getOrder()); - - $orders = $query->getOrder(); - $this->assertCount(2, $orders); - - $this->assertSame('ASC', $orders['title']); - $this->assertSame('DESC', $orders['published_at']); - } - - public function testOffsetAndLimit() - { - $query = $this->createQueryBuilder(); - - $this->assertNull($query->getOffset()); - $this->assertNull($query->getSkip()); - $this->assertNull($query->getLimit()); - - $query->offset(100); - $this->assertSame(100, $query->getOffset()); - $query->offset(-1); - $this->assertSame(0, $query->getOffset()); - - $query->skip(100); - $this->assertSame(100, $query->getOffset()); - $query->skip(-1); - $this->assertSame(0, $query->getOffset()); - - $query->limit(100); - $this->assertSame(100, $query->getLimit()); - - $query->limit(-1); - $this->assertSame(null, $query->getLimit()); - } - - public function testWhere() - { - $query = $this->createQueryBuilder(); - - $this->assertEmpty($query->getWheres()); - $query->where('field1', '=', 2); - $query->where('field', '>', 1); - - $query->whereEqualTo('field2', 1); - $query->whereNotEqualTo('field3', 3); - - $query->whereLessThan('field2', 1); - $query->whereLessThanOrEqual('field3', 3); - - $query->whereGreaterThan('field2', 1); - $query->whereGreaterThanOrEqual('field3', 3); - - $query->whereIn('field2', [1, 2, 3]); - $query->whereNotIn('field3', [1, 2, 3]); - - $query->whereNull('field2'); - $query->whereNotNull('field3'); - - $query->whereLike('field1', 'hola'); - $query->whereNotLike('field2', 'hello'); - - $query->buildSelect(); - - $wheres = $query->getWheres(); - $this->assertCount(14, $wheres); - } - - public function testFrom() - { - $query = $this->createQueryBuilder(); - - $this->assertNull($query->getFrom()); - $query->from('table'); - $this->assertSame('table', $query->getFrom()); - } - - public function testSelect() - { - $query = $this->createQueryBuilder(); - - $this->assertSame(['*'], $query->getColumns()); - $query->from('table'); - $query->columns(['id', 'name']); - $this->assertSame(['id', 'name'], $query->getColumns()); - } - - /** - * @return \Directus\Database\Query\Builder - */ - protected function createQueryBuilder() - { - $connection = get_mock_connection($this); - - return new \Directus\Database\Query\Builder($connection); - } -} \ No newline at end of file diff --git a/tests/api/Database/RowGateway/BaseRowGatewayTest.php b/tests/api/Database/RowGateway/BaseRowGatewayTest.php deleted file mode 100644 index 846a04ffd5..0000000000 --- a/tests/api/Database/RowGateway/BaseRowGatewayTest.php +++ /dev/null @@ -1,207 +0,0 @@ -data = [ - 'title' => 'Vacation', - 'date_uploaded' => '2016-08-10 11:29:34', - 'type' => 'image/jpg' - ]; - } - - public function testPopulate() - { - $data = $this->data; - - // (skip) row does not exists in the database - $row = $this->getRow(); - $row->populateSkipAcl($data, false); - - $this->assertSame($data, $row->toArray()); - $this->assertFalse($row->rowExistsInDatabase()); - - // (skip) row does exists in the database - $row = $this->getRow(); - $row->populateSkipAcl(array_merge(['id' => 1], $data), true); - - $this->assertSame(array_merge(['id' => 1], $data), $row->toArray()); - $this->assertTrue($row->rowExistsInDatabase()); - - // row does not exists in the database - $row = $this->getRow(); - $row->populate($data, false); - - $this->assertSame($data, $row->toArray()); - $this->assertFalse($row->rowExistsInDatabase()); - - // row does exists in the database - $row = $this->getRow(); - $row->populate(array_merge(['id' => 1], $data), true); - - $this->assertSame(array_merge(['id' => 1], $data), $row->toArray()); - $this->assertTrue($row->rowExistsInDatabase()); - - $row = $this->getRow(); - $result = $row->exchangeArray(array_merge(['id' => 1], $data)); - $this->assertSame(array_merge(['id' => 1], $data), $result->toArray()); - $this->assertTrue($row->rowExistsInDatabase()); - } - - public function testProperties() - { - $data = array_merge(['id' => 1], $this->data); - - $row = $this->getRow(); - - $row->populate($data, true); - - $this->assertSame(4, $row->count()); - $this->assertSame('Vacation', $row->title); - $this->assertSame('Vacation', $row['title']); - - $row['title'] = 'Vacation 2016'; - $this->assertSame('Vacation 2016', $row['title']); - - // removing an attribute value - $this->assertTrue(isset($row['title'])); - unset($row['title']); - $this->assertNull($row['title']); - $this->assertTrue(isset($row['title'])); - } - - /** - * @expectedException Directus\Permissions\Exception\ForbiddenFieldReadException - */ - public function testGetException() - { - $row = $this->getRowPrivileges(); - $date = $row['date_uploaded']; - } - - /** - * @expectedException Directus\Permissions\Exception\ForbiddenFieldReadException - */ - public function testOffsetGetException() - { - $row = $this->getRowPrivileges(); - $date = $row->date_uploaded; - } - - /** - * @expectedException Directus\Permissions\Exception\ForbiddenFieldWriteException - */ - public function testUnsetException() - { - $row = $this->getRowPrivileges(); - unset($row['type']); - } - - /** - * @expectedException Directus\Permissions\Exception\ForbiddenFieldWriteException - */ - public function testSetException() - { - $row = $this->getRowPrivileges(); - $row['type'] = 'unknown'; - } - - /** - * @expectedException \Zend\Db\RowGateway\Exception\RuntimeException - */ - public function testPrimaryKeyException() - { - $row = $this->getRow(); - - $row->populateSkipAcl($this->data, true); - } - - public function testMakeRowGateway() - { - $row = $this->getRow(); - - $acl = new Directus\Permissions\Acl(); - $adapter = get_mock_adapter($this); - $newRow = $row->makeRowGatewayFromTableName('id', 'directus_users', $adapter, $acl); - $this->assertInstanceOf('\Directus\Database\RowGateway\DirectusUsersRowGateway', $newRow); - - $newRow = $row->makeRowGatewayFromTableName('id', 'directus_files', $adapter, $acl); - $this->assertInstanceOf('\Directus\Database\RowGateway\BaseRowGateway', $newRow); - } - - public function testStringifyPrimaryKey() - { - $row = $this->getRow(); - - $this->assertInternalType('string', $row->stringifyPrimaryKeyForRecordDebugRepresentation(['id'])); - $this->assertInternalType('string', $row->stringifyPrimaryKeyForRecordDebugRepresentation([])); - } - - public function testPreSaveHook() - { - $row = $this->getRow(); - - $data = ['data' => 1]; - $this->assertSame($data, $row->preSaveDataHook($data)); - } - - public function testDelete() - { - $row = $this->getRow(); - - $row->populate($this->getDataWithID(), true); - -// $affectedRows = $row->delete(); -// $this->assertSame(1, $affectedRows); -// $this->assertFalse($row->existsInDatabase()); - } - - protected function getRow($tableName = 'users', $privileges = []) - { - $adapter = get_mock_adapter($this); - $acl = new Directus\Permissions\Acl($privileges); - $row = new \Directus\Database\RowGateway\BaseRowGateway('id', $tableName, $adapter, $acl); - - $acl->setUserId(1); - $acl->setGroupId(1); - - return $row; - } - - protected function getRowPrivileges($tableName = 'directus_files') - { - $row = $this->getRow($tableName, [ - 'directus_files' => [ - 'id' => 1, - 'table_name' => 'directus_files', - 'group_id' => 1, - 'read_field_blacklist' => ['date_uploaded'], - 'write_field_blacklist' => ['type'], - 'nav_listed' => 1, - 'status_id' => 0, - 'allow_view' => 2, - 'allow_add' => 1, - 'allow_edit' => 2, - 'allow_delete' => 2, - 'allow_alter' => 1 - ] - ]); - - $row->populate($this->data); - - return $row; - } - - protected function getData($withId = false) - { - return $withId ? array_merge(['id' => 1], $this->data) : $this->data; - } - - protected function getDataWithId() - { - return $this->getData(true); - } -} diff --git a/tests/api/Database/SchemaTest.php b/tests/api/Database/SchemaTest.php deleted file mode 100644 index ab4430fb35..0000000000 --- a/tests/api/Database/SchemaTest.php +++ /dev/null @@ -1,212 +0,0 @@ -mockAdapter = get_mock_mysql_schema($this); - $this->schema = new Schema($this->mockAdapter); - } - - public function testAdapter() - { - $this->assertInstanceOf('\Directus\Database\Schemas\Sources\SchemaInterface', $this->schema->getSchema()); - } - - public function testCoreTablesPrefix() - { - /** @var \Directus\Database\Schema\SchemaManager $schema */ - $schema = $this->schema; - $this->assertSame('directus_users', $schema->addSystemCollectionPrefix('users')); - - $tables = ['users', 'tables']; - $prefixedTables = $schema->addSystemCollectionPrefix($tables); - foreach ($tables as $table) { - $this->assertTrue(in_array('directus_' . $table, $prefixedTables)); - } - - $coreTables = $schema->getSystemCollections(); - foreach($coreTables as $table) { - $this->assertTrue(\Directus\Util\StringUtils::startsWith($table, 'directus_')); - } - } - - public function testCoreTables() - { - /** @var \Directus\Database\Schema\SchemaManager $schema */ - $schema = $this->schema; - - $coreTables = $schema->addSystemCollectionPrefix([ - 'activity', - 'bookmarks', - 'columns', - 'files', - 'groups', - 'messages', - 'messages_recipients', - 'preferences', - 'privileges', - 'schema_migrations', - 'settings', - 'tables', - 'users' - ]); - - foreach ($coreTables as $coreTable) { - $this->assertTrue(in_array($coreTable, $this->schema->getDirectusCollections())); - } - } - - public function testPickTableName() - { - $schema = $this->schema; - - $pickCoreTables = [ - 'users', - 'tables' - ]; - - $notExistingTable = [ - 'accounts', - 'databases' - ]; - - $tables = array_merge($pickCoreTables, $notExistingTable); - $filteredTables = $schema->getDirectusTables($tables); - - foreach ($tables as $table) { - $result = in_array($schema->addCoreTablePrefix($table), $filteredTables); - if (in_array($table, $notExistingTable)) { - $this->assertFalse($result); - } else { - $this->assertTrue($result); - } - } - } - - public function testGetPrimaryKey() - { - $adapter = get_mock_mysql_schema($this, ['getPrimaryKey']); - $schema = new Schema($adapter); - - $adapter->expects($this->once()) - ->method('getPrimaryKey') - ->with($this->equalTo('users')) - ->will($this->returnValue('id')); - - $this->assertSame('id', $schema->getPrimaryKey('users')); - } - - public function testTableExists() - { - $adapter = get_mock_mysql_schema($this, ['tableExists', 'someTableExists']); - $schema = new Schema($adapter); - - $adapter->expects($this->at(0)) - ->method('tableExists') - ->with($this->equalTo('users')) - ->will($this->returnValue(true)); - - $adapter->expects($this->at(1)) - ->method('tableExists') - ->with($this->equalTo('sales')) - ->will($this->returnValue(false)); - - $this->assertTrue($schema->tableExists('users')); - $this->assertFalse($schema->tableExists('sales')); - - $adapter->expects($this->at(0)) - ->method('someTableExists') - ->with($this->equalTo(['users', 'files', 'sales'])) - ->will($this->returnValue(true)); - - $adapter->expects($this->at(1)) - ->method('someTableExists') - ->with($this->equalTo(['sales', 'providers', 'customers'])) - ->will($this->returnValue(false)); - - $this->assertTrue($schema->someTableExists(['users', 'files', 'sales'])); - $this->assertFalse($schema->someTableExists(['sales', 'providers', 'customers'])); - } - - public function testGetTables() - { - $adapter = get_mock_mysql_schema($this, ['getTables']); - $adapter->expects($this->once()) - ->method('getTables') - ->will($this->returnValue([])); - - $schema = new Schema($adapter); - - $filter = ['blacklist' => 'files']; - - $adapter->expects($this->once()) - ->method('getTables') - ->with($this->equalTo($filter)); - - $schema->getTables($filter); - } - - public function testGetTablesName() - { - $adapter = get_mock_mysql_schema($this, ['getTablesName']); - $schema = new Schema($adapter); - $data = [ - ['table_name' => 'users'], - ['table_name' => 'files'] - ]; - - $adapter->expects($this->once()) - ->method('getTablesName') - ->will($this->returnValue($data)); - - $result = $schema->getTablesName(); - $this->assertInternalType('array', $result); - $this->assertCount(2, $result); - } - - public function testGetColumns() - { - $adapter = get_mysql_schema($this, [ - 'result_data' => [] - ]); - $schema = new Schema($adapter); - - $this->assertInternalType('array', $schema->getFields('files')); - $this->assertInternalType('array', $schema->getAllFields()); - } - - public function testSupportedDatabase() - { - $this->checkArrayKeys($this->schema->getSupportedDatabases()); - } - - public function testSchemaTemplates() - { - $this->checkArrayKeys($this->schema->getTemplates()); - } - - public function testDirectusTables() - { - $this->assertTrue($this->schema->isDirectusCollection('directus_files')); - $this->assertFalse($this->schema->isDirectusCollection('directus_storage')); - } - - private function checkArrayKeys(array $array) - { - foreach ($array as $item) { - $this->assertInternalType('array', $item); - $this->assertArrayHasKey('name', $item); - $this->assertArrayHasKey('id', $item); - } - } -} diff --git a/tests/api/Database/Schemas/MySQLSchemaTest.php b/tests/api/Database/Schemas/MySQLSchemaTest.php deleted file mode 100644 index 651367f03a..0000000000 --- a/tests/api/Database/Schemas/MySQLSchemaTest.php +++ /dev/null @@ -1,193 +0,0 @@ -getSchema(); - - $result = $schema->getTables(); - $this->assertInstanceOf('Zend\Db\Adapter\Driver\ResultInterface', $result); - - // With Filter - $result = $schema->getTables(['sales']); - $this->assertInstanceOf('Zend\Db\Adapter\Driver\ResultInterface', $result); - - $result = $schema->getTablesName(); - $this->assertInstanceOf('Zend\Db\Adapter\Driver\ResultInterface', $result); - } - - public function testGetTable() - { - $schema = $this->getSchema(); - - $result = $schema->getTable('users'); - $this->assertInstanceOf('Zend\Db\Adapter\Driver\ResultInterface', $result); - } - - public function testHasTable() - { - // Table exists - $schema = $this->getSchema(['result_count' => 1]); - $this->assertTrue($schema->hasTable('users')); - - // Table not exists - $schema = $this->getSchema(['result_count' => 0]); - $this->assertFalse($schema->hasTable('sales')); - } - - public function testTableExists() - { - $mockSchema = $this->getMockSchema(['hasTable']); - - $mockSchema->expects($this->at(0)) - ->method('hasTable') - ->with($this->equalTo('sales')) - ->will($this->returnValue(false)); - - $mockSchema->expects($this->at(1)) - ->method('hasTable') - ->with($this->equalTo('users')) - ->will($this->returnValue(true)); - - $this->assertFalse($mockSchema->tableExists('sales')); - $this->assertTrue($mockSchema->tableExists('users')); - } - - public function testSomeTableExists() - { - $schema = $this->getSchema(); - - $this->assertInternalType('bool', $schema->someTableExists(['users', 'sales'])); - } - - public function testGetColumns() - { - $schema = $this->getSchema(); - - $result = $schema->getColumns('users'); - $this->assertInstanceOf('Zend\Db\Adapter\Driver\ResultInterface', $result); - - $result = $schema->getColumns('users', ['column_name' => 1, 'blacklist' => ['password']]); - $this->assertInstanceOf('Zend\Db\Adapter\Driver\ResultInterface', $result); - - $result = $schema->getColumns('users', false); - $this->assertInstanceOf('Zend\Db\Adapter\Driver\ResultInterface', $result); - } - - public function testGetAllColumns() - { - $schema = $this->getSchema(); - - $result = $schema->getAllColumns(); - $this->assertInstanceOf('Zend\Db\Adapter\Driver\ResultInterface', $result); - } - - public function testParseRecord() - { - $schema = $this->getSchema(); - - $data = ['points' => '1']; - $columns = [ - ['id' => 'points', 'name' => 'points', 'type' => 'int'] - ]; - - foreach($columns as $key => $column) { - $columns[$key] = new \Directus\Database\Object\Field($column); - } - - $result = $schema->parseRecordValuesByType($data, $columns); - $this->assertSame(['points' => 1], $result); - } - - public function testGetPrimaryKey() - { - $data = [ - 'column_name' => 'id' - ]; - - $schema = $this->getSchema(['result_data' => $data]); - - $this->assertSame('id', $schema->getPrimaryKey('users')); - } - - public function testParseValues() - { - $mockSchema = $this->getMockSchema(['castValue']); - - $mockSchema->expects($this->once()) - ->method('castValue') - ->with($this->equalTo('2016'), $this->equalTo('int'), $this->equalTo(false)) - ->will($this->returnValue(2016)); - - - $this->assertSame(2016, $mockSchema->parseType('2016', 'int', false)); - } - - public function testCastValues() - { - $schema = $this->getSchema(); - - // Without data type - $this->assertSame('2016', $schema->castValue('2016')); - $this->assertSame('2016', $schema->castValue('2016', null)); - - // Numbers - $this->assertInternalType('integer', $schema->castValue('2016', 'year')); - $this->assertInternalType('integer', $schema->castValue('9223372036854775807', 'bigint')); - $this->assertInternalType('integer', $schema->castValue('1', 'smallint')); - $this->assertInternalType('integer', $schema->castValue('1', 'mediumint')); - $this->assertInternalType('integer', $schema->castValue('1', 'int')); - $this->assertInternalType('integer', $schema->castValue('1', 'long')); - $this->assertInternalType('integer', $schema->castValue('1', 'tinyint')); - $this->assertInternalType('float', $schema->castValue('1.12345678', 'float')); - - // Date - $this->assertInternalType('string', $schema->castValue('2016-04-16', 'date')); - $this->assertNull($schema->castValue('', 'date')); - $this->assertNull($schema->castValue(NULL, 'date')); - $this->assertNull($schema->castValue('not-a-date', 'date')); - $this->assertNull($schema->castValue('0000-00-00', 'date')); - $this->assertNull($schema->castValue('0000-00-00 00:00:00', 'date')); - - // Time - $this->assertInternalType('string', $schema->castValue('12:22', 'time')); - $this->assertInternalType('string', $schema->castValue('12:22:00', 'time')); - $this->assertInternalType('string', $schema->castValue('00:00:00', 'time')); - $this->assertNull($schema->castValue('', 'time')); - $this->assertNull($schema->castValue(NULL, 'time')); - // Note: this should fail - // $this->assertNull($schema->castValue('not-a-time', 'time')); - - // DateTime - $this->assertInternalType('string', $schema->castValue('2016-04-16 05:30:00', 'datetime')); - $this->assertNull($schema->castValue('', 'datetime')); - $this->assertNull($schema->castValue(NULL, 'datetime')); - $this->assertNull($schema->castValue('not-a-date', 'datetime')); - $this->assertNull($schema->castValue('0000-00-00 00:00:00', 'datetime')); - $this->assertNull($schema->castValue('0000-00-00', 'datetime')); - - // String - $this->assertInternalType('string', $schema->castValue('some text', 'char')); - $this->assertInternalType('string', $schema->castValue('some text', 'varchar')); - $this->assertInternalType('string', $schema->castValue('some text', 'text')); - $this->assertInternalType('string', $schema->castValue('some text', 'tinytext')); - $this->assertInternalType('string', $schema->castValue('some text', 'mediumtext')); - $this->assertInternalType('string', $schema->castValue('some text', 'longtext')); - $this->assertInternalType('string', $schema->castValue('some text', 'var_string')); - - // Blob - $this->assertInternalType('string', $schema->castValue('someblob', 'blob')); - $this->assertInternalType('string', $schema->castValue('someblob', 'mediumblob')); - } - - protected function getSchema($attributes = []) - { - return get_mysql_schema($this, $attributes); - } - - protected function getMockSchema(array $methods = []) - { - return get_mock_mysql_schema($this, $methods); - } -} diff --git a/tests/api/Database/Schemas/Object/CollectionTest.php b/tests/api/Database/Schemas/Object/CollectionTest.php deleted file mode 100644 index 0ca4887a74..0000000000 --- a/tests/api/Database/Schemas/Object/CollectionTest.php +++ /dev/null @@ -1,56 +0,0 @@ - 'users', - 'hidden' => 0, - 'single' => 0, - 'comment' => 'All my clients', - 'schema' => 'marketing' - ]; - - $collection = new Collection($data); - $this->assertSame(ArrayUtils::get($data, 'collection'), $collection->getName()); - $this->assertFalse($collection->isHidden()); - $this->assertFalse($collection->isSingle()); - // $this->assertInstanceOf(StatusMapping::class, $collection->getStatusMapping()); - $this->assertSame(ArrayUtils::get($data, 'comment'), $collection->getComment()); - $this->assertSame(ArrayUtils::get($data, 'schema'), $collection->getSchema()); - - - $fields = [ - new \Directus\Database\Schema\Object\Field(['field' => 'id']), - new \Directus\Database\Schema\Object\Field(['field' => 'name']), - new \Directus\Database\Schema\Object\Field(['field' => 'email']) - ]; - - $collection->setFields($fields); - - $this->assertCount(3, $collection->getFields()); - foreach ($collection->getFields() as $field) { - $this->assertInstanceOf('\Directus\Database\Schema\Object\Field', $field); - } - - $this->assertTrue($collection->hasField('email')); - $this->assertFalse($collection->hasField('password')); - $this->assertFalse($collection->hasStatusField()); - } - - /** - * @expectedException \InvalidArgumentException - */ - public function testInvalidColumnException() - { - $collection = new Collection(['collection' => 'users']); - - $collection->setFields([false, null]); - } -} diff --git a/tests/api/Database/Schemas/Object/FieldRelationshipTest.php b/tests/api/Database/Schemas/Object/FieldRelationshipTest.php deleted file mode 100644 index 3456af1fe8..0000000000 --- a/tests/api/Database/Schemas/Object/FieldRelationshipTest.php +++ /dev/null @@ -1,30 +0,0 @@ - 'category_id']); - $fieldB = new \Directus\Database\Schema\Object\Field(['field' => 'products', 'type' => 'alias']); - - $data = [ - 'collection_a' => 'projects', - 'field_a' => 'category_id', - 'junction_key_a' => null, - 'junction_collection' => null, - 'junction_mixed_collections' => null, - 'junction_key_b' => null, - 'collection_b' => 'categories', - 'field_b' => 'products' - ]; - - $relationshipA = new \Directus\Database\Schema\Object\FieldRelationship($fieldA, $data); - $relationshipB = new \Directus\Database\Schema\Object\FieldRelationship($fieldB, $data); - - $this->assertTrue($relationshipA->isValid()); - $this->assertTrue($relationshipA->isManyToOne()); - - $this->assertTrue($relationshipB->isValid()); - $this->assertTrue($relationshipB->isOneToMany()); - } -} diff --git a/tests/api/Database/Schemas/Object/FieldTest.php b/tests/api/Database/Schemas/Object/FieldTest.php deleted file mode 100644 index 0af509e7d2..0000000000 --- a/tests/api/Database/Schemas/Object/FieldTest.php +++ /dev/null @@ -1,124 +0,0 @@ -fieldData = [ - 'collection' => 'articles', - 'field' => 'related_projects', - 'type' => 'ALIAS', - 'interface' => 'many_to_many', - 'options' => '{"key": "value"}', - 'required' => 0, - 'sort' => 999, - 'comment' => 'Projects related to this project', - 'hidden_detail' => 0, - 'hidden_browse' => 0, - - // from mysql - 'default_value' => 0, - 'nullable' => 1, - 'char_length' => null - ]; - - $this->fieldData2 = [ - 'collection' => 'articles', - 'field' => 'price', - 'type' => 'DECIMAL', - 'interface' => 'numeric', - 'options' => '{"key": "value"}', - 'required' => 1, - 'sort' => 999, - 'comment' => 'Article price', - 'hidden_detail' => 0, - 'hidden_browse' => 0, - - // from mysql - 'default_value' => 0.00, - 'nullable' => 0, - 'precision' => 10, - 'scale' => 2, - 'char_length' => null - ]; - } - - public function testField() - { - $fieldData = $this->fieldData; - - $field = new \Directus\Database\Schema\Object\Field($fieldData); - $field2 = new \Directus\Database\Schema\Object\Field($this->fieldData2); - $field3 = new \Directus\Database\Schema\Object\Field(array_merge( - $this->fieldData2, - ['precision' => '10', 'scale' => '2'] - )); - $field4 = new \Directus\Database\Schema\Object\Field(array_merge( - $this->fieldData2, - [ - 'sort' => 'abc', - 'precision' => 'a', 'scale' => 'b', - 'char_length' => 255 - ] - )); - - // default value - $this->assertSame(0, $field->getDefaultValue()); - $this->assertSame(0.00, $field2->getDefaultValue()); - - // is nullable? - $this->assertTrue($field->isNullable()); - $this->assertFalse($field2->isNullable()); - - // numeric attributes - $this->assertSame(10, $field2->getPrecision()); - $this->assertSame(2, $field2->getScale()); - - // using string numbers - $this->assertSame(10, $field3->getPrecision()); - $this->assertSame(2, $field3->getScale()); - - // using characters - $this->assertSame(0, $field4->getPrecision()); - $this->assertSame(0, $field4->getScale()); - - // char length - $this->assertSame(0, $field->getCharLength()); - $this->assertSame(0, $field->getLength()); - $this->assertSame(255, $field4->getLength()); - $this->assertSame(255, $field4->getCharLength()); - - // sorting - $this->assertSame(999, $field->getSort()); - $this->assertSame(0, $field4->getSort()); - } - - public function testArrayAccess() - { - $field = new \Directus\Database\Schema\Object\Field($this->fieldData); - - $this->assertTrue(isset($field['field'])); - $this->assertSame($field['field'], 'related_projects'); - } - - /** - * @expectedException \Exception - */ - public function testArrayAccessSet() - { - $column = new \Directus\Database\Schema\Object\Field($this->fieldData); - $column['name'] = 'projects'; - } - - /** - * @expectedException \Exception - */ - public function testArrayAccessUnset() - { - $field = new \Directus\Database\Schema\Object\Field($this->fieldData); - unset($field['name']); - } -} diff --git a/tests/api/Database/TableGateway/AclAwareTableGatewayTest.php b/tests/api/Database/TableGateway/AclAwareTableGatewayTest.php deleted file mode 100644 index 5da8af9947..0000000000 --- a/tests/api/Database/TableGateway/AclAwareTableGatewayTest.php +++ /dev/null @@ -1,27 +0,0 @@ -getAclMock(); -// $adapterMock = get_adapter_mock(); -// $table = new AclAwareTableGateway($aclMock, 'directus_users', $adapterMock); - $table = $this->getMockBuilder('\Directus\Database\TableGateway\AclAwareTableGateway') - ->disableOriginalConstructor() - ->getMock(); - - $adapter = get_mock_adapter($this); - $acl = new Directus\Permissions\Acl(); - //$table = new \Directus\Database\TableGateway\AclAwareTableGateway($acl, 'users', $adapter); - } - - protected function getAclMock() - { - $mock = $this->getMockBuilder('\Directus\Permissions\Acl') - ->setConstructorArgs([]) - ->getMock(); - - return $mock; - } -} diff --git a/tests/api/Embed/EmbedManagerTest.php b/tests/api/Embed/EmbedManagerTest.php deleted file mode 100644 index 86d11d62fe..0000000000 --- a/tests/api/Embed/EmbedManagerTest.php +++ /dev/null @@ -1,48 +0,0 @@ -assertNull($embed->get('youtube')); - $this->assertNull($embed->get('vimeo')); - $this->assertNull($embed->getByType('youtube')); - $this->assertNull($embed->getByType('embed/vimeo')); - - $embed->register(new \Directus\Embed\Provider\YoutubeProvider()); - $this->assertNotNull($embed->get('youtube')); - $this->assertNotNull($embed->getByType('embed/youtube')); - $this->assertInstanceOf('\Directus\Embed\Provider\YoutubeProvider', $embed->get('youtube')); - $this->assertInstanceOf('\Directus\Embed\Provider\YoutubeProvider', $embed->getByType('embed/youtube')); - - $embed->register(new \Directus\Embed\Provider\VimeoProvider()); - $this->assertNotNull($embed->get('vimeo')); - $this->assertNotNull($embed->getByType('embed/vimeo')); - $this->assertInstanceOf('\Directus\Embed\Provider\VimeoProvider', $embed->get('vimeo')); - $this->assertInstanceOf('\Directus\Embed\Provider\VimeoProvider', $embed->getByType('embed/vimeo')); - - $data = $embed->parse($this->youtubeURL); - $this->assertInternalType('array', $data); - $this->assertEquals($data['embed_id'], 'dQw4w9WgXcQ'); - $this->assertEquals($data['type'], 'embed/youtube'); - - $data = $embed->parse($this->vimeoURL); - $this->assertInternalType('array', $data); - $this->assertEquals($data['embed_id'], '45196609'); - $this->assertEquals($data['type'], 'embed/vimeo'); - } - - - public function testEmptyEmbedManager() - { - $embed = new EmbedManager(); - $this->setExpectedException('Exception'); - $data = $embed->parse($this->vimeoURL); - } -} diff --git a/tests/api/Embed/VimeoProviderTest.php b/tests/api/Embed/VimeoProviderTest.php deleted file mode 100644 index eac369242d..0000000000 --- a/tests/api/Embed/VimeoProviderTest.php +++ /dev/null @@ -1,51 +0,0 @@ -assertTrue($vimeo->validateURL($this->vimeoURL)); - - $data = $vimeo->parse($this->vimeoURL); - $this->assertInternalType('array', $data); - - $this->assertEquals($data['embed_id'], '45196609'); - $this->assertEquals($data['type'], $vimeo->getType()); - $this->assertEquals($data['type'], 'embed/vimeo'); - - $data = $vimeo->parseID('45196609'); - $this->assertEquals($data['embed_id'], '45196609'); - $this->assertEquals($data['type'], $vimeo->getType()); - $this->assertEquals($data['type'], 'embed/vimeo'); - - $data = $vimeo->parseID(123); - } - - public function testExceptionVimeoEmbedInvalidParseURL() - { - $vimeo = new VimeoProvider(); - $this->setExpectedException('InvalidArgumentException'); - $data = $vimeo->parse($this->youtubeURL); - } - - public function testExceptionVimeoEmbedNonStringURL() - { - $vimeo = new VimeoProvider(); - $this->setExpectedException('InvalidArgumentException'); - $data = $vimeo->parse(true); - } - - public function testExceptionVimeoEmbedNoIDInURL() - { - $vimeo = new VimeoProvider(); - $this->setExpectedException('Exception'); - $data = $vimeo->parse('https://vimeo.com'); - } -} diff --git a/tests/api/Embed/YoutubeProviderTest.php b/tests/api/Embed/YoutubeProviderTest.php deleted file mode 100644 index d3b3d49a7c..0000000000 --- a/tests/api/Embed/YoutubeProviderTest.php +++ /dev/null @@ -1,51 +0,0 @@ -assertTrue($youtube->validateURL($this->youtubeURL)); - - $data = $youtube->parse($this->youtubeURL); - $this->assertInternalType('array', $data); - - $this->assertEquals($data['embed_id'], 'dQw4w9WgXcQ'); - $this->assertEquals($data['type'], $youtube->getType()); - $this->assertEquals($data['type'], 'embed/youtube'); - - $data = $youtube->parseID('dQw4w9WgXcQ'); - $this->assertEquals($data['embed_id'], 'dQw4w9WgXcQ'); - $this->assertEquals($data['type'], $youtube->getType()); - $this->assertEquals($data['type'], 'embed/youtube'); - - $data = $youtube->parseID(123); - } - - public function testExceptionYoutubeEmbedInvalidParseURL() - { - $youtube = new YoutubeProvider(); - $this->setExpectedException('InvalidArgumentException'); - $data = $youtube->parse($this->vimeoURL); - } - - public function testExceptionYoutubeEmbedNonStringURL() - { - $youtube = new YoutubeProvider(); - $this->setExpectedException('InvalidArgumentException'); - $data = $youtube->parse(true); - } - - public function testExceptionYoutubeEmbedNoIDInURL() - { - $youtube = new YoutubeProvider(); - $this->setExpectedException('Exception'); - $data = $youtube->parse('https://youtube.com'); - } -} diff --git a/tests/api/Hook/EmitterTest.php b/tests/api/Hook/EmitterTest.php deleted file mode 100644 index 73f7f73ea3..0000000000 --- a/tests/api/Hook/EmitterTest.php +++ /dev/null @@ -1,137 +0,0 @@ -set('called', true); - - return $payload; - } -} - -class EmitterTest extends \PHPUnit_Framework_TestCase -{ - public function testEmitter() - { - $emitter = new \Directus\Hook\Emitter(); - - // ========================================================= - // Empty listeners - // ========================================================= - $this->assertEmpty($emitter->getActionListeners('removed')); - $this->assertEmpty($emitter->getFilterListeners('fetched')); - - - // ========================================================= - // Expect Action callback to be called once - // ========================================================= - $actionMock = create_mock($this, 'stdClass', ['actionCallback']); - $actionMock->expects($this->at(1)) - ->method('actionCallback') - ->with($this->equalTo(2)) - ->will($this->returnValue(true)); - - $this->assertFalse($emitter->hasActionListeners('removed')); - - $emitter->addAction('removed', [$actionMock, 'actionCallback']); - - // Using Hook Interface - $actionHookMock = create_mock($this, '\Directus\Hook\HookInterface', array('handle')); - $actionHookMock->expects($this->at(0)) - ->method('handle'); - - $emitter->addAction('removed', [$actionMock, 'actionCallback']); - $emitter->addAction('removed', $actionHookMock, $emitter::P_HIGH); - $emitter->run('removed', 2); - $emitter->execute('removed', 2); - - $this->assertTrue($emitter->hasActionListeners('removed')); - - // ========================================================= - // Expect Filter callback to be called once - // and change the value - // ========================================================= - $data = ['string' => 'rngr']; - - $this->assertFalse($emitter->hasFilterListeners('fetched')); - $emitter->addFilter('fetched', function (\Directus\Hook\Payload $payload) { - $payload->set('string', $payload->get('string') . 'a'); - - return $payload; - }); - - $emitter->addFilter('fetched', function (\Directus\Hook\Payload $payload) { - $payload->set('string', $payload->get('string') . 'b'); - - return $payload; - }, $emitter::P_LOW); - - $index = $emitter->addFilter('fetched', function (\Directus\Hook\Payload $payload) { - $payload->set('string', $payload->get('string') . 'c'); - - return $payload; - }, $emitter::P_HIGH); - - $this->assertTrue($emitter->hasFilterListeners('fetched')); - - $result = $emitter->apply('fetched', $data); - $this->assertSame('rngrcab', $result['string']); - - $data = ['string' => 'rngr']; - $emitter->removeListenerWithIndex($index); - $result = $emitter->apply('fetched', $data); - $this->assertSame('rngrab', $result['string']); - } - - public function testStringListener() - { - $emitter = new \Directus\Hook\Emitter(); - - $data = []; - $emitter->addFilter('filter', HookListener::class); - - $data = $emitter->apply('filter', $data); - $this->assertArrayHasKey('called', $data); - $this->assertTrue($data['called']); - } - - public function testPayload() - { - $payload = new Payload(['name' => 'john'], ['age' => 25]); - - $this->assertSame('john', $payload->get('name')); - $this->assertSame(25, $payload->attribute('age')); - - $payload->set('country', 'us'); - $this->assertSame('us', $payload->get('country')); - - $data = $payload->getData(); - $this->assertArrayHasKey('name', $data); - $this->assertArrayHasKey('country', $data); - $this->assertSame('john', $data['name']); - $this->assertSame('us', $data['country']); - } - - /** - * @expectedException InvalidArgumentException - */ - public function testActionException() - { - $emitter = new \Directus\Hook\Emitter(); - $emitter->addAction('removed', 2); - } - - /** - * @expectedException InvalidArgumentException - */ - public function testFilterException() - { - $emitter = new \Directus\Hook\Emitter(); - $emitter->addFilter('fetched', 2); - } -} diff --git a/tests/api/Session/SessionStorageTest.php b/tests/api/Session/SessionStorageTest.php deleted file mode 100644 index 19e1bcb278..0000000000 --- a/tests/api/Session/SessionStorageTest.php +++ /dev/null @@ -1,89 +0,0 @@ - false]); - } - - /** - * @expectedException \InvalidArgumentException - */ - public function testInvalidNameNativeStorage() - { - $storage = new NativeSessionStorage(['name' => false]); - } - - public function testArrayStorage() - { - $storage = new NoPersistenceSessionStorage(['name' => 'test']); - - $this->assertSame('test', $storage->getName()); - $this->assertFalse($storage->isStarted()); - - // start storage - $this->assertTrue($storage->start()); - $this->assertTrue($storage->isStarted()); - $this->assertFalse($storage->start()); - - $storage->stop(); - $this->assertFalse($storage->isStarted()); - - // attributes - $this->assertEmpty($storage->getItems()); - - $this->assertNull($storage->get('name')); - $storage->set('name', 'john'); - $this->assertSame('john', $storage->get('name')); - $storage->set('country_code', 'DO'); - $this->assertSame('DO', $storage->get('country_code')); - - $storage->remove('name'); - $this->assertNull($storage->get('name')); - - $storage->clear(); - $this->assertEmpty($storage->getItems()); - } - - public function testNativeStorage() - { - $this->iniSet('session.use_cookies', 0); - - $storage = new NativeSessionStorage(['name' => 'test']); - - $this->assertSame('test', $storage->getName()); - $this->assertFalse($storage->isStarted()); - - // start storage - $storage->start(); - $this->assertTrue($storage->isStarted()); - $this->assertFalse($storage->start()); - - $storage->stop(); - $this->assertFalse($storage->isStarted()); - - // attributes - $this->assertEmpty($storage->getItems()); - - $this->assertNull($storage->get('name')); - $storage->set('name', 'john'); - $this->assertSame('john', $storage->get('name')); - $storage->set('country_code', 'DO'); - $this->assertSame('DO', $storage->get('country_code')); - - $storage->remove('name'); - $this->assertNull($storage->get('name')); - - $storage->clear(); - $this->assertEmpty($storage->getItems()); - } -} diff --git a/tests/api/Session/SessionTest.php b/tests/api/Session/SessionTest.php deleted file mode 100644 index cf2fdc899c..0000000000 --- a/tests/api/Session/SessionTest.php +++ /dev/null @@ -1,24 +0,0 @@ -assertInstanceOf('\Directus\Session\Storage\ArraySessionStorage', $session->getStorage()); - $this->assertSame($storage, $session->getStorage()); - } - - public function testStorageCalls() - { - $storage = new \Directus\Session\Storage\ArraySessionStorage(); - $session = new \Directus\Session\Session($storage); - - $this->assertNull($session->get('name')); - - $storage->set('name', 'joseph'); - $this->assertSame('joseph', $session->get('name')); - } -} diff --git a/tests/api/Twig/TwigTest.php b/tests/api/Twig/TwigTest.php deleted file mode 100644 index 54bfd30983..0000000000 --- a/tests/api/Twig/TwigTest.php +++ /dev/null @@ -1,17 +0,0 @@ -assertInternalType('array', $extension->getFilters()); - $this->assertInternalType('array', $extension->getFunctions()); - $this->assertInternalType('string', $extension->getName()); - } -} diff --git a/tests/api/Util/ArrayUtilsTest.php b/tests/api/Util/ArrayUtilsTest.php deleted file mode 100644 index 837d5edd11..0000000000 --- a/tests/api/Util/ArrayUtilsTest.php +++ /dev/null @@ -1,333 +0,0 @@ -assertSame('john', $array['name']); - - ArrayUtils::set($array, 'country.name', 'Unknown'); - $this->assertSame('Unknown', $array['country']['name']); - } - - public function testGetItem() - { - $item = ['name' => 'Jim', 'country' => ['name' => 'Germany', 'population' => '9']]; - $this->assertEquals(ArrayUtils::get($item, 'name'), 'Jim'); - $this->assertEquals(ArrayUtils::get($item, 'age', 18), 18); - $this->assertSame('Germany', ArrayUtils::get($item, 'country.name')); - $this->assertSame('German', ArrayUtils::get($item, 'country.language', 'German')); - } - - public function testPickItems() - { - $items = ['name' => 'Jim', 'age' => 79, 'sex' => 'M', 'country' => 'N/A']; - $this->assertEquals(count(ArrayUtils::pick($items, ['name', 'age'])), 2); - $this->assertEquals(count(ArrayUtils::pick($items, ['name', 'age', 'city'])), 2); - $this->assertEquals(ArrayUtils::pick($items, 'name'), ['name' => 'Jim']); - - $this->assertEquals(count(ArrayUtils::filterByKey($items, ['name', 'age'])), 2); - $this->assertEquals(count(ArrayUtils::filterByKey($items, ['name', 'age', 'city'])), 2); - $this->assertEquals(ArrayUtils::filterByKey($items, 'name'), ['name' => 'Jim']); - - $this->assertEquals(count(ArrayUtils::filterByKey($items, ['name', 'age'], false)), 2); - $this->assertEquals(count(ArrayUtils::filterByKey($items, ['name', 'age', 'city'], false)), 2); - $this->assertEquals(ArrayUtils::filterByKey($items, 'name'), ['name' => 'Jim'], false); - } - - public function testOmitItems() - { - $items = ['name' => 'Jim', 'age' => 79, 'sex' => 'M', 'country' => 'N/A']; - $this->assertEquals(count(ArrayUtils::omit($items, ['country'])), 3); - $this->assertEquals(count(ArrayUtils::omit($items, ['country', 'city'])), 3); - $this->assertEquals(ArrayUtils::omit($items, 'name'), ['age' => 79, 'sex' => 'M', 'country' => 'N/A']); - - $this->assertEquals(count(ArrayUtils::filterByKey($items, ['country'], true)), 3); - $this->assertEquals(count(ArrayUtils::filterByKey($items, ['name', 'age', 'city'], true)), 2); - $this->assertEquals(ArrayUtils::filterByKey($items, 'name', true), ['age' => 79, 'sex' => 'M', 'country' => 'N/A']); - } - - public function testContainsItems() - { - $items = ['name' => 'Jim', 'age' => 79, 'sex' => 'M', 'country' => 'N/A']; - $this->assertTrue(ArrayUtils::contains($items, ['name', 'age'])); - $this->assertFalse(ArrayUtils::contains($items, ['name', 'age', 'city'])); - $this->assertTrue(ArrayUtils::contains($items, 'name', 'age')); - } - - public function testContainsSomeItems() - { - $items = ['name' => 'Jim', 'age' => 79, 'sex' => 'M', 'country' => 'N/A']; - $this->assertTrue(ArrayUtils::containsSome($items, ['name', 'age', 'something'])); - $this->assertTrue(ArrayUtils::containsSome($items, ['name'])); - $this->assertTrue(ArrayUtils::containsSome($items, ['name', 'age'])); - $this->assertFalse(ArrayUtils::containsSome($items, ['someone'])); - $this->assertFalse(ArrayUtils::containsSome($items, ['someone', 'noone'])); - } - - public function testFlatKeys() - { - $array = [ - 'user' => [ - 'name' => 'John', - 'country' => [ - 'name' => 'yes' - ], - 'email' => [] - ] - ]; - - $result = ArrayUtils::dot($array); - - $this->assertInternalType('array', $result); - $this->assertArrayHasKey('user.name', $result); - $this->assertArrayHasKey('user.country', $result); - $this->assertArrayHasKey('user.country.name', $result); - $this->assertArrayHasKey('user.email', $result); - $this->assertInternalType('array', $result['user.email']); - - $result = ArrayUtils::flatKey('_', $array); - - $this->assertInternalType('array', $result); - $this->assertArrayHasKey('user_name', $result); - $this->assertArrayHasKey('user_country_name', $result); - } - - public function testDotKeys() - { - $array = [ - 'user' => [ - 'name' => 'John', - 'country' => [ - 'name' => 'yes' - ], - 'email' => [] - ] - ]; - - $this->assertTrue(ArrayUtils::has($array, 'user.email')); - $this->assertFalse(ArrayUtils::has($array, 'user.country.language')); - $this->assertSame('yes', ArrayUtils::get($array, 'user.country.name')); - $this->assertSame('John', ArrayUtils::get($array, 'user.name')); - $this->assertNull(ArrayUtils::get($array, 'user.language')); - $this->assertSame('English', ArrayUtils::get($array, 'user.language', 'English')); - } - - public function testFindFlatKeys() - { - $array = [ - 'user' => [ - 'name' => 'John', - 'country' => [ - 'name' => 'yes' - ], - 'email' => [], - 'account' => [ - 'balance' => null - ] - ] - ]; - - $this->assertEmpty(ArrayUtils::findDot($array, 'user.first_name')); - - $this->assertInternalType('array', ArrayUtils::findDot($array, 'user.name')); - $this->assertInternalType('array', ArrayUtils::findDot($array, 'user.country')); - $this->assertInternalType('array', ArrayUtils::findDot($array, 'user.country.name')); - $this->assertInternalType('array', ArrayUtils::findDot($array, 'user.email')); - $this->assertInternalType('array', ArrayUtils::findDot($array, 'user.account.balance')); - - $this->assertInternalType('array', ArrayUtils::findFlatKey('_', $array, 'user_name')); - $this->assertEmpty(ArrayUtils::findFlatKey('_', $array, 'user_dob')); - } - - public function testMissing() - { - $array1 = ['one', 'two', 'three', 'five']; - $array2 = ['one', 'four', 'five']; - - $result = ArrayUtils::missing($array1, $array2); - $this->assertTrue(in_array('four', $result)); - - $result = ArrayUtils::without($array1, $array2); - $this->assertTrue(in_array('four', $result)); - - $result = ArrayUtils::intersection($array1, $array2, true); - $this->assertTrue(in_array('four', $result)); - } - - public function testDefaults() - { - $array1 = [ - 'database' => [ - 'hostname' => 'localhost', - 'username' => 'root', - 'driver' => 'mysql' - ], - 'status_name' => 'active', - ]; - - $array2 = [ - 'database' => [ - 'hostname' => 'localhost', - 'username' => 'root', - 'password' => 'root', - 'database' => 'directus' - ] - ]; - - $newArray = ArrayUtils::defaults($array1, $array2); - $this->assertTrue(ArrayUtils::has($newArray, 'database.database')); - $this->assertSame('mysql', ArrayUtils::get($newArray, 'database.driver')); - - $newNewArray = ArrayUtils::defaults($newArray, [ - 'database' => [ - 'hostname' => '127.0.0.1' - ] - ]); - $this->assertSame('127.0.0.1', ArrayUtils::get($newNewArray, 'database.hostname')); - } - - public function testRemove() - { - $array = [ - 'name' => 'John', - 'age' => 11, - 'password' => 'secret', - 'salary' => '160', - 'gender' => 'm', - 'married' => true - ]; - - $this->assertTrue(ArrayUtils::has($array, 'married')); - ArrayUtils::remove($array, 'married'); - $this->assertFalse(ArrayUtils::has($array, 'married')); - - $this->assertTrue(ArrayUtils::contains($array, ['salary', 'gender', 'password'])); - ArrayUtils::remove($array, ['salary', 'gender', 'password']); - $this->assertFalse(ArrayUtils::contains($array, ['salary', 'gender', 'password'])); - } - - public function testAliasKeys() - { - $data = ['table' => 'users', 'column' => 'email', 'type' => 'varchar', 'ui' => 'text_input']; - $expectedData = ['table_name' => 'users', 'column_name' => 'email', 'data_type' => 'varchar', 'ui' => 'text_input']; - - $newData = ArrayUtils::aliasKeys($data, [ - 'table_name' => 'table', - 'column_name' => 'column', - 'data_type' => 'type' - ]); - - $this->assertEquals($expectedData, $newData); - } - - public function testIntersection() - { - $array1 = ['id', 'title', 'body', 'published_date']; - $array2 = ['title', 'published_date']; - - $result = ArrayUtils::intersection($array1, $array2); - $this->assertTrue(in_array('title', $result)); - $this->assertTrue(in_array('published_date', $result)); - $this->assertCount(2, $result); - } - - public function testRename() - { - $array = [ - 'name' => 'John Doe', - 'age' => 20 - ]; - - ArrayUtils::rename($array, 'name', 'full_name'); - - $this->assertSame('John Doe', $array['full_name']); - $this->assertFalse(isset($array['name'])); - - ArrayUtils::rename($array, 'age', 'full_name'); - - $this->assertSame(20, $array['full_name']); - $this->assertFalse(isset($array['age'])); - } - - public function testPull() - { - $array = [ - 'name' => 'John', - 'age' => 22 - ]; - - $age = ArrayUtils::pull($array, 'age'); - $this->assertSame(22, $age); - - $this->assertFalse(array_key_exists('age', $array)); - } - - public function testIsNumericKey() - { - $array = [ - 'one', - 'two', - 'three' - ]; - - $this->assertTrue(ArrayUtils::isNumericKeys($array)); - - $array2 = [ - 'name' => 'john' - ]; - - $this->assertFalse(ArrayUtils::isNumericKeys($array2)); - } - - public function testPushPopShift() - { - $array = [ - 'one', - 'two', - 'three' - ]; - - // Unshift - $count = ArrayUtils::unshift($array, 'zero'); - $this->assertCount($count, $array); - $this->assertSame('zero', ArrayUtils::get($array, 0)); - - // Shift - $zero = ArrayUtils::shift($array); - $this->assertCount(3, $array); - $this->assertSame('zero', $zero); - - // Push - $count = ArrayUtils::push($array, 'four'); - $this->assertCount($count, $array); - $this->assertSame('four', ArrayUtils::get($array, 3)); - - // Pop - $four = ArrayUtils::pop($array); - $this->assertCount(3, $array); - $this->assertSame('four', $four); - } - - public function testDeepLevel() - { - $array = [ - 'one' => [ - 'one.one' => 1 - ], - 'two' => [ - 'two.one' => 2, - 'two.two' => [ - 'name' => 'ballerina' - ] - ] - ]; - - $this->assertSame(2, ArrayUtils::deepLevel($array)); - } -} diff --git a/tests/api/Util/DateTimeUtilsTest.php b/tests/api/Util/DateTimeUtilsTest.php deleted file mode 100644 index 54c7ac9ab8..0000000000 --- a/tests/api/Util/DateTimeUtilsTest.php +++ /dev/null @@ -1,76 +0,0 @@ -switchToTimeZone($currentTimezone); - $this->assertEquals('2016-06-28 17:13:18', $dateTime->toString('Y-m-d H:i:s')); - } - - public function testNow() - { - $datetime = DateTimeUtils::now(); - $this->assertInstanceOf(DateTimeUtils::class, $datetime); - } - - public function testUtc() - { - $datetime = DateTimeUtils::nowInUTC(); - $this->assertInstanceOf(DateTimeUtils::class, $datetime); - $this->assertSame('UTC', $datetime->getTimezone()->getName()); - } - - public function testInDays() - { - $today = DateTimeUtils::now(); - $tomorrow = DateTimeUtils::inDays(1); - - $this->assertTrue($today < $tomorrow); - } - - public function testDaysAgo() - { - $today = DateTimeUtils::now(); - $yesterday = DateTimeUtils::wasDays(1); - - $this->assertTrue($today > $yesterday); - } - - public function testToGmt() - { - $current = DateTimeUtils::createFromDefaultFormat('2018-04-09 12:00:00'); - $gmt = $current->toGMT(); - - $this->assertSame('GMT', $gmt->getTimezone()->getName()); - $gmtValue = '2018-04-09 16:00:00'; - $this->assertSame($gmtValue, $gmt->toString()); - $this->assertSame($gmtValue, $current->toGMTString()); - } - - public function testIso8601Format() - { - $current = DateTimeUtils::createFromDefaultFormat('2018-04-09 12:00:00', 'UTC'); - $isoFormat = $current->toISO8601Format(); - $this->assertSame('2018-04-09T12:00:00+00:00', $isoFormat); - - } - - /** - * @expectedException InvalidArgumentException - */ - public function testInvalidTimeZone() - { - DateTimeUtils::now('invalid-timezone'); - } -} diff --git a/tests/api/Util/FormattingTest.php b/tests/api/Util/FormattingTest.php deleted file mode 100644 index a8feb2dd19..0000000000 --- a/tests/api/Util/FormattingTest.php +++ /dev/null @@ -1,28 +0,0 @@ -assertEquals('A Test File', Formatting::fileNameToFileTitle($path)); - } - - public function testUnderscoreToCamelCase() - { - $this->assertEquals('HelloWorld', Formatting::underscoreToCamelCase('hello_world')); - } - - public function testSanitizeTitle() - { - /* - $title = 'this is a text example'; - $this->assertEquals('this-is-a-text-example', Formatting::sanitize_title_with_dashes($title)); - - $title = 'this–is—a text example'; - $this->assertEquals('this-is-a-text-example', Formatting::sanitize_title_with_dashes($title, '', 'save')); - */ - } -} diff --git a/tests/api/Util/GitUtilsTest.php b/tests/api/Util/GitUtilsTest.php deleted file mode 100644 index 8a0fe1672d..0000000000 --- a/tests/api/Util/GitUtilsTest.php +++ /dev/null @@ -1,45 +0,0 @@ -gitPath = __DIR__ . '/git'; - $this->gitPath2 = $this->gitPath . '2'; - mkdir($this->gitPath); - file_put_contents($this->gitPath . '/HEAD', 'ref: master'); - file_put_contents($this->gitPath . '/master', 'commit-hash'); - - mkdir($this->gitPath2); - file_put_contents($this->gitPath2 . '/HEAD', 'development'); - } - - public function tearDown() - { - unlink($this->gitPath . '/HEAD'); - unlink($this->gitPath . '/master'); - unlink($this->gitPath2 . '/HEAD'); - rmdir($this->gitPath); - rmdir($this->gitPath2); - } - - public function testHashDotGit() - { - $hash = \Directus\Util\Git::getCloneHash(__DIR__ . '/git'); - $this->assertSame('commit-hash', $hash); - } - - public function testHashDotGitMissingHead() - { - $hash = \Directus\Util\Git::getCloneHash(__DIR__ . '/git2'); - $this->assertSame('development', $hash); - } - - public function testSession() - { - $this->assertSame(session_id(), \Directus\Util\Git::getCloneHash('')); - } -} diff --git a/tests/api/Util/Installation/InstallerUtilsTest.php b/tests/api/Util/Installation/InstallerUtilsTest.php deleted file mode 100644 index 1eced64f9a..0000000000 --- a/tests/api/Util/Installation/InstallerUtilsTest.php +++ /dev/null @@ -1,88 +0,0 @@ -setExpectedException('InvalidArgumentException'); - InstallerUtils::createConfig(__DIR__ . '/', []); - } - - public function testVariableReplacement() - { - $result = InstallerUtils::replacePlaceholderValues('{{name}}', ['name' => 'John']); - $this->assertSame($result, 'John'); - - $result = InstallerUtils::replacePlaceholderValues('{{user.name}}', [ - 'user' => [ - 'name' => 'John' - ] - ]); - $this->assertSame($result, 'John'); - - $result = InstallerUtils::replacePlaceholderValues('{{user.country.name}}', [ - 'user' => [ - 'name' => 'John', - 'country' => [ - 'name' => 'yes' - ] - ] - ]); - $this->assertSame($result, 'yes'); - } - - public function testCreateFiles() - { - InstallerUtils::createConfig(__DIR__ . '/', [ - 'db_type' => 'mysql', - 'db_port' => 3306, - 'db_host' => 'localhost', - 'db_name' => 'directus', - 'db_user' => 'root', - 'db_password' => 'password', - 'mail_from' => 'admin@directus.local', - 'feedback_token' => 'token', - 'feedback_login' => true, - 'auth_secret' => 'secret-auth-key', - 'auth_public' => 'public-auth-key', - 'cors_enabled' => true - ]); - - $this->assertSame(sha1_file(__DIR__ . '/mock/config.sample.php'), sha1_file(__DIR__ . '/config/api.php')); - } - - public function testCreateFiles2() - { - $this->tearDown(); - - InstallerUtils::createConfig(__DIR__ . '/', [ - 'project' => 'prod', - 'db_type' => 'mysql', - 'db_port' => 3306, - 'db_host' => 'localhost', - 'db_name' => 'directus', - 'db_user' => 'root', - 'db_password' => 'password', - 'feedback_token' => 'token', - 'feedback_login' => true, - 'auth_secret' => 'secret-auth-key', - 'auth_public' => 'public-auth-key', - 'cors_enabled' => true - ]); - - $this->assertSame(sha1_file(__DIR__ . '/mock/config.sample2.php'), sha1_file(__DIR__ . '/config/api.prod.php')); - } - - public function tearDown() - { - if (file_exists(__DIR__ . '/config/api.php')) { - unlink(__DIR__ . '/config/api.php'); - } - - if (file_exists(__DIR__ . '/config/api.prod.php')) { - unlink(__DIR__ . '/config/api.prod.php'); - } - } -} diff --git a/tests/api/Util/Installation/config/.gitkeep b/tests/api/Util/Installation/config/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/tests/api/Util/Installation/mock/config.sample.php b/tests/api/Util/Installation/mock/config.sample.php deleted file mode 100644 index 6ba6c55f6b..0000000000 --- a/tests/api/Util/Installation/mock/config.sample.php +++ /dev/null @@ -1,153 +0,0 @@ - [ - 'env' => 'production', - 'timezone' => 'America/New_York', - ], - - 'settings' => [ - 'logger' => [ - 'path' => __DIR__ . '/../logs', - ], - ], - - 'database' => [ - 'type' => 'mysql', - 'host' => 'localhost', - 'port' => 3306, - 'name' => 'directus', - 'username' => 'root', - 'password' => 'password', - 'engine' => 'InnoDB', - 'charset' => 'utf8mb4', - // When using unix socket to connect to the database the host attribute should be removed - // 'socket' => '/var/lib/mysql/mysql.sock', - ], - - 'cache' => [ - 'enabled' => false, - 'response_ttl' => 3600, // seconds - // 'pool' => [ - // 'adapter' => 'apc' - // ], - // 'pool' => [ - // 'adapter' => 'apcu' - // ], - // 'pool' => [ - // 'adapter' => 'filesystem', - // 'path' => 'cache', // relative to the api directory - // ], - // 'pool' => [ - // 'adapter' => 'memcached', - // 'host' => 'localhost', - // 'port' => 11211 - // ], - // 'pool' => [ - // 'adapter' => 'redis', - // 'host' => 'localhost', - // 'port' => 6379 - // ], - ], - - 'storage' => [ - 'adapter' => 'local', - // The storage root is the directus root directory. - // All path are relative to the storage root when the path is not starting with a forward slash. - // By default the uploads directory is located at the directus public root - // An absolute path can be used as alternative. - 'root' => 'public/uploads/_/originals', - // This is the url where all the media will be pointing to - // here is where Directus will assume all assets will be accessed - // Ex: (yourdomain)/uploads/_/originals - 'root_url' => '/uploads/_/originals', - // Same as "root", but for the thumbnails - 'thumb_root' => 'public/uploads/_/thumbnails', - // 'key' => 's3-key', - // 'secret' => 's3-secret', - // 'region' => 's3-region', - // 'version' => 's3-version', - // 'bucket' => 's3-bucket' - // 'options' => ['ACL' => 'public-read', 'Cache-Control' => 'max-age=604800'] - ], - - 'mail' => [ - 'default' => [ - 'transport' => 'sendmail', - 'from' => 'admin@directus.local' - ], - ], - - 'cors' => [ - 'enabled' => true, - 'origin' => ['*'], - 'methods' => [ - 'GET', - 'POST', - 'PUT', - 'PATCH', - 'DELETE', - 'HEAD', - ], - 'headers' => [], - 'exposed_headers' => [], - 'max_age' => null, // in seconds - 'credentials' => false, - ], - - 'rate_limit' => [ - 'enabled' => false, - 'limit' => 100, // number of request - 'interval' => 60, // seconds - 'adapter' => 'redis', - 'host' => '127.0.0.1', - 'port' => 6379, - 'timeout' => 10 - ], - - 'hooks' => [ - 'actions' => [], - 'filters' => [], - ], - - 'feedback' => [ - 'token' => 'token', - 'login' => true - ], - - // These tables will not be loaded in the directus schema - 'tableBlacklist' => [], - - 'auth' => [ - 'secret_key' => 'secret-auth-key', - 'public_key' => 'public-auth-key', - 'social_providers' => [ - // 'okta' => [ - // 'client_id' => '', - // 'client_secret' => '', - // 'base_url' => 'https://dev-000000.oktapreview.com/oauth2/default' - // ], - // 'github' => [ - // 'client_id' => '', - // 'client_secret' => '' - // ], - // 'facebook' => [ - // 'client_id' => '', - // 'client_secret' => '', - // 'graph_api_version' => 'v2.8', - // ], - // 'google' => [ - // 'client_id' => '', - // 'client_secret' => '', - // 'hosted_domain' => '*', - // // Uses OpenIDConnect to fetch the email instead of using the Google+ API - // // Disabling the OIDC Mode, requires you to enable the Google+ API otherwise it will fail - // 'use_oidc_mode' => true, - // ], - // 'twitter' => [ - // 'identifier' => '', - // 'secret' => '' - // ] - ] - ], -]; diff --git a/tests/api/Util/Installation/mock/config.sample2.php b/tests/api/Util/Installation/mock/config.sample2.php deleted file mode 100644 index 8bf14b6ff5..0000000000 --- a/tests/api/Util/Installation/mock/config.sample2.php +++ /dev/null @@ -1,153 +0,0 @@ - [ - 'env' => 'production', - 'timezone' => 'America/New_York', - ], - - 'settings' => [ - 'logger' => [ - 'path' => __DIR__ . '/../logs', - ], - ], - - 'database' => [ - 'type' => 'mysql', - 'host' => 'localhost', - 'port' => 3306, - 'name' => 'directus', - 'username' => 'root', - 'password' => 'password', - 'engine' => 'InnoDB', - 'charset' => 'utf8mb4', - // When using unix socket to connect to the database the host attribute should be removed - // 'socket' => '/var/lib/mysql/mysql.sock', - ], - - 'cache' => [ - 'enabled' => false, - 'response_ttl' => 3600, // seconds - // 'pool' => [ - // 'adapter' => 'apc' - // ], - // 'pool' => [ - // 'adapter' => 'apcu' - // ], - // 'pool' => [ - // 'adapter' => 'filesystem', - // 'path' => 'cache', // relative to the api directory - // ], - // 'pool' => [ - // 'adapter' => 'memcached', - // 'host' => 'localhost', - // 'port' => 11211 - // ], - // 'pool' => [ - // 'adapter' => 'redis', - // 'host' => 'localhost', - // 'port' => 6379 - // ], - ], - - 'storage' => [ - 'adapter' => 'local', - // The storage root is the directus root directory. - // All path are relative to the storage root when the path is not starting with a forward slash. - // By default the uploads directory is located at the directus public root - // An absolute path can be used as alternative. - 'root' => 'public/uploads/prod/originals', - // This is the url where all the media will be pointing to - // here is where Directus will assume all assets will be accessed - // Ex: (yourdomain)/uploads/_/originals - 'root_url' => '/uploads/prod/originals', - // Same as "root", but for the thumbnails - 'thumb_root' => 'public/uploads/prod/thumbnails', - // 'key' => 's3-key', - // 'secret' => 's3-secret', - // 'region' => 's3-region', - // 'version' => 's3-version', - // 'bucket' => 's3-bucket' - // 'options' => ['ACL' => 'public-read', 'Cache-Control' => 'max-age=604800'] - ], - - 'mail' => [ - 'default' => [ - 'transport' => 'sendmail', - 'from' => 'admin@example.com' - ], - ], - - 'cors' => [ - 'enabled' => true, - 'origin' => ['*'], - 'methods' => [ - 'GET', - 'POST', - 'PUT', - 'PATCH', - 'DELETE', - 'HEAD', - ], - 'headers' => [], - 'exposed_headers' => [], - 'max_age' => null, // in seconds - 'credentials' => false, - ], - - 'rate_limit' => [ - 'enabled' => false, - 'limit' => 100, // number of request - 'interval' => 60, // seconds - 'adapter' => 'redis', - 'host' => '127.0.0.1', - 'port' => 6379, - 'timeout' => 10 - ], - - 'hooks' => [ - 'actions' => [], - 'filters' => [], - ], - - 'feedback' => [ - 'token' => 'token', - 'login' => true - ], - - // These tables will not be loaded in the directus schema - 'tableBlacklist' => [], - - 'auth' => [ - 'secret_key' => 'secret-auth-key', - 'public_key' => 'public-auth-key', - 'social_providers' => [ - // 'okta' => [ - // 'client_id' => '', - // 'client_secret' => '', - // 'base_url' => 'https://dev-000000.oktapreview.com/oauth2/default' - // ], - // 'github' => [ - // 'client_id' => '', - // 'client_secret' => '' - // ], - // 'facebook' => [ - // 'client_id' => '', - // 'client_secret' => '', - // 'graph_api_version' => 'v2.8', - // ], - // 'google' => [ - // 'client_id' => '', - // 'client_secret' => '', - // 'hosted_domain' => '*', - // // Uses OpenIDConnect to fetch the email instead of using the Google+ API - // // Disabling the OIDC Mode, requires you to enable the Google+ API otherwise it will fail - // 'use_oidc_mode' => true, - // ], - // 'twitter' => [ - // 'identifier' => '', - // 'secret' => '' - // ] - ] - ], -]; diff --git a/tests/api/Util/JWTTest.php b/tests/api/Util/JWTTest.php deleted file mode 100644 index 753eabbc1d..0000000000 --- a/tests/api/Util/JWTTest.php +++ /dev/null @@ -1,39 +0,0 @@ -assertTrue(JWTUtils::isJWT($token)); - $this->assertFalse(JWTUtils::isJWT('token')); - - $token = implode('.', [base64_encode('null'), 'k', 'en']); - $this->assertFalse(JWTUtils::isJWT($token)); - $this->assertFalse(JWTUtils::isJWT(123)); - - $token = implode('.', [base64_encode('{"typ": "none"}'), 'k', 'en']); - $this->assertFalse(JWTUtils::isJWT($token)); - } - - public function testExpiration() - { - $data = ['exp' => 0]; - $token = JWTUtils::encode($data, 123); - $this->assertTrue(JWTUtils::hasExpired($token)); - - $data = ['exp' => time() * 2]; - $token = JWTUtils::encode($data, 123); - $this->assertFalse(JWTUtils::hasExpired($token)); - - $data = ['id' => 1]; - $token = JWTUtils::encode($data, 123); - $this->assertNull(JWTUtils::hasExpired($token)); - } -} diff --git a/tests/api/Util/SchemaUtilTest.php b/tests/api/Util/SchemaUtilTest.php deleted file mode 100644 index cf6608e9dd..0000000000 --- a/tests/api/Util/SchemaUtilTest.php +++ /dev/null @@ -1,34 +0,0 @@ -assertEquals('column_name_here', SchemaUtils::cleanColumnName('column name here')); - $this->assertEquals('column_name_here', SchemaUtils::cleanColumnName('column name$here')); - $this->assertEquals('column_name_here', SchemaUtils::cleanColumnName('column name $here')); - $this->assertEquals('column_', SchemaUtils::cleanColumnName('column ')); - $this->assertEquals('column_3', SchemaUtils::cleanColumnName('column 3')); - $this->assertEquals('column', SchemaUtils::cleanColumnName('3column')); - } - - public function testTableName() - { - $this->assertEquals('column_name_here', SchemaUtils::cleanTableName('column name here')); - $this->assertEquals('column_name_here', SchemaUtils::cleanTableName('column name$here')); - $this->assertEquals('column_name_here', SchemaUtils::cleanTableName('column name $here')); - $this->assertEquals('column_', SchemaUtils::cleanTableName('column ')); - $this->assertEquals('column_3', SchemaUtils::cleanTableName('column 3')); - } - - public function testIdentifierName() - { - $this->assertEquals('column_name_here', SchemaUtils::cleanIdentifier('column name here')); - $this->assertEquals('column_name_here', SchemaUtils::cleanIdentifier('column name$here')); - $this->assertEquals('column_name_here', SchemaUtils::cleanIdentifier('column name $here')); - $this->assertEquals('column_', SchemaUtils::cleanIdentifier('column ')); - $this->assertEquals('column_3', SchemaUtils::cleanIdentifier('column 3')); - } -} diff --git a/tests/api/Util/StringUtilsTest.php b/tests/api/Util/StringUtilsTest.php deleted file mode 100644 index 97a811e6bf..0000000000 --- a/tests/api/Util/StringUtilsTest.php +++ /dev/null @@ -1,157 +0,0 @@ -assertTrue(StringUtils::contains('I am learning the abc', 'abc')); - $this->assertFalse(StringUtils::contains('I am John', 'Jack')); - - $this->assertTrue(StringUtils::contains('JavaScript, Java, PHP, C', ['Java', 'C'])); - $this->assertFalse(StringUtils::contains('JavaScript, Java, PHP, C', ['C#', 'C++'])); - } - - public function testHas() - { - $this->assertTrue(StringUtils::has('I am learning the abc', 'abc')); - $this->assertFalse(StringUtils::has('I am John', 'Jack')); - - $this->assertTrue(StringUtils::has('JavaScript, Java, PHP, C', ['Java', 'C'])); - $this->assertFalse(StringUtils::has('JavaScript, Java, PHP, C', ['C#', 'C++'])); - } - - public function testStartsWith() - { - $string = 'john_mcclane'; - $this->assertTrue(StringUtils::startsWith($string, 'john')); - $this->assertFalse(StringUtils::startsWith($string, 'mcclane')); - } - - public function testEndsWith() - { - $string = 'john_marston'; - $this->assertTrue(StringUtils::endsWith($string, 'marston')); - $this->assertFalse(StringUtils::endsWith($string, 'john')); - } - - public function testLength() - { - $this->assertEquals(10, StringUtils::length('mr. falcon')); - } - - public function testRandom() - { - $length = 10; - $this->assertEquals(10, strlen(StringUtils::random($length))); - $this->assertEquals(16, strlen(StringUtils::random())); - $this->assertInternalType('string', StringUtils::random()); - $this->assertEquals(1, strlen(StringUtils::random(1))); - - if (!function_exists('random_bytes')) { - function random_bytes($length) - { - if ($length == 99) { - throw new \Exception('Random exception'); - } - - return str_repeat('a', $length); - } - } - - $this->assertEquals(10, strlen(StringUtils::random($length))); - $this->assertEquals(99, strlen(StringUtils::random(99))); - } - - public function testRandomString() - { - $length = 10; - $this->assertEquals(10, strlen(StringUtils::randomString($length))); - $this->assertEquals(16, strlen(StringUtils::randomString())); - $this->assertInternalType('string', StringUtils::randomString()); - $this->assertEquals(1, strlen(StringUtils::randomString(1))); - } - - /** - * @expectedException InvalidArgumentException - */ - public function testRandomHasException() - { - StringUtils::random(0); - } - - public function testUnderscoreToCamelCase() - { - $this->assertSame('camelCase', StringUtils::underscoreToCamelCase('camel_case')); - $this->assertSame('CamelCase', StringUtils::underscoreToCamelCase('camel_case', true)); - } - - public function testToCamelCase() - { - $this->assertSame('camelCase', StringUtils::toCamelCase('camel_case')); - $this->assertSame('CamelCase', StringUtils::toCamelCase('camel_case', true)); - - $this->assertSame('camelCase', StringUtils::toCamelCase('camel-case', false, '-')); - $this->assertSame('CamelCase', StringUtils::toCamelCase('camel-case', true, '-')); - } - - public function testCharSequence() - { - $this->assertSame('a', StringUtils::charSequence()); - $this->assertSame('b', StringUtils::charSequence('a')); - $this->assertSame('aa', StringUtils::charSequence('z')); - $this->assertSame('ab', StringUtils::charSequence('aa')); - } - - public function testReplacePlaceholder() - { - $string = 'I went to {{place}}'; - $data = ['place' => 'Portland']; - $expected = 'I went to Portland'; - $this->assertEquals($expected, StringUtils::replacePlaceholder($string, $data)); - $this->assertEquals($expected, StringUtils::replacePlaceholder($string, $data, StringUtils::PLACEHOLDER_DOUBLE_MUSTACHE)); - - $string = 'I went to %{place}'; - $this->assertEquals($expected, StringUtils::replacePlaceholder($string, $data, StringUtils::PLACEHOLDER_PERCENTAGE_MUSTACHE)); - - $string = 'Took a flight from {{from_airport}} to {{to_airport}}'; - $data = ['from_airport' => 'SFO', 'to_airport' => 'PDX']; - $expected = 'Took a flight from SFO to PDX'; - $this->assertEquals($expected, StringUtils::replacePlaceholder($string, $data)); - $this->assertEquals($expected, StringUtils::replacePlaceholder($string, $data, StringUtils::PLACEHOLDER_DOUBLE_MUSTACHE)); - - $string = 'Took a flight from %{from_airport} to %{to_airport}'; - $this->assertEquals($expected, StringUtils::replacePlaceholder($string, $data, StringUtils::PLACEHOLDER_PERCENTAGE_MUSTACHE)); - - $string = 'Paid: {{true}}, overdue: {{false}}.'; - $data = ['true' => true, 'false' => false]; - $expected = 'Paid: true, overdue: false.'; - $this->assertEquals($expected, StringUtils::replacePlaceholder($string, $data, StringUtils::PLACEHOLDER_DOUBLE_MUSTACHE)); - } - - public function testCsv() - { - $csv = 'one, two, , three,four'; - - // trim string - $result = StringUtils::csv($csv); - $this->assertInternalType('array', $result); - $this->assertCount(5, $result); - $this->assertSame('two', $result[1]); - - // without trim - $result = StringUtils::csv($csv, false); - $this->assertInternalType('array', $result); - $this->assertCount(5, $result); - $this->assertSame(' two', $result[1]); - } - - /** - * @expectedException \InvalidArgumentException - */ - public function testCsvException() - { - $result = StringUtils::csv(['one', 'two']); - } -} diff --git a/tests/api/Validator/ValidatorTest.php b/tests/api/Validator/ValidatorTest.php deleted file mode 100644 index 0b1fa5e81d..0000000000 --- a/tests/api/Validator/ValidatorTest.php +++ /dev/null @@ -1,64 +0,0 @@ - 'string-value', - 'numeric' => 1, - 'required' => true, - 'email' => 'admin@getdirectus.com' - ]; - $rules = [ - 'string' => 'string', - 'numeric' => 'numeric', - 'required' => 'required', - 'email' => 'email' - ]; - - foreach ($data as $key => $value) { - $violations = $validator->validate($value, [$key => $rules[$key]]); - $this->assertSame(0, $violations->count()); - } - } - - public function testFailedConstraint() - { - $validator = new Validator(); - - $data = [ - 'string' => 1, - 'numeric' => 'string', - 'required' => null, - 'email' => 'email' - ]; - $rules = [ - 'string' => 'string', - 'numeric' => 'numeric', - 'required' => 'required', - 'email' => 'email' - ]; - - foreach ($data as $key => $value) { - $violations = $validator->validate($value, [$key => $rules[$key]]); - $this->assertSame(1, $violations->count()); - } - } - - /** - * @expectedException \Directus\Validator\Exception\UnknownConstraintException - */ - public function testUnknownConstraint() - { - $validator = new Validator(); - - $validator->validate(['data' => 1], ['data' => 'boolean']); - } -} diff --git a/tests/api/functionsTest.php b/tests/api/functionsTest.php deleted file mode 100644 index e460fe82ff..0000000000 --- a/tests/api/functionsTest.php +++ /dev/null @@ -1,566 +0,0 @@ -assertSame($expected, uc_convert($text)); - } - - public function testGetURL() - { - $url = get_url(); - $this->assertSame('http://localhost/', $url); - - $_SERVER['HTTP_HOST'] = 'localhost'; - - $url = get_url(); - $this->assertSame('http://localhost/', $url); - - $url = get_url('/users'); - $this->assertSame('http://localhost/users', $url); - } - - public function testFind() - { - $array = [ - ['name' => 'john', 'age' => 1], - ['name' => 'jane', 'age' => 2], - ]; - - $result = find($array, 'name', 'john'); - $this->assertSame('john', $result['name']); - $this->assertNull(find($array, 'name', 'peter')); - } - - public function testToNameValue() - { - $array = [ - 'john' => 2300, - 'peter' => 330 - ]; - - $result = to_name_value($array, null); - $expected = [ - ['name' => 'john', 'value' => 2300], - ['name' => 'peter', 'value' => 330] - ]; - $this->assertSame($expected, $result); - - $result = to_name_value($array, ['status' => 1]); - $expected = [ - ['name' => 'john', 'value' => 2300, 'status' => 1], - ['name' => 'peter', 'value' => 330, 'status' => 1] - ]; - $this->assertSame($expected, $result); - } - - public function testIsNumericKeyArray() - { - $array = [ - 'name', - 'age', - 'country' - ]; - - $this->assertTrue(is_numeric_keys_array($array)); - $this->assertFalse(is_numeric_keys_array([ - 'name' => 'john', - 'age' => 1, - 'country' => 'yes' - ])); - } - - public function testTimezoneList() - { - $timezones = get_timezone_list(); - - $this->assertInternalType('array', $timezones); - } - - public function testShorthandSize() - { - $this->assertSame(1 * MB_IN_BYTES, convert_shorthand_size_to_bytes('1m')); - $this->assertSame(1 * MB_IN_BYTES, convert_shorthand_size_to_bytes('1m')); - $this->assertSame(1 * KB_IN_BYTES, convert_shorthand_size_to_bytes('1k')); - $this->assertSame(1 * KB_IN_BYTES, convert_shorthand_size_to_bytes('1K')); - $this->assertSame(1 * GB_IN_BYTES, convert_shorthand_size_to_bytes('1g')); - $this->assertSame(1 * GB_IN_BYTES, convert_shorthand_size_to_bytes('1G')); - } - - public function testGetMaxUploadSize() - { - $this->assertTrue(is_int(get_max_upload_size())); - } - - public function testFindDirectories() - { - $this->createTempDirs(); - - $directories = find_directories($this->path); - - $this->assertSame(3, count($directories)); - - $this->removeTempDirs(); - } - - public function testFindFiles() - { - $this->createTempFiles(); - $path = $this->path; - - $filesFound = find_files($path, 0, '*'); - $this->assertSame(9, count($filesFound)); - - $jsFilesFound = find_js_files($path); - $this->assertSame(2, count($jsFilesFound)); - - $htmlFilesFound = find_html_files($path); - $this->assertSame(2, count($htmlFilesFound)); - - $twigFilesFound = find_twig_files($path); - $this->assertSame(2, count($twigFilesFound)); - - $phpFilesFound = find_php_files($path); - $this->assertSame(2, count($phpFilesFound)); - - // Including subdirectories - $filesFound = find_files($path, 0, '*', true); - $this->assertSame(13, count($filesFound)); - - $jsFilesFound = find_js_files($path, true); - $this->assertSame(3, count($jsFilesFound)); - - $htmlFilesFound = find_html_files($path, true); - $this->assertSame(3, count($htmlFilesFound)); - - $twigFilesFound = find_twig_files($path, true); - $this->assertSame(3, count($twigFilesFound)); - - $phpFilesFound = find_php_files($path, true); - $this->assertSame(3, count($phpFilesFound)); - - $this->removeTempFiles(); - } - - public function testGetGravatar() - { - $email = 'admin@localhost'; - $s = 200; - $d = 'identicon'; - $r = 'g'; - $avatarURL = get_gravatar($email, $s, $d, $r); - $expected = '//www.gravatar.com/avatar/' . md5($email) . "?s=$s&d=$d&r=$r"; - - $this->assertSame($expected, $avatarURL); - - $avatarImg = get_gravatar($email, $s, $d, $r, true); - $this->assertSame('', $avatarImg); - - $avatarImg = get_gravatar($email, $s, $d, $r, true, ['alt' => 'image']); - $this->assertSame('image', $avatarImg); - } - - public function testNormalizePath() - { - // From WordPress tests - // NOTE: Comment out the disk letter as we don't support that part from the borrow function - // if we end up doing it, we have the tests - $paths = array( - '/WINDOWS' => '/WINDOWS', - // 'C:/' => 'C:/', - // 'C:/WINDOWS' => 'C:/WINDOWS', - // 'C:/WINDOWS/system32' => 'C:/WINDOWS/system32', - '\\WINDOWS' => '/WINDOWS', - // 'C:\\' => 'C:/', - // 'C:\\WINDOWS' => 'C:/WINDOWS', - // 'C:\\\\WINDOWS' => 'C:/WINDOWS', - // 'C:\\WINDOWS\\system32' => 'C:/WINDOWS/system32', - '\\\\sambashare\\foo' => '/sambashare/foo', - // 'c:/windows' => 'C:/windows', - // 'c:\\windows' => 'C:/windows', - ); - - foreach ($paths as $original => $expected) { - $this->assertEquals($expected, normalize_path($original)); - } - } - - public function testColumnIdentifierReverse() - { - $original = 'posts.comments.author.email'; - $expected = 'email.author.comments.posts'; - - $this->assertSame($expected, column_identifier_reverse($original)); - $this->assertSame('name', column_identifier_reverse('name')); - } - - public function testCompactSortToArray() - { - $this->assertSame(['title' => 'ASC'], compact_sort_to_array('title')); - $this->assertSame(['title' => 'DESC'], compact_sort_to_array('-title')); - $this->expectException(\Directus\Exception\Exception::class); - compact_sort_to_array(['title' => 'ASC']); - } - - public function testDefineConstant() - { - $this->assertFalse(defined('A_RANDOM_CONSTANT')); - $defined = define_constant('A_RANDOM_CONSTANT', 1); - $this->assertFalse($defined); - $this->assertTrue(defined('A_RANDOM_CONSTANT')); - $this->assertSame(1, A_RANDOM_CONSTANT); - $defined = define_constant('A_RANDOM_CONSTANT', 2); - $this->assertTrue($defined); - $this->assertSame(1, A_RANDOM_CONSTANT); - } - - public function testArrayDeep() - { - $array1 = [ - 'one', - 'two', - 'three' - ]; - - $this->assertSame(0, \Directus\Util\ArrayUtils::deepLevel($array1)); - - $array2 = [ - 'one', - 'two', - 'three' => [ - 'threed', - '3d', - 'triple' - ], - 'four' => [ - 'for', - '4' - ] - ]; - - $this->assertSame(1, \Directus\Util\ArrayUtils::deepLevel($array2)); - - $array3 = [ - 'one', - 'two', - 'three' => [ - 'threed', - '3d' => [ - '4d' - ], - 'triple' - ], - - ]; - - $this->assertSame(2, \Directus\Util\ArrayUtils::deepLevel($array3)); - } - - public function testGetColumnsFlatAt() - { - $columns = [ - 'zero-0', - 'zero-1.one-1', - 'zero-2', - 'zero-3.one-1.two-1', - 'zero-3.one-2' - ]; - - $this->assertSame([ - 'zero-0', - 'zero-1', - 'zero-2', - 'zero-3', - 'zero-3' - ], get_columns_flat_at($columns, 0)); - - $this->assertSame([ - 'one-1', - 'one-1', - 'one-2' - ], get_columns_flat_at($columns, 1)); - - $this->assertSame([ - 'two-1' - ], get_columns_flat_at($columns, 2)); - - $this->assertCount(5, get_columns_flat_at($columns, 0)); - $this->assertCount(3, get_columns_flat_at($columns, 1)); - $this->assertCount(1, get_columns_flat_at($columns, 2)); - } - - public function testGetFlatColumns() - { - $original = [ - 'one' => null, - 'two' => null, - 'three' => [ - 'threed' => null, - '3d' => null, - 'triple' => null, - '3ple' => [ - 'double' => null - ] - ], - 'four' => [ - 'for' => null, - '4' => null - ] - ]; - - $expected = [ - 'one', - 'two', - 'three.threed', - 'three.3d', - 'three.triple', - 'three.3ple.double', - 'four.for', - 'four.4' - ]; - - $this->assertSame($expected, get_array_flat_columns($original)); - $this->assertSame(implode(',', $expected), get_csv_flat_columns($original)); - } - - public function testGetUnflatColumns() - { - $original = [ - 'one', - 'two', - 'three.threed', - 'three.3d', - 'three.triple', - 'three.3ple.double', - 'four.for', - 'four.4' - ]; - - $expected = [ - 'one' => null, - 'two' => null, - 'three' => [ - 'threed' => null, - '3d' => null, - 'triple' => null, - '3ple' => [ - 'double' => null - ] - ], - 'four' => [ - 'for' => null, - '4' => null - ] - ]; - - $this->assertSame($expected, get_unflat_columns($original)); - $this->assertSame($expected, get_unflat_columns(implode(',', $original))); - } - - public function testSlugify() - { - $original = 'ÁÄÂÀÃÅČÇĆĎÉĚËÈÊẼĔȆÍÌÎÏŇÑÓÖÒÔÕØŘŔŠŤÚŮÜÙÛÝŸŽáäâàãåčçćďéěëèêẽĕȇíìîïňñóöòôõøðřŕšťúůüùûýÿžþÞĐđßÆa·/_,:;'; - $expected = 'aaaaaacccdeeeeeeeeiiiinnoooooorrstuuuuuyyzaaaaaacccdeeeeeeeeiiiinnooooooorrstuuuuuyyzbbddbaa-'; - - $this->assertSame($expected, slugify($original)); - } - - public function testPingRoute() - { - $env = \Slim\Http\Environment::mock([ - 'SCRIPT_NAME' => '/index.php', - 'REQUEST_URI' => '/ping', - 'REQUEST_METHOD' => 'GET', - ]); - $uri = \Slim\Http\Uri::createFromEnvironment($env); - $headers = \Slim\Http\Headers::createFromEnvironment($env); - $cookies = []; - $serverParams = $env->all(); - $body = new \Slim\Http\Body(fopen('php://temp', 'r+')); - $req = new \Directus\Application\Http\Request('GET', $uri, $headers, $cookies, $serverParams, $body); - $res = new \Directus\Application\Http\Response(); - - $app = create_ping_server(); - $app->getContainer()['request'] = $req; - $app->getContainer()['response'] = $res; - $resOut = $app($req, $res); - - $this->assertEmpty($resOut->getBody()->getContents()); - $this->assertSame(404, $resOut->getStatusCode()); - } - - public function testPingRouteProduction() - { - $env = \Slim\Http\Environment::mock([ - 'SCRIPT_NAME' => '/index.php', - 'REQUEST_URI' => '/ping', - 'REQUEST_METHOD' => 'GET', - ]); - $uri = \Slim\Http\Uri::createFromEnvironment($env); - $headers = \Slim\Http\Headers::createFromEnvironment($env); - $cookies = []; - $serverParams = $env->all(); - $body = new \Slim\Http\Body(fopen('php://temp', 'r+')); - $req = new \Directus\Application\Http\Request('GET', $uri, $headers, $cookies, $serverParams, $body); - $res = new \Directus\Application\Http\Response(); - - $app = create_ping_server([ - 'settings' => [ - 'debug' => false, - 'env' => 'development' - ] - ]); - $app->getContainer()['request'] = $req; - $app->getContainer()['response'] = $res; - ob_start(); - $app->run(); - $resOut = ob_get_clean(); - - $this->assertSame('pong', $resOut); - } - - public function testPingServer() - { - $this->assertInternalType('bool', ping_server()); - } - - public function testConvertParamColumn() - { - $this->assertInternalType('array', convert_param_columns([])); - $this->assertInternalType('array', convert_param_columns(['one'])); - $this->assertInternalType('array', convert_param_columns(['one', 'two'])); - $this->assertInternalType('array', convert_param_columns('')); - $this->assertInternalType('array', convert_param_columns('one')); - $this->assertInternalType('array', convert_param_columns('one,two')); - $this->assertInternalType('array', convert_param_columns(null)); - $this->assertInternalType('array', convert_param_columns(false)); - $this->assertInternalType('array', convert_param_columns(1)); - } - - protected $files = [ - 'file.js', - 'module.js', - 'dir/index.js', - 'file.php', - 'module.php', - 'dir/index.php', - 'file.html', - 'file.twig', - 'module.html', - 'module.twig', - 'dir/index.html', - 'dir/index.twig', - ]; - - protected $path; - - public function setUp() - { - $this->path = __DIR__ . '/tmp'; - - $this->removeTempFiles(); - $this->removeTempDirs(); - } - - protected function createTempDirs() - { - $path = $this->path; - $dirs = ['one', 'two', 'three']; - $subs = ['a', 'b', 'c', '_d', '_e']; - - // create the directory - mkdir($path); - file_put_contents($path . '/ignore1', ''); - file_put_contents($path . '/ignore2', ''); - - // create subdirectories - foreach ($dirs as $dir) { - $dir = $path . '/' . $dir; - mkdir($dir); - - foreach ($subs as $sub) { - mkdir($dir . '/' . $sub); - } - } - } - - protected function removeTempDirs() - { - $path = $this->path; - $dirs = ['one', 'two', 'three']; - $subs = ['a', 'b', 'c', '_d', '_e']; - - // remove the directories - foreach ($dirs as $dir) { - $dir = $path . '/' . $dir; - - // make sure to remove the subdirectory first - // rmdir only remove empty directories - foreach ($subs as $sub) { - $subdir = $dir . '/' . $sub; - if (is_dir($subdir)) { - rmdir($subdir); - } - } - - if (is_dir($dir)) { - rmdir($dir); - } - } - - // remove files - if (file_exists($path . '/ignore1')) { - unlink($path . '/ignore1'); - } - - if (file_exists($path . '/ignore2')) { - unlink($path . '/ignore2'); - } - - // remove main directory - if (is_dir($path)) { - rmdir($path); - } - } - - protected function createTempFiles() - { - $path = $this->path; - $files = $this->files; - - if (is_dir($path)) { - $this->removeTempFiles(); - } - - mkdir($path); - mkdir($path . '/dir'); - - foreach ($files as $file) { - file_put_contents($path . '/' . $file, ''); - } - } - - protected function removeTempFiles() - { - $path = $this->path; - $files = $this->files; - - foreach ($files as $file) { - $filePath = $path . '/' . $file; - if (file_exists($filePath)) { - unlink($filePath); - } - } - - if (is_dir($path . '/dir')) { - rmdir($path . '/dir'); - } - - if (is_dir($path)) { - rmdir($path); - } - } -} diff --git a/tests/assets/image.jpeg b/tests/assets/image.jpeg deleted file mode 100644 index 143bfd88a72a8a75db0e1feb5db7c6f1b1c17093..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 407 zcmchSOAdlS42D~VVa7m!@(zKSNVta!6B0d<$MGDlTzCi{8*efeSK`i%Uy~;N)5l+T zbx%n5({2Jp0OSDofGtSj`@WEzq?Cb*v|^GlTt$>*86`w{)zx{?mPF0EY5U$#W$WVuM$`w~_wWR|K_b2ojd X{P!IqfqX|0Y~bXD(Q@uzm2$Ti>lP!` diff --git a/tests/assets/travis-ci-apache b/tests/assets/travis-ci-apache deleted file mode 100644 index 72b26e2ebd..0000000000 --- a/tests/assets/travis-ci-apache +++ /dev/null @@ -1,21 +0,0 @@ - - DocumentRoot %TRAVIS_BUILD_DIR%/public - - - Options FollowSymLinks MultiViews ExecCGI - AllowOverride All - Require all granted - - - # Wire up Apache to use Travis CI's php-fpm. - - AddHandler php5-fcgi .php - Action php5-fcgi /php5-fcgi - Alias /php5-fcgi /usr/lib/cgi-bin/php5-fcgi - FastCgiExternalServer /usr/lib/cgi-bin/php5-fcgi -host 127.0.0.1:9000 -pass-header Authorization - - - Require all granted - - - diff --git a/tests/db.sql b/tests/db.sql deleted file mode 100644 index c454630369..0000000000 --- a/tests/db.sql +++ /dev/null @@ -1,797 +0,0 @@ -# ************************************************************ -# Sequel Pro SQL dump -# Version 4541 -# -# http://www.sequelpro.com/ -# https://github.com/sequelpro/sequelpro -# -# Host: localhost (MySQL 5.6.38) -# Database: directus_test -# Generation Time: 2019-01-04 14:42:43 +0000 -# ************************************************************ - - -/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; -/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; -/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; -/*!40101 SET NAMES utf8 */; -/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; -/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; -/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; - - -# Dump of table categories -# ------------------------------------------------------------ - -DROP TABLE IF EXISTS `categories`; - -CREATE TABLE `categories` ( - `id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `name` varchar(100) CHARACTER SET utf8mb4 NOT NULL DEFAULT '', - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - -LOCK TABLES `categories` WRITE; -/*!40000 ALTER TABLE `categories` DISABLE KEYS */; - -INSERT INTO `categories` (`id`, `name`) -VALUES - (1,'Old Category'); - -/*!40000 ALTER TABLE `categories` ENABLE KEYS */; -UNLOCK TABLES; - -# Dump of table directus_activity -# ------------------------------------------------------------ - -DROP TABLE IF EXISTS `directus_activity`; - -CREATE TABLE `directus_activity` ( - `id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `action` varchar(45) NOT NULL, - `action_by` int(11) unsigned NOT NULL DEFAULT '0', - `action_on` datetime NOT NULL, - `ip` varchar(50) NOT NULL, - `user_agent` varchar(255) NOT NULL, - `collection` varchar(64) NOT NULL, - `item` varchar(255) NOT NULL, - `edited_on` datetime DEFAULT NULL, - `comment` text, - `comment_deleted_on` datetime DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - - - -# Dump of table directus_activity_seen -# ------------------------------------------------------------ - -DROP TABLE IF EXISTS `directus_activity_seen`; - -CREATE TABLE `directus_activity_seen` ( - `id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `activity` int(11) unsigned NOT NULL, - `user` int(11) unsigned NOT NULL DEFAULT '0', - `seen_on` datetime DEFAULT NULL, - `archived` tinyint(1) unsigned NOT NULL DEFAULT '0', - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - - - -# Dump of table directus_collection_presets -# ------------------------------------------------------------ - -DROP TABLE IF EXISTS `directus_collection_presets`; - -CREATE TABLE `directus_collection_presets` ( - `id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `title` varchar(255) DEFAULT NULL, - `user` int(11) unsigned DEFAULT NULL, - `role` int(11) unsigned DEFAULT NULL, - `collection` varchar(64) NOT NULL, - `search_query` varchar(100) DEFAULT NULL, - `filters` text, - `view_type` varchar(100) NOT NULL DEFAULT 'tabular', - `view_query` text, - `view_options` text, - `translation` text, - PRIMARY KEY (`id`), - UNIQUE KEY `idx_user_collection_title` (`user`,`collection`,`title`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - -LOCK TABLES `directus_collection_presets` WRITE; -/*!40000 ALTER TABLE `directus_collection_presets` DISABLE KEYS */; - -INSERT INTO `directus_collection_presets` (`id`, `title`, `user`, `role`, `collection`, `search_query`, `filters`, `view_type`, `view_query`, `view_options`, `translation`) -VALUES - (1,NULL,NULL,NULL,'directus_activity',NULL,NULL,'tabular','{\"tabular\":{\"sort\":\"-action_on\",\"fields\":\"action,action_by,action_on,collection,item\"}}','{\"tabular\":{\"widths\":{\"action\":170,\"action_by\":170,\"action_on\":180,\"collection\":200,\"item\":200}}}',NULL), - (2,NULL,NULL,NULL,'directus_files',NULL,NULL,'cards',NULL,'{\"cards\":{\"title\":\"title\",\"subtitle\":\"type\",\"content\":\"description\",\"src\":\"data\"}}',NULL), - (3,NULL,NULL,NULL,'directus_users',NULL,NULL,'cards',NULL,'{\"cards\":{\"title\":\"first_name\",\"subtitle\":\"last_name\",\"content\":\"title\",\"src\":\"avatar\",\"icon\":\"person\"}}',NULL); - -/*!40000 ALTER TABLE `directus_collection_presets` ENABLE KEYS */; -UNLOCK TABLES; - - -# Dump of table directus_collections -# ------------------------------------------------------------ - -DROP TABLE IF EXISTS `directus_collections`; - -CREATE TABLE `directus_collections` ( - `collection` varchar(64) NOT NULL, - `managed` tinyint(1) unsigned NOT NULL DEFAULT '1', - `hidden` tinyint(1) unsigned NOT NULL DEFAULT '0', - `single` tinyint(1) unsigned NOT NULL DEFAULT '0', - `icon` varchar(30) DEFAULT NULL, - `note` varchar(255) DEFAULT NULL, - `translation` text, - PRIMARY KEY (`collection`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - -LOCK TABLES `directus_collections` WRITE; -/*!40000 ALTER TABLE `directus_collections` DISABLE KEYS */; - -INSERT INTO `directus_collections` (`collection`, `managed`, `hidden`, `single`, `icon`, `note`, `translation`) -VALUES - ('home',1,0,0,NULL,NULL,NULL), - ('home_news',1,0,0,NULL,NULL,NULL), - ('languages',1,0,0,NULL,NULL,NULL), - ('news',1,0,0,NULL,NULL,NULL), - ('news_translations',1,0,0,NULL,NULL,NULL); - -/*!40000 ALTER TABLE `directus_collections` ENABLE KEYS */; -UNLOCK TABLES; - -# Dump of table directus_fields -# ------------------------------------------------------------ - -DROP TABLE IF EXISTS `directus_fields`; - -CREATE TABLE `directus_fields` ( - `id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `collection` varchar(64) NOT NULL, - `field` varchar(64) NOT NULL, - `type` varchar(64) NOT NULL, - `interface` varchar(64) DEFAULT NULL, - `options` text, - `locked` tinyint(1) unsigned NOT NULL DEFAULT '0', - `validation` varchar(255) DEFAULT NULL, - `required` tinyint(1) unsigned NOT NULL DEFAULT '0', - `readonly` tinyint(1) unsigned NOT NULL DEFAULT '0', - `hidden_detail` tinyint(1) unsigned NOT NULL DEFAULT '0', - `hidden_browse` tinyint(1) unsigned NOT NULL DEFAULT '0', - `sort` int(11) unsigned DEFAULT NULL, - `width` int(11) unsigned NOT NULL DEFAULT '4', - `group` int(11) unsigned DEFAULT NULL, - `note` varchar(1024) DEFAULT NULL, - `translation` text, - PRIMARY KEY (`id`), - UNIQUE KEY `idx_collection_field` (`collection`,`field`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - -LOCK TABLES `directus_fields` WRITE; -/*!40000 ALTER TABLE `directus_fields` DISABLE KEYS */; - -INSERT INTO `directus_fields` (`id`, `collection`, `field`, `type`, `interface`, `options`, `locked`, `validation`, `required`, `readonly`, `hidden_detail`, `hidden_browse`, `sort`, `width`, `group`, `note`, `translation`) -VALUES - (1,'directus_activity','id','integer','primary-key',NULL,1,NULL,1,1,1,0,NULL,4,NULL,NULL,NULL), - (2,'directus_activity','action','string','activity-icon',NULL,1,NULL,0,1,0,0,1,4,NULL,NULL,NULL), - (3,'directus_activity','collection','string','collections',NULL,1,NULL,0,1,0,0,2,2,NULL,NULL,NULL), - (4,'directus_activity','item','string','text-input',NULL,1,NULL,0,1,0,0,3,2,NULL,NULL,NULL), - (5,'directus_activity','action_by','integer','user',NULL,1,NULL,0,1,0,0,4,2,NULL,NULL,NULL), - (6,'directus_activity','action_on','datetime','datetime','{\"showRelative\":true}',1,NULL,0,1,0,0,5,2,NULL,NULL,NULL), - (7,'directus_activity','edited_on','datetime','datetime','{\"showRelative\":true}',1,NULL,0,1,0,0,6,2,NULL,NULL,NULL), - (8,'directus_activity','comment_deleted_on','datetime','datetime','{\"showRelative\":true}',1,NULL,0,1,0,0,7,2,NULL,NULL,NULL), - (9,'directus_activity','ip','string','text-input',NULL,1,NULL,0,1,0,0,8,2,NULL,NULL,NULL), - (10,'directus_activity','user_agent','string','text-input',NULL,1,NULL,0,1,0,0,9,2,NULL,NULL,NULL), - (11,'directus_activity','comment','string','textarea',NULL,1,NULL,0,1,0,0,10,4,NULL,NULL,NULL), - (12,'directus_collection_presets','id','integer','primary-key',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (13,'directus_collection_presets','title','string','text-input',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (14,'directus_collection_presets','user','integer','user',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (15,'directus_collection_presets','role','m2o','many-to-one',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (16,'directus_collection_presets','collection','m2o','many-to-one',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (17,'directus_collection_presets','search_query','string','text-input',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (18,'directus_collection_presets','filters','json','code',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (19,'directus_collection_presets','view_options','json','code',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (20,'directus_collection_presets','view_type','string','text-input',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (21,'directus_collection_presets','view_query','json','code',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (22,'directus_collections','fields','o2m','one-to-many',NULL,1,NULL,0,0,1,1,1,4,NULL,NULL,NULL), - (23,'directus_collections','collection','string','primary-key',NULL,1,NULL,1,1,0,0,2,2,NULL,NULL,NULL), - (24,'directus_collections','note','string','text-input',NULL,1,NULL,0,0,0,0,3,2,NULL,NULL,NULL), - (25,'directus_collections','managed','boolean','toggle',NULL,1,NULL,0,0,0,0,4,1,NULL,NULL,NULL), - (26,'directus_collections','hidden','boolean','toggle',NULL,1,NULL,0,0,0,0,5,1,NULL,NULL,NULL), - (27,'directus_collections','single','boolean','toggle',NULL,1,NULL,0,0,0,0,6,1,NULL,NULL,NULL), - (28,'directus_collections','translation','json','code',NULL,1,NULL,0,0,1,0,7,4,NULL,NULL,NULL), - (29,'directus_collections','icon','string','icon',NULL,1,NULL,0,0,0,0,8,4,NULL,NULL,NULL), - (30,'directus_fields','id','integer','primary-key',NULL,1,NULL,1,0,1,0,NULL,4,NULL,NULL,NULL), - (31,'directus_fields','collection','m2o','many-to-one',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (32,'directus_fields','field','string','text-input',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (33,'directus_fields','type','string','primary-key',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (34,'directus_fields','interface','string','primary-key',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (35,'directus_fields','options','json','code',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (36,'directus_fields','locked','boolean','toggle',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (37,'directus_fields','translation','json','code',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (38,'directus_fields','readonly','boolean','toggle',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (39,'directus_fields','validation','string','text-input',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (40,'directus_fields','required','boolean','toggle',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (41,'directus_fields','sort','sort','sort',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (42,'directus_fields','note','string','text-input',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (43,'directus_fields','hidden_detail','boolean','toggle',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (44,'directus_fields','hidden_browse','boolean','toggle',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (45,'directus_fields','width','integer','numeric',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (46,'directus_fields','group','m2o','many-to-one',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (47,'directus_files','data','alias','file',NULL,1,NULL,0,0,1,0,0,4,NULL,NULL,NULL), - (48,'directus_files','id','integer','primary-key',NULL,1,NULL,1,0,1,0,1,4,NULL,NULL,NULL), - (49,'directus_files','preview','alias','file-preview',NULL,1,NULL,0,0,0,0,2,4,NULL,NULL,NULL), - (50,'directus_files','title','string','text-input','{\"placeholder\":\"Enter a descriptive title...\",\"iconRight\":\"title\"}',1,NULL,0,0,0,0,3,2,NULL,NULL,NULL), - (51,'directus_files','filename','string','text-input','{\"placeholder\":\"Enter a unique file name...\",\"iconRight\":\"insert_drive_file\"}',1,NULL,0,1,0,0,4,2,NULL,NULL,NULL), - (52,'directus_files','tags','array','tags',NULL,0,NULL,0,0,0,0,5,2,NULL,NULL,NULL), - (53,'directus_files','location','string','text-input','{\"placeholder\":\"Enter a location...\",\"iconRight\":\"place\"}',0,NULL,0,0,0,0,6,2,NULL,NULL,NULL), - (54,'directus_files','description','string','wysiwyg','{\"placeholder\":\"Enter a caption or description...\"}',0,NULL,0,0,0,0,7,4,NULL,NULL,NULL), - (55,'directus_files','width','integer','numeric','{\"iconRight\":\"straighten\"}',1,NULL,0,1,0,0,8,1,NULL,NULL,NULL), - (56,'directus_files','height','integer','numeric','{\"iconRight\":\"straighten\"}',1,NULL,0,1,0,0,9,1,NULL,NULL,NULL), - (57,'directus_files','duration','integer','numeric','{\"iconRight\":\"timer\"}',1,NULL,0,1,0,0,10,1,NULL,NULL,NULL), - (58,'directus_files','filesize','integer','file-size','{\"iconRight\":\"storage\"}',1,NULL,0,1,0,0,11,1,NULL,NULL,NULL), - (59,'directus_files','uploaded_on','datetime','datetime','{\"iconRight\":\"today\"}',1,NULL,0,1,0,0,12,2,NULL,NULL,NULL), - (60,'directus_files','uploaded_by','integer','user',NULL,1,NULL,0,1,0,0,13,2,NULL,NULL,NULL), - (61,'directus_files','metadata','json','code',NULL,1,NULL,0,0,0,0,14,4,NULL,NULL,NULL), - (62,'directus_files','type','string','text-input',NULL,1,NULL,0,1,1,0,NULL,4,NULL,NULL,NULL), - (63,'directus_files','charset','string','text-input',NULL,1,NULL,0,1,1,1,NULL,4,NULL,NULL,NULL), - (64,'directus_files','embed','string','text-input',NULL,1,NULL,0,1,1,0,NULL,4,NULL,NULL,NULL), - (65,'directus_files','folder','m2o','many-to-one',NULL,1,NULL,0,0,1,0,NULL,4,NULL,NULL,NULL), - (66,'directus_files','storage','string','text-input',NULL,1,NULL,0,0,1,1,NULL,4,NULL,NULL,NULL), - (67,'directus_folders','id','integer','primary-key',NULL,1,NULL,1,0,1,0,NULL,4,NULL,NULL,NULL), - (68,'directus_folders','name','string','text-input',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (69,'directus_folders','parent_folder','m2o','many-to-one',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (70,'directus_permissions','id','integer','primary-key',NULL,1,NULL,1,0,1,0,NULL,4,NULL,NULL,NULL), - (71,'directus_permissions','collection','m2o','many-to-one',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (72,'directus_permissions','role','m2o','many-to-one',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (73,'directus_permissions','status','string','text-input',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (74,'directus_permissions','create','string','text-input',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (75,'directus_permissions','read','string','text-input',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (76,'directus_permissions','update','string','text-input',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (77,'directus_permissions','delete','string','primary-key',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (78,'directus_permissions','comment','string','text-input',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (79,'directus_permissions','explain','string','text-input',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (80,'directus_permissions','status_blacklist','array','tags',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (81,'directus_permissions','read_field_blacklist','array','tags',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (82,'directus_permissions','write_field_blacklist','array','tags',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (83,'directus_relations','id','integer','primary-key',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (84,'directus_relations','collection_many','string','collections',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (85,'directus_relations','field_many','string','text-input',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (86,'directus_relations','collection_one','string','collections',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (87,'directus_relations','field_one','string','text-input',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (88,'directus_relations','junction_field','string','text-input',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (89,'directus_revisions','id','integer','primary-key',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (90,'directus_revisions','activity','m2o','many-to-one',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (91,'directus_revisions','collection','m2o','many-to-one',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (92,'directus_revisions','item','string','text-input',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (93,'directus_revisions','data','json','code',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (94,'directus_revisions','delta','json','code',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (95,'directus_revisions','parent_item','string','text-input',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (96,'directus_revisions','parent_collection','string','collections',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (97,'directus_revisions','parent_changed','boolean','toggle',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (98,'directus_roles','id','integer','primary-key',NULL,1,NULL,1,0,1,0,NULL,4,NULL,NULL,NULL), - (99,'directus_roles','external_id','string','text-input',NULL,1,NULL,0,1,1,1,NULL,4,NULL,NULL,NULL), - (100,'directus_roles','name','string','text-input',NULL,1,NULL,0,0,0,0,1,2,NULL,NULL,NULL), - (101,'directus_roles','description','string','text-input',NULL,1,NULL,0,0,0,0,2,2,NULL,NULL,NULL), - (102,'directus_roles','ip_whitelist','string','textarea',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (103,'directus_roles','nav_blacklist','string','textarea',NULL,1,NULL,0,0,1,1,NULL,4,NULL,NULL,NULL), - (104,'directus_settings','auto_sign_out','integer','numeric',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (105,'directus_settings','logo','file','file',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (106,'directus_settings','color','string','color-palette',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (107,'directus_settings','trusted_proxies','string','tags',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (108,'directus_settings','project_url','string','text-input',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (109,'directus_users','id','integer','primary-key',NULL,1,NULL,1,0,1,0,1,4,NULL,NULL,NULL), - (110,'directus_users','status','status','status','{\"status_mapping\":{\"draft\":{\"name\":\"Draft\",\"text_color\":\"white\",\"background_color\":\"light-gray\",\"listing_subdued\":false,\"listing_badge\":true,\"soft_delete\":false},\"invited\":{\"name\":\"Invited\",\"text_color\":\"white\",\"background_color\":\"light-gray\",\"listing_subdued\":false,\"listing_badge\":true,\"soft_delete\":false},\"active\":{\"name\":\"Active\",\"text_color\":\"white\",\"background_color\":\"success\",\"listing_subdued\":false,\"listing_badge\":false,\"soft_delete\":false},\"suspended\":{\"name\":\"Suspended\",\"text_color\":\"white\",\"background_color\":\"light-gray\",\"listing_subdued\":false,\"listing_badge\":true,\"soft_delete\":false},\"deleted\":{\"name\":\"Deleted\",\"text_color\":\"white\",\"background_color\":\"danger\",\"listing_subdued\":false,\"listing_badge\":true,\"soft_delete\":true}}}',1,NULL,0,0,0,0,2,4,NULL,NULL,NULL), - (111,'directus_users','first_name','string','text-input','{\"placeholder\":\"Enter your give name...\"}',1,NULL,1,0,0,0,3,2,NULL,NULL,NULL), - (112,'directus_users','last_name','string','text-input','{\"placeholder\":\"Enter your surname...\"}',1,NULL,1,0,0,0,4,2,NULL,NULL,NULL), - (113,'directus_users','email','string','text-input','{\"placeholder\":\"Enter your email address...\"}',1,NULL,1,0,0,0,5,2,NULL,NULL,NULL), - (114,'directus_users','email_notifications','boolean','toggle',NULL,1,NULL,0,0,0,0,6,2,NULL,NULL,NULL), - (115,'directus_users','password','string','password',NULL,1,NULL,1,0,0,0,7,2,NULL,NULL,NULL), - (116,'directus_users','roles','o2m','user-roles',NULL,1,NULL,0,0,0,0,8,2,NULL,NULL,NULL), - (117,'directus_users','company','string','text-input','{\"placeholder\":\"Enter your company or organization name...\"}',0,NULL,0,0,0,0,9,2,NULL,NULL,NULL), - (118,'directus_users','title','string','text-input','{\"placeholder\":\"Enter your title or role...\"}',0,NULL,0,0,0,0,10,2,NULL,NULL,NULL), - (119,'directus_users','timezone','string','dropdown','{\"choices\":{\"Pacific\\/Midway\":\"(UTC-11:00) Midway Island\",\"Pacific\\/Samoa\":\"(UTC-11:00) Samoa\",\"Pacific\\/Honolulu\":\"(UTC-10:00) Hawaii\",\"US\\/Alaska\":\"(UTC-09:00) Alaska\",\"America\\/Los_Angeles\":\"(UTC-08:00) Pacific Time (US & Canada)\",\"America\\/Tijuana\":\"(UTC-08:00) Tijuana\",\"US\\/Arizona\":\"(UTC-07:00) Arizona\",\"America\\/Chihuahua\":\"(UTC-07:00) Chihuahua\",\"America\\/Mexico\\/La_Paz\":\"(UTC-07:00) La Paz\",\"America\\/Mazatlan\":\"(UTC-07:00) Mazatlan\",\"US\\/Mountain\":\"(UTC-07:00) Mountain Time (US & Canada)\",\"America\\/Managua\":\"(UTC-06:00) Central America\",\"US\\/Central\":\"(UTC-06:00) Central Time (US & Canada)\",\"America\\/Guadalajara\":\"(UTC-06:00) Guadalajara\",\"America\\/Mexico_City\":\"(UTC-06:00) Mexico City\",\"America\\/Monterrey\":\"(UTC-06:00) Monterrey\",\"Canada\\/Saskatchewan\":\"(UTC-06:00) Saskatchewan\",\"America\\/Bogota\":\"(UTC-05:00) Bogota\",\"US\\/Eastern\":\"(UTC-05:00) Eastern Time (US & Canada)\",\"US\\/East-Indiana\":\"(UTC-05:00) Indiana (East)\",\"America\\/Lima\":\"(UTC-05:00) Lima\",\"America\\/Quito\":\"(UTC-05:00) Quito\",\"Canada\\/Atlantic\":\"(UTC-04:00) Atlantic Time (Canada)\",\"America\\/New_York\":\"(UTC-04:00) New York\",\"America\\/Caracas\":\"(UTC-04:30) Caracas\",\"America\\/La_Paz\":\"(UTC-04:00) La Paz\",\"America\\/Santiago\":\"(UTC-04:00) Santiago\",\"America\\/Santo_Domingo\":\"(UTC-04:00) Santo Domingo\",\"Canada\\/Newfoundland\":\"(UTC-03:30) Newfoundland\",\"America\\/Sao_Paulo\":\"(UTC-03:00) Brasilia\",\"America\\/Argentina\\/Buenos_Aires\":\"(UTC-03:00) Buenos Aires\",\"America\\/Argentina\\/GeorgeTown\":\"(UTC-03:00) Georgetown\",\"America\\/Godthab\":\"(UTC-03:00) Greenland\",\"America\\/Noronha\":\"(UTC-02:00) Mid-Atlantic\",\"Atlantic\\/Azores\":\"(UTC-01:00) Azores\",\"Atlantic\\/Cape_Verde\":\"(UTC-01:00) Cape Verde Is.\",\"Africa\\/Casablanca\":\"(UTC+00:00) Casablanca\",\"Europe\\/Edinburgh\":\"(UTC+00:00) Edinburgh\",\"Etc\\/Greenwich\":\"(UTC+00:00) Greenwich Mean Time : Dublin\",\"Europe\\/Lisbon\":\"(UTC+00:00) Lisbon\",\"Europe\\/London\":\"(UTC+00:00) London\",\"Africa\\/Monrovia\":\"(UTC+00:00) Monrovia\",\"UTC\":\"(UTC+00:00) UTC\",\"Europe\\/Amsterdam\":\"(UTC+01:00) Amsterdam\",\"Europe\\/Belgrade\":\"(UTC+01:00) Belgrade\",\"Europe\\/Berlin\":\"(UTC+01:00) Berlin\",\"Europe\\/Bern\":\"(UTC+01:00) Bern\",\"Europe\\/Bratislava\":\"(UTC+01:00) Bratislava\",\"Europe\\/Brussels\":\"(UTC+01:00) Brussels\",\"Europe\\/Budapest\":\"(UTC+01:00) Budapest\",\"Europe\\/Copenhagen\":\"(UTC+01:00) Copenhagen\",\"Europe\\/Ljubljana\":\"(UTC+01:00) Ljubljana\",\"Europe\\/Madrid\":\"(UTC+01:00) Madrid\",\"Europe\\/Paris\":\"(UTC+01:00) Paris\",\"Europe\\/Prague\":\"(UTC+01:00) Prague\",\"Europe\\/Rome\":\"(UTC+01:00) Rome\",\"Europe\\/Sarajevo\":\"(UTC+01:00) Sarajevo\",\"Europe\\/Skopje\":\"(UTC+01:00) Skopje\",\"Europe\\/Stockholm\":\"(UTC+01:00) Stockholm\",\"Europe\\/Vienna\":\"(UTC+01:00) Vienna\",\"Europe\\/Warsaw\":\"(UTC+01:00) Warsaw\",\"Africa\\/Lagos\":\"(UTC+01:00) West Central Africa\",\"Europe\\/Zagreb\":\"(UTC+01:00) Zagreb\",\"Europe\\/Athens\":\"(UTC+02:00) Athens\",\"Europe\\/Bucharest\":\"(UTC+02:00) Bucharest\",\"Africa\\/Cairo\":\"(UTC+02:00) Cairo\",\"Africa\\/Harare\":\"(UTC+02:00) Harare\",\"Europe\\/Helsinki\":\"(UTC+02:00) Helsinki\",\"Europe\\/Istanbul\":\"(UTC+02:00) Istanbul\",\"Asia\\/Jerusalem\":\"(UTC+02:00) Jerusalem\",\"Europe\\/Kyiv\":\"(UTC+02:00) Kyiv\",\"Africa\\/Johannesburg\":\"(UTC+02:00) Pretoria\",\"Europe\\/Riga\":\"(UTC+02:00) Riga\",\"Europe\\/Sofia\":\"(UTC+02:00) Sofia\",\"Europe\\/Tallinn\":\"(UTC+02:00) Tallinn\",\"Europe\\/Vilnius\":\"(UTC+02:00) Vilnius\",\"Asia\\/Baghdad\":\"(UTC+03:00) Baghdad\",\"Asia\\/Kuwait\":\"(UTC+03:00) Kuwait\",\"Europe\\/Minsk\":\"(UTC+03:00) Minsk\",\"Africa\\/Nairobi\":\"(UTC+03:00) Nairobi\",\"Asia\\/Riyadh\":\"(UTC+03:00) Riyadh\",\"Europe\\/Volgograd\":\"(UTC+03:00) Volgograd\",\"Asia\\/Tehran\":\"(UTC+03:30) Tehran\",\"Asia\\/Abu_Dhabi\":\"(UTC+04:00) Abu Dhabi\",\"Asia\\/Baku\":\"(UTC+04:00) Baku\",\"Europe\\/Moscow\":\"(UTC+04:00) Moscow\",\"Asia\\/Muscat\":\"(UTC+04:00) Muscat\",\"Europe\\/St_Petersburg\":\"(UTC+04:00) St. Petersburg\",\"Asia\\/Tbilisi\":\"(UTC+04:00) Tbilisi\",\"Asia\\/Yerevan\":\"(UTC+04:00) Yerevan\",\"Asia\\/Kabul\":\"(UTC+04:30) Kabul\",\"Asia\\/Islamabad\":\"(UTC+05:00) Islamabad\",\"Asia\\/Karachi\":\"(UTC+05:00) Karachi\",\"Asia\\/Tashkent\":\"(UTC+05:00) Tashkent\",\"Asia\\/Calcutta\":\"(UTC+05:30) Chennai\",\"Asia\\/Kolkata\":\"(UTC+05:30) Kolkata\",\"Asia\\/Mumbai\":\"(UTC+05:30) Mumbai\",\"Asia\\/New_Delhi\":\"(UTC+05:30) New Delhi\",\"Asia\\/Sri_Jayawardenepura\":\"(UTC+05:30) Sri Jayawardenepura\",\"Asia\\/Katmandu\":\"(UTC+05:45) Kathmandu\",\"Asia\\/Almaty\":\"(UTC+06:00) Almaty\",\"Asia\\/Astana\":\"(UTC+06:00) Astana\",\"Asia\\/Dhaka\":\"(UTC+06:00) Dhaka\",\"Asia\\/Yekaterinburg\":\"(UTC+06:00) Ekaterinburg\",\"Asia\\/Rangoon\":\"(UTC+06:30) Rangoon\",\"Asia\\/Bangkok\":\"(UTC+07:00) Bangkok\",\"Asia\\/Hanoi\":\"(UTC+07:00) Hanoi\",\"Asia\\/Jakarta\":\"(UTC+07:00) Jakarta\",\"Asia\\/Novosibirsk\":\"(UTC+07:00) Novosibirsk\",\"Asia\\/Beijing\":\"(UTC+08:00) Beijing\",\"Asia\\/Chongqing\":\"(UTC+08:00) Chongqing\",\"Asia\\/Hong_Kong\":\"(UTC+08:00) Hong Kong\",\"Asia\\/Krasnoyarsk\":\"(UTC+08:00) Krasnoyarsk\",\"Asia\\/Kuala_Lumpur\":\"(UTC+08:00) Kuala Lumpur\",\"Australia\\/Perth\":\"(UTC+08:00) Perth\",\"Asia\\/Singapore\":\"(UTC+08:00) Singapore\",\"Asia\\/Taipei\":\"(UTC+08:00) Taipei\",\"Asia\\/Ulan_Bator\":\"(UTC+08:00) Ulaan Bataar\",\"Asia\\/Urumqi\":\"(UTC+08:00) Urumqi\",\"Asia\\/Irkutsk\":\"(UTC+09:00) Irkutsk\",\"Asia\\/Osaka\":\"(UTC+09:00) Osaka\",\"Asia\\/Sapporo\":\"(UTC+09:00) Sapporo\",\"Asia\\/Seoul\":\"(UTC+09:00) Seoul\",\"Asia\\/Tokyo\":\"(UTC+09:00) Tokyo\",\"Australia\\/Adelaide\":\"(UTC+09:30) Adelaide\",\"Australia\\/Darwin\":\"(UTC+09:30) Darwin\",\"Australia\\/Brisbane\":\"(UTC+10:00) Brisbane\",\"Australia\\/Canberra\":\"(UTC+10:00) Canberra\",\"Pacific\\/Guam\":\"(UTC+10:00) Guam\",\"Australia\\/Hobart\":\"(UTC+10:00) Hobart\",\"Australia\\/Melbourne\":\"(UTC+10:00) Melbourne\",\"Pacific\\/Port_Moresby\":\"(UTC+10:00) Port Moresby\",\"Australia\\/Sydney\":\"(UTC+10:00) Sydney\",\"Asia\\/Yakutsk\":\"(UTC+10:00) Yakutsk\",\"Asia\\/Vladivostok\":\"(UTC+11:00) Vladivostok\",\"Pacific\\/Auckland\":\"(UTC+12:00) Auckland\",\"Pacific\\/Fiji\":\"(UTC+12:00) Fiji\",\"Pacific\\/Kwajalein\":\"(UTC+12:00) International Date Line West\",\"Asia\\/Kamchatka\":\"(UTC+12:00) Kamchatka\",\"Asia\\/Magadan\":\"(UTC+12:00) Magadan\",\"Pacific\\/Marshall_Is\":\"(UTC+12:00) Marshall Is.\",\"Asia\\/New_Caledonia\":\"(UTC+12:00) New Caledonia\",\"Asia\\/Solomon_Is\":\"(UTC+12:00) Solomon Is.\",\"Pacific\\/Wellington\":\"(UTC+12:00) Wellington\",\"Pacific\\/Tongatapu\":\"(UTC+13:00) Nuku\'alofa\"},\"placeholder\":\"Choose a timezone...\"}',1,NULL,0,0,0,0,11,2,NULL,NULL,NULL), - (120,'directus_users','locale','string','language','{\"limit\":true}',1,NULL,0,0,0,0,12,2,NULL,NULL,NULL), - (121,'directus_users','locale_options','json','code',NULL,1,NULL,0,0,1,1,13,4,NULL,NULL,NULL), - (122,'directus_users','token','string','text-input',NULL,1,NULL,0,0,1,1,14,4,NULL,NULL,NULL), - (123,'directus_users','last_login','datetime','datetime',NULL,1,NULL,0,1,0,0,15,2,NULL,NULL,NULL), - (124,'directus_users','last_access_on','datetime','datetime',NULL,1,NULL,0,1,1,0,16,2,NULL,NULL,NULL), - (125,'directus_users','last_page','string','text-input',NULL,1,NULL,0,1,1,1,17,2,NULL,NULL,NULL), - (126,'directus_users','avatar','file','file',NULL,1,NULL,0,0,0,0,18,4,NULL,NULL,NULL), - (127,'directus_users','invite_token','string','text-input',NULL,1,NULL,0,0,1,1,NULL,4,NULL,NULL,NULL), - (128,'directus_users','invite_accepted','boolean','toggle',NULL,1,NULL,0,0,1,1,NULL,4,NULL,NULL,NULL), - (129,'directus_users','last_ip','string','text-input',NULL,1,NULL,0,1,1,0,NULL,4,NULL,NULL,NULL), - (130,'directus_users','external_id','string','text-input',NULL,1,NULL,0,1,1,0,NULL,4,NULL,NULL,NULL), - (131,'directus_user_roles','id','integer','primary-key',NULL,1,NULL,1,0,1,0,NULL,4,NULL,NULL,NULL), - (132,'directus_user_roles','user','m2o','many-to-one',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (133,'directus_user_roles','role','m2o','many-to-one',NULL,1,NULL,0,0,0,0,NULL,4,NULL,NULL,NULL), - (134, 'products', 'status', 'status', 'status', '{\"status_mapping\":{\"1\":{\"name\":\"Published\"},\"2\":{\"name\":\"Draft\",\"published\":\"0\"}}}', 0, NULL, 0, 0, 0, 0, 0, 4, NULL, '0', NULL), - (135, 'products', 'category_id', 'number', 'many_to_one', NULL, 0, NULL, 0, 0, 0, 0, NULL, 4, NULL, NULL, NULL), - (136, 'products', 'images', 'o2m', 'one-to-many', NULL, 0, NULL, 0, 0, 0, 0, NULL, 4, NULL, NULL, NULL), - (137, 'categories', 'id', 'number', 'primary_key', NULL, 0, NULL, 0, 0, 0, 0, 0, 4, NULL, NULL, NULL), - (138, 'categories', 'products', 'O2M', 'one-to-many', '{\"status_mapping\":{\"1\":{\"name\":\"Published\"},\"2\":{\"name\":\"Draft\",\"published\":\"0\"}}}', 0, NULL, 0, 0, 0, 0, NULL, 4, NULL, NULL, NULL), - (139, 'categories', 'name', 'string', 'text_input', NULL, 0, NULL, 0, 0, 0, 0, NULL, 4, NULL, NULL, NULL), - (140, 'languages', 'code', 'string', 'text-input', NULL, 0, NULL, 0, 0, 0, 0, 0, 4, NULL, NULL, NULL), - (141, 'languages', 'name', 'string', 'text-input', NULL, 0, NULL, 0, 0, 0, 0, 0, 4, NULL, NULL, NULL), - (142, 'news', 'id', 'integer', 'text-input', NULL, 0, NULL, 0, 0, 0, 0, 0, 4, NULL, NULL, NULL), - (143, 'news_translations', 'id', 'integer', 'text-input', NULL, 0, NULL, 0, 0, 0, 0, 0, 4, NULL, NULL, NULL), - (144, 'news_translations', 'title', 'varchar', 'text-input', NULL, 0, NULL, 0, 0, 0, 0, 0, 4, NULL, NULL, NULL), - (145, 'news_translations', 'content', 'text', 'textarea', NULL, 0, NULL, 0, 0, 0, 0, 0, 4, NULL, NULL, NULL), - (146, 'news_translations', 'news', 'integer', 'numeric', NULL, 0, NULL, 0, 0, 0, 0, 0, 4, NULL, NULL, NULL), - (147, 'news_translations', 'language', 'lang', 'lang', NULL, 0, NULL, 0, 0, 0, 0, 0, 4, NULL, NULL, NULL), - (148, 'news', 'translations', 'translation', 'translation', NULL, 0, NULL, 0, 0, 0, 0, NULL, 4, NULL, NULL, NULL), - (149, 'home', 'id', 'primary_key', 'numeric', NULL, 0, NULL, 0, 0, 0, 0, 0, 4, NULL, NULL, NULL), - (150, 'home', 'title', 'varchar', 'text-input', NULL, 0, NULL, 0, 0, 0, 0, 0, 4, NULL, NULL, NULL), - (151, 'home', 'news', 'o2m', 'one-to-many', NULL, 0, NULL, 0, 0, 0, 0, 0, 4, NULL, NULL, NULL), - (152, 'home_news', 'id', 'primary_key', 'numeric', NULL, 0, NULL, 0, 0, 0, 0, 0, 4, NULL, NULL, NULL), - (153, 'home_news', 'home_id', 'integer', 'numeric', NULL, 0, NULL, 0, 0, 0, 0, 0, 4, NULL, NULL, NULL), - (154, 'home_news', 'news_id', 'integer', 'numeric', NULL, 0, NULL, 0, 0, 0, 0, 0, 4, NULL, NULL, NULL); - - -/*!40000 ALTER TABLE `directus_fields` ENABLE KEYS */; -UNLOCK TABLES; - - -# Dump of table directus_files -# ------------------------------------------------------------ - -DROP TABLE IF EXISTS `directus_files`; - -CREATE TABLE `directus_files` ( - `id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `storage` varchar(50) NOT NULL DEFAULT 'local', - `filename` varchar(255) NOT NULL, - `title` varchar(255) DEFAULT NULL, - `type` varchar(255) DEFAULT NULL, - `uploaded_by` int(11) unsigned NOT NULL, - `uploaded_on` datetime NOT NULL, - `charset` varchar(50) DEFAULT NULL, - `filesize` int(11) unsigned NOT NULL DEFAULT '0', - `width` int(11) unsigned DEFAULT NULL, - `height` int(11) unsigned DEFAULT NULL, - `duration` int(11) DEFAULT NULL, - `embed` varchar(200) DEFAULT NULL, - `folder` int(11) unsigned DEFAULT NULL, - `description` text, - `location` varchar(200) DEFAULT NULL, - `tags` varchar(255) DEFAULT NULL, - `metadata` text, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - - -# Dump of table directus_folders -# ------------------------------------------------------------ - -DROP TABLE IF EXISTS `directus_folders`; - -CREATE TABLE `directus_folders` ( - `id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `name` varchar(191) CHARACTER SET utf8mb4 NOT NULL, - `parent_folder` int(11) unsigned DEFAULT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `idx_name_parent_folder` (`name`,`parent_folder`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - - - -# Dump of table directus_migrations -# ------------------------------------------------------------ - -DROP TABLE IF EXISTS `directus_migrations`; - -CREATE TABLE `directus_migrations` ( - `version` bigint(20) NOT NULL, - `migration_name` varchar(100) DEFAULT NULL, - `start_time` timestamp NULL DEFAULT NULL, - `end_time` timestamp NULL DEFAULT NULL, - `breakpoint` tinyint(1) NOT NULL DEFAULT '0', - PRIMARY KEY (`version`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - -LOCK TABLES `directus_migrations` WRITE; -/*!40000 ALTER TABLE `directus_migrations` DISABLE KEYS */; - -INSERT INTO `directus_migrations` (`version`, `migration_name`, `start_time`, `end_time`, `breakpoint`) -VALUES - (20180220023138,'CreateActivityTable','2019-01-04 15:42:26','2019-01-04 15:42:26',0), - (20180220023144,'CreateActivitySeenTable','2019-01-04 15:42:26','2019-01-04 15:42:26',0), - (20180220023152,'CreateCollectionsPresetsTable','2019-01-04 15:42:26','2019-01-04 15:42:27',0), - (20180220023157,'CreateCollectionsTable','2019-01-04 15:42:27','2019-01-04 15:42:27',0), - (20180220023202,'CreateFieldsTable','2019-01-04 15:42:27','2019-01-04 15:42:27',0), - (20180220023208,'CreateFilesTable','2019-01-04 15:42:27','2019-01-04 15:42:27',0), - (20180220023213,'CreateFoldersTable','2019-01-04 15:42:27','2019-01-04 15:42:27',0), - (20180220023217,'CreateRolesTable','2019-01-04 15:42:27','2019-01-04 15:42:27',0), - (20180220023226,'CreatePermissionsTable','2019-01-04 15:42:27','2019-01-04 15:42:27',0), - (20180220023232,'CreateRelationsTable','2019-01-04 15:42:27','2019-01-04 15:42:27',0), - (20180220023238,'CreateRevisionsTable','2019-01-04 15:42:27','2019-01-04 15:42:27',0), - (20180220023243,'CreateSettingsTable','2019-01-04 15:42:27','2019-01-04 15:42:27',0), - (20180220023248,'CreateUsersTable','2019-01-04 15:42:27','2019-01-04 15:42:27',0), - (20180426173310,'CreateUserRoles','2019-01-04 15:42:27','2019-01-04 15:42:27',0); - -/*!40000 ALTER TABLE `directus_migrations` ENABLE KEYS */; -UNLOCK TABLES; - - -# Dump of table directus_permissions -# ------------------------------------------------------------ - -DROP TABLE IF EXISTS `directus_permissions`; - -CREATE TABLE `directus_permissions` ( - `id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `collection` varchar(64) NOT NULL, - `role` int(11) unsigned NOT NULL, - `status` varchar(64) DEFAULT NULL, - `create` varchar(16) DEFAULT 'none', - `read` varchar(16) DEFAULT 'none', - `update` varchar(16) DEFAULT 'none', - `delete` varchar(16) DEFAULT 'none', - `comment` varchar(8) DEFAULT 'none', - `explain` varchar(8) DEFAULT 'none', - `read_field_blacklist` varchar(1000) DEFAULT NULL, - `write_field_blacklist` varchar(1000) DEFAULT NULL, - `status_blacklist` varchar(1000) DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - - - -# Dump of table directus_relations -# ------------------------------------------------------------ - -DROP TABLE IF EXISTS `directus_relations`; - -CREATE TABLE `directus_relations` ( - `id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `collection_many` varchar(64) NOT NULL, - `field_many` varchar(45) NOT NULL, - `collection_one` varchar(64) DEFAULT NULL, - `field_one` varchar(64) DEFAULT NULL, - `junction_field` varchar(64) DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - -LOCK TABLES `directus_relations` WRITE; -/*!40000 ALTER TABLE `directus_relations` DISABLE KEYS */; - -INSERT INTO `directus_relations` (`id`, `collection_many`, `field_many`, `collection_one`, `field_one`, `junction_field`) -VALUES - (1,'directus_activity','action_by','directus_users',NULL,NULL), - (2,'directus_activity_seen','user','directus_users',NULL,NULL), - (3,'directus_activity_seen','activity','directus_activity',NULL,NULL), - (4,'directus_collections_presets','user','directus_users',NULL,NULL), - (5,'directus_collections_presets','group','directus_groups',NULL,NULL), - (6,'directus_files','uploaded_by','directus_users',NULL,NULL), - (7,'directus_files','folder','directus_folders',NULL,NULL), - (8,'directus_folders','parent_folder','directus_folders',NULL,NULL), - (9,'directus_permissions','group','directus_groups',NULL,NULL), - (10,'directus_revisions','activity','directus_activity',NULL,NULL), - (11,'directus_user_roles','user','directus_users','roles','role'), - (12,'directus_user_roles','role','directus_roles','users','user'), - (13,'directus_users','avatar','directus_files',NULL,NULL), - (14,'directus_fields','collection','directus_collections','fields',NULL), - (15, 'products', 'category_id', 'categories', 'products',NULL), - (16, 'news_translations', 'news', 'news', 'translations',NULL), - (17, 'products_images', 'product_id', 'products', 'images',NULL), - (18, 'products_images', 'file_id', 'directus_files', NULL,NULL), - (19, 'home_news', 'news_id', 'news', NULL,NULL), - (20, 'home_news', 'home_id', 'home', 'news',NULL); - - -/*!40000 ALTER TABLE `directus_relations` ENABLE KEYS */; -UNLOCK TABLES; - - -# Dump of table directus_revisions -# ------------------------------------------------------------ - -DROP TABLE IF EXISTS `directus_revisions`; - -CREATE TABLE `directus_revisions` ( - `id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `activity` int(11) unsigned NOT NULL, - `collection` varchar(64) NOT NULL, - `item` varchar(255) NOT NULL, - `data` longtext NOT NULL, - `delta` longtext, - `parent_collection` varchar(64) DEFAULT NULL, - `parent_item` varchar(255) DEFAULT NULL, - `parent_changed` tinyint(1) unsigned DEFAULT '0', - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - - - -# Dump of table directus_roles -# ------------------------------------------------------------ - -DROP TABLE IF EXISTS `directus_roles`; - -CREATE TABLE `directus_roles` ( - `id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `name` varchar(100) NOT NULL, - `description` varchar(500) DEFAULT NULL, - `ip_whitelist` text, - `nav_blacklist` text, - `external_id` varchar(255) DEFAULT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `idx_group_name` (`name`), - UNIQUE KEY `idx_roles_external_id` (`external_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - -LOCK TABLES `directus_roles` WRITE; -/*!40000 ALTER TABLE `directus_roles` DISABLE KEYS */; - -INSERT INTO `directus_roles` (`id`, `name`, `description`, `ip_whitelist`, `nav_blacklist`, `external_id`) -VALUES - (1,'Administrator','Admins have access to all managed data within the system by default',NULL,NULL,NULL), - (2,'Public','This sets the data that is publicly available through the API without a token',NULL,NULL,NULL), - (3,'Intern',NULL,NULL,NULL, '3'); - -/*!40000 ALTER TABLE `directus_roles` ENABLE KEYS */; -UNLOCK TABLES; - - -# Dump of table directus_settings -# ------------------------------------------------------------ - -DROP TABLE IF EXISTS `directus_settings`; - -CREATE TABLE `directus_settings` ( - `id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `key` varchar(64) NOT NULL, - `value` text NOT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `idx_key` (`key`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - -LOCK TABLES `directus_settings` WRITE; -/*!40000 ALTER TABLE `directus_settings` DISABLE KEYS */; - -INSERT INTO `directus_settings` (`id`, `key`, `value`) -VALUES - (1,'auto_sign_out','60'), - (2,'project_name','Directus'), - (3,'project_url',''), - (4,'default_limit','200'), - (5,'logo',''), - (6,'color','light-blue-600'), - (7,'youtube_api_key',''), - (8,'trusted_proxies',''), - (9,'thumbnail_dimensions','200x200'), - (10,'thumbnail_quality_tags','{\"poor\": 25, \"good\": 50, \"better\": 75, \"best\": 100}'), - (11,'thumbnail_actions','{\"contain\":{\"options\":{\"resizeCanvas\":false,\"position\":\"center\",\"resizeRelative\":false,\"canvasBackground\":\"ccc\"}},\"crop\":{\"options\":{\"position\":\"center\"}}}'), - (12,'thumbnail_cache_ttl','86400'), - (13,'thumbnail_not_found_location',''); - -/*!40000 ALTER TABLE `directus_settings` ENABLE KEYS */; -UNLOCK TABLES; - - -# Dump of table directus_user_roles -# ------------------------------------------------------------ - -DROP TABLE IF EXISTS `directus_user_roles`; - -CREATE TABLE `directus_user_roles` ( - `id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `user` int(11) unsigned DEFAULT NULL, - `role` int(11) unsigned DEFAULT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `idx_user_role` (`user`,`role`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - -LOCK TABLES `directus_user_roles` WRITE; -/*!40000 ALTER TABLE `directus_user_roles` DISABLE KEYS */; - -INSERT INTO `directus_user_roles` (`id`, `user`, `role`) -VALUES - (1,1,1), - (2,2,3), - (3,3,3); - -/*!40000 ALTER TABLE `directus_user_roles` ENABLE KEYS */; -UNLOCK TABLES; - - -# Dump of table directus_users -# ------------------------------------------------------------ - -DROP TABLE IF EXISTS `directus_users`; - -CREATE TABLE `directus_users` ( - `id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `status` varchar(16) NOT NULL DEFAULT 'draft', - `first_name` varchar(50) DEFAULT NULL, - `last_name` varchar(50) DEFAULT NULL, - `email` varchar(128) NOT NULL, - `password` varchar(255) DEFAULT NULL, - `token` varchar(255) DEFAULT NULL, - `timezone` varchar(32) NOT NULL DEFAULT 'America/New_York', - `locale` varchar(8) DEFAULT 'en-US', - `locale_options` text, - `avatar` int(11) unsigned DEFAULT NULL, - `company` varchar(191) DEFAULT NULL, - `title` varchar(191) DEFAULT NULL, - `email_notifications` int(1) NOT NULL DEFAULT '1', - `last_access_on` datetime DEFAULT NULL, - `last_page` varchar(192) DEFAULT NULL, - `external_id` varchar(255) DEFAULT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `idx_users_email` (`email`), - UNIQUE KEY `idx_users_token` (`token`), - UNIQUE KEY `idx_users_external_id` (`external_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - -LOCK TABLES `directus_users` WRITE; -/*!40000 ALTER TABLE `directus_users` DISABLE KEYS */; - -INSERT INTO `directus_users` (`id`, `status`, `first_name`, `last_name`, `email`, `password`, `token`, `timezone`, `locale`, `locale_options`, `avatar`, `company`, `title`, `email_notifications`, `last_access_on`, `last_page`, `external_id`) -VALUES - (1, 'active', 'Admin', 'User', 'admin@getdirectus.com', '$2y$10$sx0.rYeNCXvJZ9LYGPZofekAq2ah7pVEWnB3YR5aNNseLBAILztc2', 'token', 'Europe/Berlin', 'en-US', '0', 1, NULL, NULL, 1, '2018-05-21 15:48:03', '/collections/projects', '00ud6pmxj4KW5F6Ua0h7'), - (2, 'active', 'Intern', 'User', 'intern@getdirectus.com', NULL, 'intern_token', 'Europe/Berlin', 'en-US', '0', NULL, NULL, NULL, 1, NULL, NULL, NULL), - (3, 'suspended', 'Disabled', 'User', 'disabled@getdirectus.com', '$2y$10$Njtky/bsFG9qzeW7EPy8FubOay.GxRFWTlCrQEDyR9D0N2UMdxC3u', 'disabled_token', 'America/New_York', 'en-US', '0', NULL, NULL, NULL, 1, NULL, NULL, NULL); - - -/*!40000 ALTER TABLE `directus_users` ENABLE KEYS */; -UNLOCK TABLES; - -# Dump of table home -# ------------------------------------------------------------ - -DROP TABLE IF EXISTS `home`; - -CREATE TABLE `home` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `title` varchar(100) DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - -LOCK TABLES `home` WRITE; -/*!40000 ALTER TABLE `home` DISABLE KEYS */; - -INSERT INTO `home` (`id`, `title`) -VALUES - (1,'title 1'); - -/*!40000 ALTER TABLE `home` ENABLE KEYS */; -UNLOCK TABLES; - - -# Dump of table home_news -# ------------------------------------------------------------ - -DROP TABLE IF EXISTS `home_news`; - -CREATE TABLE `home_news` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `home_id` int(10) unsigned DEFAULT NULL, - `news_id` int(10) unsigned DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - -LOCK TABLES `home_news` WRITE; -/*!40000 ALTER TABLE `home_news` DISABLE KEYS */; - -INSERT INTO `home_news` (`id`, `home_id`, `news_id`) -VALUES - (1,1,1); - -/*!40000 ALTER TABLE `home_news` ENABLE KEYS */; -UNLOCK TABLES; - - -# Dump of table languages -# ------------------------------------------------------------ - -DROP TABLE IF EXISTS `languages`; - -CREATE TABLE `languages` ( - `code` char(2) NOT NULL DEFAULT '', - `name` varchar(255) DEFAULT NULL, - PRIMARY KEY (`code`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - -LOCK TABLES `languages` WRITE; -/*!40000 ALTER TABLE `languages` DISABLE KEYS */; - -INSERT INTO `languages` (`code`, `name`) -VALUES - ('en','English'), - ('es','Español'), - ('nl','Nederlands'); - -/*!40000 ALTER TABLE `languages` ENABLE KEYS */; -UNLOCK TABLES; - - -# Dump of table news -# ------------------------------------------------------------ - -DROP TABLE IF EXISTS `news`; - -CREATE TABLE `news` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - -LOCK TABLES `news` WRITE; -/*!40000 ALTER TABLE `news` DISABLE KEYS */; - -INSERT INTO `news` (`id`) -VALUES - (1), - (2); - -/*!40000 ALTER TABLE `news` ENABLE KEYS */; -UNLOCK TABLES; - - -# Dump of table news_translations -# ------------------------------------------------------------ - -DROP TABLE IF EXISTS `news_translations`; - -CREATE TABLE `news_translations` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `title` varchar(255) DEFAULT NULL, - `content` text, - `news` int(10) unsigned DEFAULT NULL, - `language` char(2) DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - -LOCK TABLES `news_translations` WRITE; -/*!40000 ALTER TABLE `news_translations` DISABLE KEYS */; - -INSERT INTO `news_translations` (`id`, `title`, `content`, `news`, `language`) -VALUES - (1,'Title','content',1,'en'), - (2,'Titulo','contenido',1,'es'), - (3,'Titel','inhoud',1,'nl'); - -/*!40000 ALTER TABLE `news_translations` ENABLE KEYS */; -UNLOCK TABLES; - - -# Dump of table products -# ------------------------------------------------------------ - -DROP TABLE IF EXISTS `products`; - -CREATE TABLE `products` ( - `id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `name` varchar(255) DEFAULT NULL, - `status` int(11) NOT NULL DEFAULT '2', - `price` decimal(10,2) unsigned NOT NULL, - `category_id` int(11) DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - - - -# Dump of table products_images -# ------------------------------------------------------------ - -DROP TABLE IF EXISTS `products_images`; - -CREATE TABLE `products_images` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `product_id` int(11) DEFAULT NULL, - `file_id` int(11) DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; - - - - -/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; -/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; -/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; -/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; -/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; diff --git a/tests/io/ActivityCommentTest.php b/tests/io/ActivityCommentTest.php deleted file mode 100644 index 1f2ea1439b..0000000000 --- a/tests/io/ActivityCommentTest.php +++ /dev/null @@ -1,475 +0,0 @@ - 'test', - 'fields' => [ - [ - 'field' => 'id', - 'auto_increment' => true, - 'type' => 'integer', - 'datatype' => 'integer', - 'primary_key' => true, - 'interface' => 'primary_key', - 'length' => 11, - ], - [ - 'field' => 'name', - 'type' => 'string', - 'datatype' => 'varchar', - 'interface' => 'text_input', - 'length' => 255, - ], - [ - 'field' => 'status', - 'type' => 'status', - 'datatype' => 'integer', - 'interface' => 'status', - 'default_value' => 2, - 'length' => 11, - ], - ] - ], ['query' => ['access_token' => 'token']]); - - $query = 'CREATE TABLE `objects` ( - `id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `name` varchar(100) NOT NULL, - PRIMARY KEY (`id`) - ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;'; - - static::$db->execute($query); - - table_insert(static::$db, 'directus_collections', [ - 'collection' => 'objects' - ]); - } - - public static function tearDownAfterClass() - { - static::resetDatabase(); - } - - public static function resetDatabase() - { - self::clearData(); - truncate_table(static::$db, 'directus_permissions'); - truncate_table(static::$db, 'directus_folders'); - truncate_table(static::$db, 'directus_activity'); - drop_table(static::$db, 'test'); - drop_table(static::$db, 'test2'); - drop_table(static::$db, 'objects'); - } - - public static function clearData() - { - if (table_exists(static::$db, 'test')) { - truncate_table(static::$db, 'test'); - } - - if (table_exists(static::$db, 'test2')) { - truncate_table(static::$db, 'test2'); - } - - truncate_table(static::$db, 'directus_permissions'); - truncate_table(static::$db, 'directus_collection_presets'); - truncate_table(static::$db, 'directus_settings'); - reset_table_id(static::$db, 'directus_roles', 4); - reset_table_id(static::$db, 'directus_users', 4); - truncate_table(static::$db, 'directus_files'); - truncate_table(static::$db, 'directus_folders'); - $storagePath = __DIR__ . '/../../public/uploads/_/originals'; - - clear_storage($storagePath); - } - - public function testWithoutFlag() - { - $this->clearData(); - $this->flags = []; - - $this->doCollectionPresets(); - $this->doCollections(); - $this->doFields(); - $this->doFiles(); - $this->doFilesFolders(); - $this->doRoles(); - $this->doItems(); - $this->doPermissions(); - $this->doSettings(); - $this->doUsers(); - } - - public function testWithFlagOff() - { - $this->clearData(); - $this->flags = []; - - $this->setFlagOff('directus_collection_presets'); - $this->doCollectionPresets(); - - $this->setFlagOff('directus_collections'); - $this->doCollections(); - - $this->setFlagOff('directus_collections'); - $this->doFields(); - - $this->setFlagOff('directus_files'); - $this->doFiles(); - - $this->setFlagOff('directus_folders'); - $this->doFilesFolders(); - - $this->setFlagOff('directus_roles'); - $this->doRoles(); - - $this->setFlagOff('test'); - $this->doItems(); - - $this->setFlagOff('test', 0); - $this->doItemsWithStatus(0); - $this->setFlagOff('test', 1); - $this->doItemsWithStatus(0); - - $this->setFlagOff('directus_permissions'); - $this->doPermissions(); - - $this->setFlagOff('directus_settings'); - $this->doSettings(); - - $this->setFlagOff('directus_users'); - $this->doUsers(); - } - - public function testWithFlagOnAlways() - { - $this->clearData(); - $this->flags = []; - - $this->setFlagOnAlways('directus_collection_presets'); - $this->doCollectionPresets(true); - $this->doCollectionPresets(false, 'message'); - - $this->setFlagOnAlways('directus_collections'); - $this->doCollections(true); - $this->doCollections(false, 'message'); - - $this->setFlagOnAlways('directus_fields'); - $this->doFields(true); - $this->doFields(false, 'message'); - - $this->setFlagOnAlways('directus_files'); - $this->doFiles(true); - $this->doFiles(false, 'message'); - - $this->setFlagOnAlways('directus_folders'); - $this->doFilesFolders(true); - $this->doFilesFolders(false, 'message'); - - $this->setFlagOnAlways('directus_roles'); - $this->doRoles(true); - $this->doRoles(false, 'message'); - - $this->setFlagOnAlways('test'); - $this->doItems(true); - $this->doItems(false, 'message'); - - $this->setFlagOnAlways('test', 0); - $this->doItemsWithStatus(0, true); - $this->doItemsWithStatus(0, false, 'message'); - - $this->setFlagOnAlways('test', 1); - $this->doItemsWithStatus(1, true); - $this->doItemsWithStatus(1, false, 'message'); - - $this->setFlagOnAlways('directus_permissions'); - $this->doPermissions(true); - $this->doPermissions(false, 'message'); - - $this->setFlagOnAlways('directus_settings'); - $this->doSettings(true); - $this->doSettings(false, 'message'); - - $this->setFlagOnAlways('directus_users'); - $this->doUsers(true); - $this->doUsers(false, 'message'); - } - - protected function doFiles($error = false, $message = null) - { - $data = [ - 'filename' => 'activity.jpg', - 'data' => '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAUDBAQEAwUEBAQFBQUGBwwIBwcHBw8LCwkMEQ8SEhEPERETFhwXExQaFRERGCEYGh0dHx8fExciJCIeJBweHx7/2wBDAQUFBQcGBw4ICA4eFBEUHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh7/wAARCAB4AKADASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAX/xAAUEAEAAAAAAAAAAAAAAAAAAAAA/8QAFgEBAQEAAAAAAAAAAAAAAAAAAAUH/8QAFBEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEQMRAD8AugILDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH/9k=' - ]; - $this->create('files', $data, $error, $message); - $this->update('files/1', ['title' => 'Title test'], $error, $message); - $this->delete('files/1', $error, $message); - } - - protected function doFilesFolders($error = false, $message = null) - { - $data = [ - 'name' => 'folder' - ]; - $this->create('files/folders', $data, $error, $message); - $this->update('files/folders/1', ['name' => 'logos'], $error, $message); - $this->delete('files/folders/1', $error, $message); - } - - protected function doRoles($error = false, $message = null) - { - $data = ['name' => 'new-role']; - $this->create('roles', $data, $error, $message); - $this->update('roles/4', $data, $error, $message); - $this->delete('roles/4', $error, $message); - } - - protected function doItems($error = false, $message = null) - { - $data = ['name' => 'new']; - $this->create('items/test', $data, $error, $message); - $this->update('items/test/1', $data, $error, $message); - $this->delete('items/test/1', $error, $message); - } - - protected function doItemsWithStatus($status, $error = false, $message = null) - { - if (table_exists(static::$db, 'test')) { - truncate_table(static::$db, 'test'); - } - - $data = ['name' => 'new', 'status' => $status]; - $this->create('items/test', $data, $error, $message); - $this->update('items/test/1', $data, $error, $message); - $this->delete('items/test/1', $error, $message); - } - - protected function doPermissions($error = false, $message = null) - { - $data = ['collection' => 'something', 'role' => 1]; - $this->create('permissions', $data, $error, $message); - $this->update('permissions/2', ['create' => 1], $error, $message); - $this->delete('permissions/2', $error, $message); - } - - protected function doSettings($error = false, $message = null) - { - $data = [ - 'scope' => 'scope-name', - 'key' => 'value', - 'value' => 1 - ]; - - $this->create('settings', $data, $error, $message); - $this->update('settings/1', ['value' => 'new-value'], $error, $message); - $this->delete('settings/1', $error, $message); - } - - protected function doUsers($error = false, $message = null) - { - $data = [ - 'first_name' => 'John', - 'last_name' => 'Doe', - 'password' => 'test', - 'email' => 'test@getdirectus.com' - ]; - - $this->create('users', $data, $error, $message); - $this->update('users/4', ['password' => 'password'], $error, $message); - $this->delete('users/4', $error, $message); - } - - protected function doCollectionPresets($error = false, $message = null) - { - $data = [ - 'role' => 1, - 'collection' => 'test2', - 'search_query' => 'name', - 'view_type' => 'tabular' - ]; - - $this->create('collection_presets', $data, $error, $message); - $this->update('collection_presets/1', ['search_query' => 'id+name'], $error, $message); - $this->delete('collection_presets/1', $error, $message); - } - - protected function doCollections($error = false, $message = null) - { - $data = [ - 'collection' => 'test2', - 'fields' => [ - [ - 'field' => 'id', - 'interface' => 'primary_key', - 'type' => 'integer', - 'length' => 11, - 'auto_increment' => true, - 'datatype' => 'integer', - 'primary_key' => true, - ], - [ - 'field' => 'name', - 'interface' => 'text_input', - 'type' => 'string', - 'datatype' => 'varchar', - 'length' => 255 - ], - ] - ]; - - $this->create('collections', $data, $error, $message); - $this->update('collections/test2', ['hidden' => 1], $error, $message); - $this->delete('collections/test2', $error, $message); - } - - protected function doFields($error = false, $message = null) - { - $data = [ - 'field' => 'title', - 'interface' => 'text_input', - 'type' => 'string', - 'datatype' => 'varchar', - 'length' => 255, - ]; - - $this->create('fields/objects', $data, $error, $message); - $this->update('fields/objects/title', ['required' => 1], $error, $message); - $this->delete('fields/objects/title', $error, $message); - } - - /** - * @param $path - * @param $data - * @param null $error - * @param null $message - * - * @return ResponseInterface - */ - protected function create($path, $data, $error = null, $message = null) - { - return $this->request('post', $path, [ - 'data' => $data, - 'error' => $error, - 'query' => ['comment' => $message] - ]); - } - - protected function update($path, $data, $error = null, $message = null) - { - $this->request('patch', $path, [ - 'data' => $data, - 'error' => $error, - 'query' => ['comment' => $message] - ]); - } - - protected function delete($path, $error, $message) - { - $this->request('delete', $path, [ - 'error' => $error, - 'query' => ['comment' => $message] - ]); - } - - protected function request($type, $path, array $options = []) - { - $error = isset($options['error']) ? $options['error'] : false; - $extraQuery = isset($options['query']) ? $options['query'] : []; - $query = array_merge($extraQuery, ['access_token' => 'token']); - $data = isset($options['data']) ? $options['data'] : []; - - $function = sprintf('request_%s%s', - $error ? 'error_' : '', - $type - ); - - switch ($type) { - case 'patch': - case 'post': - $args = [ - $data, - ['query' => $query] - ]; - break; - case 'delete': - $args = [ - ['query' => $query] - ]; - break; - default: - $args = [$query]; - } - - array_unshift($args, $path); - - $response = call_user_func_array($function, $args); - - if ($error) { - assert_response_error($this, $response); - } else if ($type === 'delete') { - assert_response_empty($this, $response); - } else { - assert_response($this, $response); - } - - return $response; - } - - protected function setFlag($collection, $value, $status) - { - $data = [ - 'collection' => $collection, - 'role' => 1, - 'status' => $status, - 'explain' => $value - ]; - - $options = [ - 'query' => [ - 'access_token' => 'token', - 'comment' => 'setting flag' - ] - ]; - - if (isset($this->flags[$collection])) { - request_patch('permissions/' . $this->flags[$collection], $data, $options); - } else { - $this->flags[$collection] = count($this->flags) + 1; - request_post('permissions', $data, $options); - } - } - - protected function setFlagOn($collection, $level, $status = null) - { - $this->setFlag($collection, $level, $status); - } - - protected function setFlagOnAlways($collection, $status = null) - { - $this->setFlagOn($collection, 'always', $status); - } - - protected function setFlagOff($collection, $status = null) - { - $this->setFlag($collection, null, $status); - } -} diff --git a/tests/io/ActivitySkipTest.php b/tests/io/ActivitySkipTest.php deleted file mode 100644 index 7e19057938..0000000000 --- a/tests/io/ActivitySkipTest.php +++ /dev/null @@ -1,111 +0,0 @@ -assertSame(0, table_count(static::$db, 'directus_activity')); - $path = 'items/products'; - $response = request_post( - $path, - ['name' => 'product', 'price' => 10.00], - ['query' => ['access_token' => 'token', 'activity_skip' => true]] - ); - - $this->assertSame(0, table_count(static::$db, 'directus_activity')); - - $product = response_get_data($response); - $response = request_patch( - $path . '/' . $product->id, - ['name' => 'product 2'], - ['query' => ['access_token' => 'token', 'activity_skip' => true]] - ); - - $this->assertSame(0, table_count(static::$db, 'directus_activity')); - - $response = request_delete( - $path . '/' . $product->id, - ['query' => ['access_token' => 'token', 'activity_skip' => true]] - ); - - $this->assertSame(0, table_count(static::$db, 'directus_activity')); - } - - public function testSkipActivityOff() - { - $this->assertSame(0, table_count(static::$db, 'directus_activity')); - $path = 'items/products'; - $response = request_post( - $path, - ['name' => 'product', 'price' => 10.00], - ['query' => ['access_token' => 'token', 'activity_skip' => false]] - ); - - $this->assertSame(1, table_count(static::$db, 'directus_activity')); - - $product = response_get_data($response); - $response = request_patch( - $path . '/' . $product->id, - ['name' => 'product 2'], - ['query' => ['access_token' => 'token', 'activity_skip' => false]] - ); - - $this->assertSame(2, table_count(static::$db, 'directus_activity')); - - $response = request_delete( - $path . '/' . $product->id, - ['query' => ['access_token' => 'token', 'activity_skip' => false]] - ); - - $this->assertSame(3, table_count(static::$db, 'directus_activity')); - } - - public function testWithoutSkipActivity() - { - $this->assertSame(3, table_count(static::$db, 'directus_activity')); - $path = 'items/products'; - $response = request_post( - $path, - ['name' => 'product', 'price' => 10.00], - ['query' => ['access_token' => 'token']] - ); - - $this->assertSame(4, table_count(static::$db, 'directus_activity')); - - $product = response_get_data($response); - $response = request_patch( - $path . '/' . $product->id, - ['name' => 'product 2'], - ['query' => ['access_token' => 'token']] - ); - - $this->assertSame(5, table_count(static::$db, 'directus_activity')); - - $response = request_delete( - $path . '/' . $product->id, - ['query' => ['access_token' => 'token']] - ); - - $this->assertSame(6, table_count(static::$db, 'directus_activity')); - } -} diff --git a/tests/io/ActivityTest.php b/tests/io/ActivityTest.php deleted file mode 100644 index dbe9d12eeb..0000000000 --- a/tests/io/ActivityTest.php +++ /dev/null @@ -1,275 +0,0 @@ -db = create_db_connection(); - - $this->truncateTable(); - $this->dropSampleTables(); - $this->createSampleTables(); - - $currentTime = time(); - for ($i = 15; $i >= 1; $i--) { - $date = date( - 'Y-m-d', - strtotime( - sprintf('-%d day', $i), - $currentTime - ) - ); - table_insert($this->db, 'directus_activity', [ - 'id' => null, - 'action' => 'authentication', - 'action_by' => 1, - 'action_on' => sprintf('%s 15:52:37', $date), - 'ip' => '::1', - 'user_agent' => 'GuzzleHttp/6.2.1 curl/7.52.1 PHP/5.5.38', - 'collection' => 'directus_users', - 'item' => 1, - 'comment' => null - - ]); - } - } - - public function tearDown() - { - $this->truncateTable(); - $this->dropSampleTables(); - } - - public function testColumns() - { - $columns = [ - 'id', - 'action', - 'action_by', - 'action_on', - 'ip', - 'user_agent', - 'collection', - 'item', - 'edited_on', - 'comment', - 'comment_deleted_on', - ]; - - $path = 'activity'; - - // Not selecting columns - $response = request_get($path, ['access_token' => 'token']); - assert_response($this, $response, [ - 'data' => 'array', - 'fields' => $columns - ]); - - // Using Asterisk - $response = request_get($path, ['access_token' => 'token', 'fields' => '*']); - assert_response($this, $response, [ - 'data' => 'array', - 'fields' => $columns - ]); - - // Using a list of columns (array) - $response = request_get($path, ['access_token' => 'token', 'fields' => $columns]); - assert_response($this, $response, [ - 'data' => 'array', - 'fields' => $columns - ]); - - // Using a list of columns (csv) - $response = request_get($path, ['access_token' => 'token', 'fields' => implode(',', $columns)]); - assert_response($this, $response, [ - 'data' => 'array', - 'fields' => $columns - ]); - - // Selecting some columns (array) - $someColumns = ['id', 'action']; - $response = request_get($path, ['access_token' => 'token', 'fields' => $someColumns]); - assert_response($this, $response, [ - 'data' => 'array', - 'fields' => $someColumns - ]); - - // Selecting some columns (csv) - $response = request_get($path, ['access_token' => 'token', 'fields' => implode(',', $someColumns)]); - assert_response($this, $response, [ - 'data' => 'array', - 'fields' => $someColumns - ]); - } - - public function testMeta() - { - $path = 'activity'; - $response = request_get($path, [ - 'meta' => '*', - 'access_token' => 'token' - ]); - - assert_response($this, $response, [ - 'data' => 'array' - ]); - assert_response_meta($this, $response, [ - 'collection' => 'directus_activity', - 'type' => 'collection' - ]); - } - - public function testLimit() - { - $path = 'activity'; - $response = request_get($path, [ - 'meta' => '*', - 'access_token' => 'token', - 'limit' => 10 - ]); - - assert_response($this, $response, [ - 'count' => 10, - 'data' => 'array' - ]); - assert_response_meta($this, $response, [ - 'collection' => 'directus_activity', - 'type' => 'collection', - 'result_count' => 10 - ]); - } - - public function testId() - { - $path = 'activity/1'; - $response = request_get($path, [ - 'meta' => '*', - 'access_token' => 'token' - ]); - - assert_response($this, $response); - assert_response_meta($this, $response, [ - 'collection' => 'directus_activity', - 'type' => 'item' - ]); - } - - public function testActivity() - { - $this->truncateTable(); - - // Authenticate - request_post('auth/authenticate', [ - 'email' => 'admin@getdirectus.com', - 'password' => 'password' - ]); - - request_post('items/test', [ - 'name' => 'Product 1' - ], ['query' => ['access_token' => 'token']]); - - request_patch('items/test/1', [ - 'name' => 'Product 01' - ], ['query' => ['access_token' => 'token']]); - - request_delete('items/test/1', ['query' => ['access_token' => 'token']]); - - $response = request_get('activity', ['access_token' => 'token']); - - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 4 - ]); - - $result = response_to_object($response); - $data = $result->data; - $actions = [ - DirectusActivityTableGateway::ACTION_AUTHENTICATE, - DirectusActivityTableGateway::ACTION_CREATE, - DirectusActivityTableGateway::ACTION_UPDATE, - DirectusActivityTableGateway::ACTION_DELETE - ]; - - foreach ($data as $item) { - $this->assertSame(array_shift($actions), $item->action); - } - } - - public function testGetActivity() - { - $response = request_get('activity/1', ['access_token' => 'token']); - assert_response($this, $response); - - $this->truncateTable(); - - try { - $response = request_get('activity/1', ['access_token' => 'token']); - } catch (RequestException $e) { - $response = $e->getResponse(); - } - - assert_response_error($this, $response, [ - 'status' => 404, - 'code' => ItemNotFoundException::ERROR_CODE - ]); - } - - public function testCreateComment() - { - $response = request_post('activity/comment', [ - 'collection' => 'categories', - 'item' => 1, - 'comment' => 'a comment' - ], ['query' => ['access_token' => 'token']]); - - assert_response($this, $response, [ - 'data' => 'object' - ]); - - assert_response_data_contains($this, $response, [ - 'action' => DirectusActivityTableGateway::ACTION_COMMENT, - 'comment' => 'a comment' - ]); - } - - protected function truncateTable() - { - truncate_table($this->db, 'directus_activity'); - } - - protected function createSampleTables() - { - if (!$this->db) { - return; - } - - $query = 'CREATE TABLE `test` ( - `id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `name` varchar(100) NOT NULL, - PRIMARY KEY (`id`) - ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;'; - - $this->db->execute($query); - - table_insert($this->db, 'directus_collections', [ - 'collection' => 'test' - ]); - } - - protected function dropSampleTables() - { - drop_table($this->db, 'test'); - } -} diff --git a/tests/io/AuthenticationTest.php b/tests/io/AuthenticationTest.php deleted file mode 100644 index dc029360f3..0000000000 --- a/tests/io/AuthenticationTest.php +++ /dev/null @@ -1,226 +0,0 @@ - 'admin@getdirectus.com', - 'password' => 'password' - ]); - - assert_response($this, $response, [ - 'status' => 200, - 'public' => true - ]); - - $result = response_to_object($response); - $data = $result->data; - $this->assertObjectHasAttribute('token', $data); - $token = $data->token; - $this->assertTrue(JWTUtils::isJWT($token)); - $payload = JWTUtils::getPayload($token); - $this->assertInternalType('int', $payload->exp); - $this->assertInternalType('int', $payload->id); - // $this->assertInternalType('int', $payload->group); - - // Query String - $path = 'collections'; - $response = request_get($path, ['access_token' => $token]); - - assert_response($this, $response, [ - 'status' => 200, - 'data' => 'array' - ]); - - // Header Authorization - $path = 'collections'; - $response = request_get($path, [], [ - 'headers' => [ - 'Authorization' => 'Bearer ' . $token - ] - ]); - - assert_response($this, $response, [ - 'status' => 200, - 'data' => 'array' - ]); - - // Basic Auth - $path = 'collections'; - $response = request_get($path, [], ['auth' => [$token, null]]); - - assert_response($this, $response, [ - 'status' => 200, - 'data' => 'array' - ]); - } - - public function testRefreshToken() - { - $path = 'auth/authenticate'; - $response = request_post($path, [ - 'email' => 'admin@getdirectus.com', - 'password' => 'password' - ]); - - assert_response($this, $response, [ - 'status' => 200, - 'public' => true - ]); - - $result = response_to_object($response); - $currentToken = $result->data->token; - $currentPayload = JWTUtils::getPayload($currentToken); - - $path = 'auth/refresh'; - // wait a moment to refresh - sleep(2); - $response2 = request_post($path, [ - 'token' => $currentToken - ]); - - $result2 = response_to_object($response2); - $newToken = $result2->data->token; - $this->assertNotSame($newToken, $currentToken); - $newPayload = JWTUtils::getPayload($newToken); - - $this->assertTrue($newPayload->exp > $currentPayload->exp); - - // TODO: Can we test the setting ttl? - } - - public function testInvalidCredentials() - { - $path = 'auth/authenticate'; - $response = request_error_post($path, [ - 'email' => 'user@getdirectus.com', - 'password' => 'password' - ]); - - assert_response_error($this, $response, [ - 'status' => 404, - 'data' => 'array', - 'code' => InvalidUserCredentialsException::ERROR_CODE - ]); - } - - public function testDisabledUserCredentials() - { - $path = 'auth/authenticate'; - $response = request_error_post($path, [ - 'email' => 'disabled@getdirectus.com', - 'password' => 'password' - ]); - - assert_response_error($this, $response, [ - 'status' => 401, - 'data' => 'array', - 'code' => UserInactiveException::ERROR_CODE - ]); - } - - public function testValidation() - { - $path = 'auth/authenticate'; - $response = request_error_post($path, []); - - assert_response_error($this, $response, [ - 'status' => 422, - 'code' => InvalidRequestException::ERROR_CODE - ]); - - $response = request_error_post($path, [ - 'password' => 'password' - ]); - - assert_response_error($this, $response, [ - 'status' => 422, - 'code' => InvalidRequestException::ERROR_CODE - ]); - - $response = request_error_post($path, [ - 'email' => 'user@getdirectus.com' - ]); - - assert_response_error($this, $response, [ - 'status' => 422, - 'code' => InvalidRequestException::ERROR_CODE - ]); - } - - public function testInvalidTokenRefresh() - { - $path = 'auth/refresh'; - $response = request_error_post($path, [ - 'token' => 'token' - ]); - - assert_response_error($this, $response, [ - 'status' => 401, - 'code' => InvalidTokenException::ERROR_CODE - ]); - - // valid but expired token - $response = request_error_post($path, [ - 'token' => $this->generateExpiredToken() - ]); - - assert_response_error($this, $response, [ - 'status' => 401, - 'code' => ExpiredTokenException::ERROR_CODE - ]); - - // empty payload - $response = request_error_post($path, [ - 'token' => 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.W10.pwrFXDuy0W5KvU5BC7ZjwqssUKcYnkOFRKOUNkwhnkE' - ]); - - assert_response_error($this, $response, [ - 'status' => 401, - 'code' => InvalidTokenException::ERROR_CODE - ]); - } - - public function testDisabledUserToken() - { - $path = 'users'; - $response = request_error_get($path, [ - 'access_token' => 'disabled_token' - ]); - - assert_response_error($this, $response, [ - 'status' => 401, - 'code' => UserInactiveException::ERROR_CODE - ]); - } - - protected function generateExpiredToken() - { - $config = require __DIR__ . '/../../config/api.php'; - $secretKey = array_get($config, 'auth.secret_key'); - - $payload = [ - 'id' => 1, - 'type' => JWTUtils::TYPE_AUTH, - 'exp' => time() - 3600, - ]; - - return JWTUtils::encode($payload, $secretKey, 'HS256'); - } -} diff --git a/tests/io/CollectionPresetsTest.php b/tests/io/CollectionPresetsTest.php deleted file mode 100644 index 188ffcdf4e..0000000000 --- a/tests/io/CollectionPresetsTest.php +++ /dev/null @@ -1,169 +0,0 @@ - 'tabular', 'collection' => 'products'], - ['view_type' => 'tabular', 'collection' => 'products', 'user' => 2], - ['view_type' => 'tabular', 'collection' => 'orders', 'user' => 1], - ['view_type' => 'tabular', 'collection' => 'categories', 'user' => 1], - ['view_type' => 'tabular', 'collection' => 'orders', 'user' => 2], - ['view_type' => 'tabular', 'collection' => 'customers', 'user' => 1] - ]; - - public static function resetDatabase() - { - $db = create_db_connection(); - reset_table_id($db, 'directus_collection_presets', 4); - } - - public static function setUpBeforeClass() - { - static::resetDatabase(); - } - - public static function tearDownAfterClass() - { - static::resetDatabase(); - } - - public function testCreate() - { - $path = 'collection_presets'; - - $data = $this->data[0]; - $response = request_post($path, $data, ['query' => ['access_token' => 'token']]); - - assert_response($this, $response); - assert_response_data_contains($this, $response, $data); - } - - public function testUpdate() - { - $path = 'collection_presets/4'; - - $data = [ - 'collection' => 'products', - 'search_query' => 'a product' - ]; - $response = request_patch($path, $data, ['query' => ['access_token' => 'token']]); - - assert_response($this, $response); - assert_response_data_contains($this, $response, $data); - } - - public function testGetOne() - { - $path = 'collection_presets/4'; - - $data = [ - 'id' => 4, - 'collection' => 'products', - 'search_query' => 'a product' - ]; - - $response = request_get($path, ['access_token' => 'token']); - assert_response($this, $response); - assert_response_data_contains($this, $response, $data); - assert_response_data_fields($this, $response, [ - 'id', - 'title', - 'user', - 'role', - 'collection', - 'search_query', - 'filters', - 'view_type', - 'view_query', - 'view_options', - 'translation', - ]); - } - - public function testList() - { - $path = 'collection_presets'; - - $response = request_get($path, ['access_token' => 'token']); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 4 - ]); - } - - public function testDelete() - { - $path = 'collection_presets/4'; - $response = request_delete($path, ['query' => ['access_token' => 'token']]); - - assert_response_empty($this, $response); - } - - public function testAllUserCollectionPresets() - { - $path = 'collection_presets'; - $data = $this->data; - - foreach ($data as $item) { - request_post($path, $item, ['query' => ['access_token' => 'token']]); - } - - $response = request_get($path, [ - 'access_token' => 'token', - 'filter' => [ - 'user' => 1 - ] - ]); - - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 3 - ]); - - $response = request_get($path, [ - 'access_token' => 'token', - 'filter' => [ - 'user' => 2 - ] - ]); - - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 2 - ]); - } - - public function testAllCollectionPresets() - { - $path = 'collection_presets'; - - $response = request_get($path, [ - 'access_token' => 'token', - 'filter' => [ - 'collection' => 'products' - ] - ]); - - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 2 - ]); - - $response = request_get($path, [ - 'access_token' => 'token', - 'filter' => [ - 'collection' => 'customers' - ] - ]); - - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 1 - ]); - } -} diff --git a/tests/io/CollectionsTest.php b/tests/io/CollectionsTest.php deleted file mode 100644 index 175722ca1b..0000000000 --- a/tests/io/CollectionsTest.php +++ /dev/null @@ -1,322 +0,0 @@ - 'token' - ]; - - protected static $tableName = 'items'; - protected static $db; - - public static function resetDatabase() - { - drop_table(static::$db, static::$tableName); - } - - public static function setUpBeforeClass() - { - static::$db = create_db_connection(); - static::resetDatabase(); - } - - public static function tearDownAfterClass() - { - static::resetDatabase(); - } - - public function testCreate() - { - $data = [ - 'collection' => static::$tableName, - 'fields' => [ - [ - 'field' => 'id', - 'type' => 'integer', - 'datatype' => 'integer', - 'interface' => 'primary_key', - 'primary_key' => true, - 'auto_increment' => true, - 'signed' => false, - 'length' => 11, - ], - [ - 'field' => 'status', - 'type' => 'integer', - 'datatype' => 'integer', - 'interface' => 'status', - 'signed' => false, - 'length' => 11, - ], - [ - 'field' => 'sort', - 'type' => 'integer', - 'datatype' => 'integer', - 'interface' => 'sort', - 'signed' => false, - 'length' => 11, - ], - [ - 'field' => 'name', - 'interface' => 'text_input', - 'type' => 'string', - 'datatype' => 'VARCHAR', - 'length' => 255 - ] - ] - ]; - - $response = request_post('collections', $data, ['query' => $this->queryParams]); - assert_response($this, $response); - assert_response_data_contains($this, $response, ArrayUtils::pick($data, 'collection')); - - $this->assertTrue(table_exists(static::$db, static::$tableName)); - - // Has Directus tables record - $result = table_find(static::$db, 'directus_collections', [ - 'collection' => static::$tableName - ]); - $this->assertTrue(count($result) === 1); - - // Has columns records - $result = table_find(static::$db, 'directus_fields', [ - 'collection' => static::$tableName - ]); - $this->assertTrue(count($result) === 4); - } - - public function testGetOne() - { - $response = request_get('collections/' . static::$tableName, $this->queryParams); - assert_response($this, $response); - assert_response_data_contains($this, $response, [ - 'collection' => static::$tableName - ]); - - $response = request_error_get('collections/nonexisting', $this->queryParams); - assert_response_error($this, $response, [ - 'code' => CollectionNotFoundException::ERROR_CODE, - 'status' => 404 - ]); - } - - public function testUpdate() - { - $data = [ - 'hidden' => true, - 'single' => true - ]; - - $response = request_patch('collections/' . static::$tableName, $data, ['query' => $this->queryParams]); - assert_response($this, $response); - assert_response_data_contains($this, $response, array_merge([ - 'collection' => static::$tableName - ], $data)); - - // Change back - $data = [ - 'hidden' => false, - 'single' => false - ]; - - $response = request_patch('collections/' . static::$tableName, $data, ['query' => $this->queryParams]); - assert_response($this, $response); - assert_response_data_contains($this, $response, array_merge([ - 'collection' => static::$tableName - ], $data)); - - // Columns: Add one, Update one - $data = [ - 'fields' => [ - [ - 'field' => 'name', - 'length' => 64 - ], - [ - 'field' => 'datetime', - 'type' => 'datetime', - 'datatype' => 'datetime', - 'interface' => 'datetime', - 'required' => true - ] - ] - ]; - - $response = request_patch('collections/' . static::$tableName, $data, ['query' => $this->queryParams]); - assert_response($this, $response); - assert_response_data_contains($this, $response, [ - 'collection' => static::$tableName - ]); - - // Has the new columns records - $result = table_find(static::$db, 'directus_fields', [ - 'collection' => static::$tableName - ]); - $this->assertTrue(count($result) === 5); - - // ============================================================================= - // Columns: Add one - // ============================================================================= - $data = [ - 'fields' => [ - [ - 'field' => 'datetime_two', - 'type' => 'datetime', - 'datatype' => 'datetime', - 'interface' => 'datetime', - 'required' => true - ] - ] - ]; - - $response = request_patch('collections/' . static::$tableName, $data, ['query' => $this->queryParams]); - assert_response($this, $response); - assert_response_data_contains($this, $response, [ - 'collection' => static::$tableName - ]); - - // Has the new columns records - $result = table_find(static::$db, 'directus_fields', [ - 'collection' => static::$tableName - ]); - $this->assertTrue(count($result) === 6); - - // ============================================================================= - // Columns: Update one - // ============================================================================= - $data = [ - 'fields' => [ - [ - 'field' => 'datetime_two', - 'required' => false - ] - ] - ]; - - $response = request_patch('collections/' . static::$tableName, $data, ['query' => $this->queryParams]); - assert_response($this, $response); - assert_response_data_contains($this, $response, [ - 'collection' => static::$tableName - ]); - - // didn't add new columns information - $result = table_find(static::$db, 'directus_fields', [ - 'collection' => static::$tableName - ]); - $this->assertTrue(count($result) === 6); - } - - public function testList() - { - $response = request_get('collections', $this->queryParams); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 24 - // 15 core tables, - // categories, - // products, - // products_images - // news - // news_translations - // languages - // home - // home_news - // and static::$tableName - ]); - } - - public function testDelete() - { - $response = request_delete('collections/' . static::$tableName, ['query' => $this->queryParams]); - assert_response_empty($this, $response); - - $response = request_error_get('collections/' . static::$tableName, $this->queryParams); - assert_response_error($this, $response, [ - 'code' => CollectionNotFoundException::ERROR_CODE, - 'status' => 404 - ]); - - $this->assertFalse(table_exists(static::$db, static::$tableName)); - - // Empty collections records - $result = table_find(static::$db, 'directus_collections', [ - 'collection' => static::$tableName - ]); - $this->assertTrue(count($result) === 0); - - // empty fields records - $result = table_find(static::$db, 'directus_fields', [ - 'collection' => static::$tableName - ]); - $this->assertTrue(count($result) === 0); - } - - public function testUnmanagedTable() - { - $name = static::$tableName; - $path = 'collections/' . $name; - drop_table(static::$db, $name); - create_table(static::$db, $name); - - // GET COLLECTION (NOT MANAGED) - $response = request_get('collections/' . $name, $this->queryParams); - assert_response($this, $response); - assert_response_data_contains($this, $response, ['managed' => false]); - - // UPDATE COLLECTION (NOT MANAGED) - $response = request_error_patch($path, ['hidden' => true], ['query' => $this->queryParams]); - assert_response_error($this, $response, [ - 'code' => CollectionNotManagedException::ERROR_CODE, - 'status' => 404 - ]); - - $response = request_error_patch($path, ['hidden' => true, 'managed' => false], ['query' => $this->queryParams]); - assert_response_error($this, $response, [ - 'code' => CollectionNotManagedException::ERROR_CODE, - 'status' => 404 - ]); - - $response = request_patch($path, ['hidden' => true, 'managed' => true], ['query' => $this->queryParams]); - assert_response($this, $response); - assert_response_data_contains($this, $response, ['managed' => true]); - - // GET COLLECTION ALREADY MANAGED - $response = request_get('collections/' . $name, $this->queryParams); - assert_response($this, $response); - assert_response_data_contains($this, $response, ['managed' => true]); - - // UPDATE A COLLECTION MANAGED - $response = request_patch($path, ['hidden' => true], ['query' => $this->queryParams]); - assert_response($this, $response); - - // set managed to flag - $response = request_patch($path, ['managed' => false], ['query' => $this->queryParams]); - assert_response($this, $response); - assert_response_data_contains($this, $response, ['managed' => false]); - - - // GET COLLECTION (NOT MANAGED) - $response = request_get('collections/' . $name, $this->queryParams); - assert_response($this, $response); - assert_response_data_contains($this, $response, ['managed' => false]); - - // UPDATE COLLECTION (NOT MANAGED) - $response = request_error_patch($path, ['hidden' => true], ['query' => $this->queryParams]); - assert_response_error($this, $response, [ - 'code' => CollectionNotManagedException::ERROR_CODE, - 'status' => 404 - ]); - - $response = request_error_patch($path, ['hidden' => true, 'managed' => false], ['query' => $this->queryParams]); - assert_response_error($this, $response, [ - 'code' => CollectionNotManagedException::ERROR_CODE, - 'status' => 404 - ]); - } -} diff --git a/tests/io/FieldsTest.php b/tests/io/FieldsTest.php deleted file mode 100644 index 81f98b5f60..0000000000 --- a/tests/io/FieldsTest.php +++ /dev/null @@ -1,430 +0,0 @@ - 'token' - ]; - - /** - * @var Connection - */ - protected static $db; - - /** - * @var string - */ - protected static $tableName = 'test'; - protected static $testDateTime = 'datetime_test'; - - public static function resetDatabase() - { - drop_table(static::$db, static::$tableName); - drop_table(static::$db, static::$testDateTime); - } - - public static function setUpBeforeClass() - { - static::$db = create_db_connection(); - static::resetDatabase(); - } - - public static function tearDownAfterClass() - { - static::resetDatabase(); - } - - public function testCreate() - { - // Create a test table - $data = [ - 'collection' => static::$tableName, - 'fields' => [ - [ - 'field' => 'id', - 'type' => 'integer', - 'datatype' => 'integer', - 'primary_key' => true, - 'auto_increment' => true, - ] - ] - ]; - - $response = request_post('collections', $data, ['query' => $this->queryParams]); - assert_response($this, $response); - assert_response_data_contains($this, $response, [ - 'collection' => static::$tableName - ]); - - // -------------------------------------------------------------------- - $data = [ - 'field' => 'name', - 'length' => 100, - 'type' => 'string', - 'datatype' => 'varchar', - ]; - - $response = request_post('fields/' . static::$tableName, $data, ['query' => $this->queryParams]); - assert_response($this, $response); - assert_response_data_contains($this, $response, [ - 'field' => 'name', - 'type' => 'string', - ]); - - // Has columns records - $result = table_find(static::$db, 'directus_fields', [ - 'collection' => static::$tableName - ]); - $this->assertTrue(count($result) === 2); - $this->assertTrue(column_exists(static::$db, static::$tableName, 'name')); - } - - public function testCreateAliasFields() - { - $fieldsCount = 2; - $types = DataTypes::getAliasTypes(); - foreach ($types as $type) { - $data = [ - 'field' => $type, - 'type' => $type - ]; - - $response = request_post('fields/' . static::$tableName, $data, ['query' => $this->queryParams]); - assert_response($this, $response); - assert_response_data_contains($this, $response, $data); - - // Has columns records - $result = table_find(static::$db, 'directus_fields', [ - 'collection' => static::$tableName - ]); - - $fieldsCount++; - $this->assertTrue(count($result) === $fieldsCount); - $this->assertFalse(column_exists(static::$db, static::$tableName, $type)); - } - - // ---------------------------------------------------------------------------- - // change type to another alias type - // ---------------------------------------------------------------------------- - $typeIdx = count($types); - foreach ($types as $type) { - $typeIdx--; - $data = [ - 'type' => $types[$typeIdx] - ]; - - $path = sprintf('fields/%s/%s', static::$tableName, $type); - $response = request_patch($path, $data, ['query' => $this->queryParams]); - assert_response($this, $response); - assert_response_data_contains($this, $response, $data); - - // Has columns records - $result = table_find(static::$db, 'directus_fields', [ - 'collection' => static::$tableName - ]); - - $this->assertTrue(count($result) === $fieldsCount); - $this->assertFalse(column_exists(static::$db, static::$tableName, $type)); - } - - // ---------------------------------------------------------------------------- - // change alias type to a non-alias type - // ---------------------------------------------------------------------------- - foreach ($types as $type) { - $data = [ - 'type' => 'integer', - 'datatype' => 'integer', - ]; - - $path = sprintf('fields/%s/%s', static::$tableName, $type); - $response = request_patch($path, $data, ['query' => $this->queryParams]); - assert_response($this, $response); - assert_response_data_contains($this, $response, ArrayUtils::omit($data, 'datatype'), false); - - // Has columns records - $result = table_find(static::$db, 'directus_fields', [ - 'collection' => static::$tableName - ]); - - $this->assertTrue(count($result) === $fieldsCount); - $this->assertTrue(column_exists(static::$db, static::$tableName, $type)); - } - - // ---------------------------------------------------------------------------- - // change non-alias type to an alias type - // ---------------------------------------------------------------------------- - foreach ($types as $type) { - $data = [ - 'type' => $type - ]; - - $path = sprintf('fields/%s/%s', static::$tableName, $type); - $response = request_patch($path, $data, ['query' => $this->queryParams]); - assert_response($this, $response); - assert_response_data_contains($this, $response, $data); - - // Has columns records - $result = table_find(static::$db, 'directus_fields', [ - 'collection' => static::$tableName - ]); - - $this->assertTrue(count($result) === $fieldsCount); - $this->assertFalse(column_exists(static::$db, static::$tableName, $type)); - } - - foreach ($types as $type) { - $response = request_delete('fields/' . static::$tableName . '/' . $type, ['query' => $this->queryParams]); - assert_response_empty($this, $response); - } - } - - public function testCreateUnknownDataType() - { - // Create a test table - $data = [ - 'collection' => 'unknown_type', - 'fields' => [ - [ - 'field' => 'id', - 'datatype' => 'integer', - 'type' => 'primary_key', - 'primary_key' => true, - 'auto_increment' => true, - ], - [ - 'field' => 'test', - 'type' => 'unknown', - ] - ] - ]; - - $response = request_error_post('collections', $data, ['query' => $this->queryParams]); - assert_response_error($this, $response, [ - 'code' => UnknownTypeException::ERROR_CODE, - 'status' => 422 - ]); - } - - public function testUpdate() - { - $data = [ - 'field' => 'name', - 'length' => 255, - ]; - - $response = request_patch('fields/' . static::$tableName . '/name', $data, ['query' => $this->queryParams]); - assert_response($this, $response); - assert_response_data_contains($this, $response, [ - 'field' => 'name', - 'type' => 'string', - ]); - - // Has columns records - $result = table_find(static::$db, 'directus_fields', [ - 'collection' => static::$tableName - ]); - $this->assertSame(2, count($result)); - $this->assertTrue(column_exists(static::$db, static::$tableName, 'name')); - } - - public function testUpdateUnknownDataType() - { - $data = [ - 'type' => 'unknown', - 'datatype' => 'varchar', - 'length' => 255, - ]; - - $response = request_error_patch('fields/' . static::$tableName . '/name', $data, ['query' => $this->queryParams]); - assert_response_error($this, $response, [ - 'code' => UnknownTypeException::ERROR_CODE, - 'status' => 422 - ]); - } - - public function testGetOne() - { - $data = [ - 'field' => 'name', - 'collection' => 'test' - ]; - - $response = request_get('fields/' . static::$tableName . '/name', $this->queryParams); - assert_response($this, $response, [ - 'datatype', - 'default_value', - 'auto_increment', - 'primary_key', - 'unique', - 'signed', - 'length', - ]); - assert_response_data_contains($this, $response, $data); - $this->assertTrue(column_exists(static::$db, static::$tableName, 'name')); - } - - public function testUpdateOptions() - { - $options = [ - 'option' => true, - 'read_only' => false - ]; - - $data = [ - 'options' => $options - ]; - - // Using form_params convert true/false to "1"/"0" - $response = request_patch('fields/' . static::$tableName . '/name', $data, ['query' => $this->queryParams]); - assert_response($this, $response); - assert_response_data_contains($this, $response, [ - 'options' => json_decode(json_encode(['option' => 1, 'read_only' => 0])) - ], false); - - $data = [ - 'options' => $options - ]; - - $response = request_patch('fields/' . static::$tableName . '/name', $data, ['json' => true, 'query' => $this->queryParams]); - assert_response($this, $response); - assert_response_data_contains($this, $response, [ - 'options' => json_decode(json_encode($options)) - ], false); - } - - public function testGetOptions() - { - $response = request_get('fields/' . static::$tableName . '/name', $this->queryParams); - assert_response($this, $response, [ - 'has_fields' => true, - 'fields' => ['options'] - ]); - } - - public function testList() - { - $response = request_get('fields/' . static::$tableName, $this->queryParams); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 2 - ]); - } - - public function testDateTimeTypes() - { - $collectionName = static::$testDateTime; - - // Create a test table - $data = [ - 'collection' => $collectionName, - 'fields' => [ - [ - 'field' => 'id', - 'type' => 'integer', - 'datatype' => 'integer', - 'primary_key' => true, - 'auto_increment' => true, - ], - [ - 'field' => 'datetime', - 'type' => 'datetime', - 'datatype' => 'datetime', - ], - [ - 'field' => 'date', - 'type' => 'date', - 'datatype' => 'date', - ], - [ - 'field' => 'time', - 'type' => 'time', - 'datatype' => 'time', - ], - ] - ]; - - $response = request_post('collections', $data, ['query' => $this->queryParams]); - assert_response($this, $response); - assert_response_data_contains($this, $response, [ - 'collection' => $collectionName - ]); - - // Using ISO format - $datetime = new DateTimeUtils(); - $isoDateTime = $datetime->toISO8601Format(); - $data = [ - 'datetime' => $isoDateTime, - 'date' => $isoDateTime, - 'time' => $isoDateTime, - ]; - - $response = request_post('items/' . $collectionName, $data, ['query' => $this->queryParams]); - assert_response($this, $response); - assert_response_data_contains($this, $response, [ - 'datetime' => $datetime->toUTC()->toISO8601Format(), - 'date' => $datetime->toString($datetime::DEFAULT_DATE_FORMAT), - 'time' => $datetime->toString($datetime::DEFAULT_TIME_FORMAT), - ]); - - // Using Datetime format - $datetime = new DateTimeUtils(); - $datetimeValue = $datetime->toString(); - $data = [ - 'datetime' => $datetimeValue, - 'date' => $datetimeValue, - 'time' => $datetimeValue, - ]; - - $response = request_post('items/' . $collectionName, $data, ['query' => $this->queryParams]); - assert_response($this, $response); - assert_response_data_contains($this, $response, [ - 'datetime' => $datetime->toUTC()->toISO8601Format(), - 'date' => $datetime->toString($datetime::DEFAULT_DATE_FORMAT), - 'time' => $datetime->toString($datetime::DEFAULT_TIME_FORMAT), - ]); - - // Using its format - $datetime = new DateTimeUtils(); - $data = [ - 'datetime' => $datetime->toISO8601Format(), - 'date' => $datetime->toString($datetime::DEFAULT_DATE_FORMAT), - 'time' => $datetime->toString($datetime::DEFAULT_TIME_FORMAT), - ]; - - $response = request_post('items/' . $collectionName, $data, ['query' => $this->queryParams]); - assert_response($this, $response); - assert_response_data_contains($this, $response, [ - 'datetime' => $datetime->toUTC()->toISO8601Format(), - 'date' => $datetime->toString($datetime::DEFAULT_DATE_FORMAT), - 'time' => $datetime->toString($datetime::DEFAULT_TIME_FORMAT), - ]); - } - - public function testDelete() - { - $response = request_delete('fields/' . static::$tableName . '/name', ['query' => $this->queryParams]); - assert_response_empty($this, $response); - - $response = request_error_get('fields/'. static::$tableName . '/name', $this->queryParams); - assert_response_error($this, $response, [ - 'code' => FieldNotFoundException::ERROR_CODE, - 'status' => 404 - ]); - - $response = request_error_delete('fields/' . static::$tableName . '/id', ['query' => $this->queryParams]); - assert_response_error($this, $response, [ - 'code' => UnprocessableEntityException::ERROR_CODE, - 'status' => 422 - ]); - } -} diff --git a/tests/io/FilesTest.php b/tests/io/FilesTest.php deleted file mode 100644 index 2c3f5c2f59..0000000000 --- a/tests/io/FilesTest.php +++ /dev/null @@ -1,345 +0,0 @@ - 'token' - ]; - - protected static $db; - - /** - * @var string - */ - protected static $fileName = 'green.jpg'; - protected static $fileName2 = 'myphoto.jpg'; - - /** - * @var string - */ - protected static $uploadPath; - - public static function resetDatabase() - { - static::$uploadPath = realpath(__DIR__ . '/../../public/uploads/_/originals'); - - static::$db = create_db_connection(); - truncate_table(static::$db, 'directus_files'); - truncate_table(static::$db, 'directus_folders'); - - clear_storage(static::$uploadPath); - } - - public static function setUpBeforeClass() - { - static::resetDatabase(); - } - - public static function tearDownAfterClass() - { - static::resetDatabase(); - } - - public function testCreate() - { - $name = static::$fileName; - $data = [ - 'filename' => $name, - 'data' => $this->getImageBase64() - ]; - - $response = request_post('files', $data, ['query' => $this->queryParams]); - assert_response($this, $response); - assert_response_data_contains($this, $response, ['filename' => $name]); - - $this->assertTrue(file_exists(static::$uploadPath . '/' . $name)); - } - - public function testUnableBatchCreate() - { - $data = [ - [ - 'filename' => 'test1.jpg', - 'data' => $this->getImageBase64() - ], [ - 'filename' => 'test2.jpg', - 'data' => $this->getImageBase64() - ] - ]; - - $response = request_error_post('files', $data, ['query' => $this->queryParams]); - assert_response_error($this, $response, [ - 'status' => 400, - 'code' => BatchUploadNotAllowedException::ERROR_CODE, - ]); - } - - public function testCreateWithMultipart() - { - $name = 'image.jpg'; - $title = 'new file'; - - $response = request('POST', 'files', [ - 'multipart' => [ - [ - 'name' => 'filename', - 'contents' => $name - ], - [ - 'name' => 'title', - 'contents' => $title, - ], - [ - 'name' => 'data', - 'contents' => $this->getImageStream() - ] - ], - 'query' => $this->queryParams - ]); - - assert_response($this, $response); - assert_response_data_contains($this, $response, [ - 'filename' => $name, - 'title' => $title - ]); - - $this->assertTrue(file_exists(static::$uploadPath . '/' . $name)); - } - - public function testUpdate() - { - $data = [ - 'title' => 'Green background' - ]; - - $response = request_patch('files/1', $data, ['query' => $this->queryParams]); - assert_response($this, $response); - assert_response_data_contains($this, $response, array_merge(['id' => 1], $data)); - } - - public function testUnableBatchUpdateWithFiles() - { - // Update multiple files with different data - $data = [ - [ - 'id' => 1, - 'filename' => 'test1.jpg', - 'data' => $this->getImageBase64() - ], [ - 'id' => 2, - 'filename' => 'test2.jpg', - 'data' => $this->getImageBase64() - ] - ]; - - $response = request_error_patch('files', $data, ['query' => $this->queryParams]); - assert_response_error($this, $response, [ - 'status' => 400, - 'code' => BatchUploadNotAllowedException::ERROR_CODE, - ]); - - // Update multiple files with same data - $data = [ - 'filename' => 'test2.jpg', - 'data' => $this->getImageBase64() - ]; - - $response = request_error_patch('files/1,2', $data, ['query' => $this->queryParams]); - assert_response_error($this, $response, [ - 'status' => 400, - 'code' => BatchUploadNotAllowedException::ERROR_CODE, - ]); - } - - public function testGetOne() - { - $data = [ - 'id' => 1, - 'title' => 'Green background' - ]; - - $response = request_get('files/1', $this->queryParams); - assert_response($this, $response); - assert_response_data_contains($this, $response, $data); - } - - public function testCreateFileWithFolder() - { - $data = [ - 'name' => 'photos' - ]; - - $response = request_post('files/folders', $data, ['query' => $this->queryParams]); - assert_response($this, $response); - assert_response_data_contains($this, $response, $data); - $folder = response_get_data($response); - - // Upload file - $name = static::$fileName2; - $data = [ - 'folder' => $folder->id, - 'filename' => $name, - 'data' => $this->getImageBase64() - ]; - - $response = request_post('files', $data, ['query' => $this->queryParams]); - assert_response($this, $response); - assert_response_data_contains($this, $response, ['filename' => $name]); - - $this->assertTrue(file_exists(static::$uploadPath . '/' . $name)); - } - - public function testUpdateFolder() - { - $data = [ - 'id' => 1, - 'name' => 'pictures', - 'parent_folder' => null - ]; - - $response = request_patch('files/folders/1', $data, ['query' => $this->queryParams]); - assert_response($this, $response); - assert_response_data_contains($this, $response, $data); - } - - public function testGetOneFolder() - { - $data = [ - 'id' => 1, - 'name' => 'pictures', - 'parent_folder' => null - ]; - - $response = request_get('files/folders/1', $this->queryParams); - assert_response($this, $response); - assert_response_data_contains($this, $response, $data); - } - - public function testListFolder() - { - $response = request_get('files/folders', $this->queryParams); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 1 - ]); - } - - public function testDeleteFolder() - { - $response = request_delete('files/folders/1', ['query' => $this->queryParams]); - assert_response_empty($this, $response); - - $response = request_error_get('files/folders/1', $this->queryParams); - assert_response_error($this, $response, [ - 'code' => ItemNotFoundException::ERROR_CODE, - 'status' => 404 - ]); - } - - public function testList() - { - $response = request_get('files', $this->queryParams); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 3 - ]); - } - - public function testBatchUpdateWithoutFiles() - { - // Update multiple files with different data - $data = [ - [ - 'id' => 1, - 'title' => 'one', - ], [ - 'id' => 2, - 'title' => 'two', - ] - ]; - - $response = request_patch('files', $data, ['query' => $this->queryParams]); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 2 - ]); - - $items = response_get_data($response); - $this->assertSame('one', $items[0]->title); - $this->assertSame('two', $items[1]->title); - - // Update multiple files with same data - $data = [ - 'title' => 'one-two' - ]; - - $response = request_patch('files/1,2', $data, ['query' => $this->queryParams]); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 2 - ]); - - $items = response_get_data($response); - $this->assertSame('one-two', $items[0]->title); - $this->assertSame('one-two', $items[1]->title); - } - - public function testDelete() - { - $response = request_delete('files/1', ['query' => $this->queryParams]); - assert_response_empty($this, $response); - - $response = request_error_get('files/1', $this->queryParams); - assert_response_error($this, $response, [ - 'code' => ItemNotFoundException::ERROR_CODE, - 'status' => 404 - ]); - - $this->assertFalse(file_exists(static::$uploadPath . '/' . static::$fileName)); - - // delete filename 2 - $response = request_delete('files/3', ['query' => $this->queryParams]); - assert_response_empty($this, $response); - - $response = request_error_get('files/3', $this->queryParams); - assert_response_error($this, $response, [ - 'code' => ItemNotFoundException::ERROR_CODE, - 'status' => 404 - ]); - - $this->assertFalse(file_exists(static::$uploadPath . '/' . static::$fileName2)); - } - - public function testCreateWithoutExtension() - { - $name = 'image'; - $data = [ - 'filename' => $name, - 'data' => $this->getImageBase64() - ]; - - $response = request_post('files', $data, ['query' => $this->queryParams]); - assert_response($this, $response); - assert_response_data_contains($this, $response, ['filename' => $name]); - - $this->assertTrue(file_exists(static::$uploadPath . '/' . $name)); - } - - protected function getImageBase64() - { - // TODO: Allow the data alone - // TODO: Guess the data type - // TODO: Confirm is base64 - return 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAUDBAQEAwUEBAQFBQUGBwwIBwcHBw8LCwkMEQ8SEhEPERETFhwXExQaFRERGCEYGh0dHx8fExciJCIeJBweHx7/2wBDAQUFBQcGBw4ICA4eFBEUHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh7/wAARCAB4AKADASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAX/xAAUEAEAAAAAAAAAAAAAAAAAAAAA/8QAFgEBAQEAAAAAAAAAAAAAAAAAAAUH/8QAFBEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEQMRAD8AugILDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH/9k='; - } - - protected function getImageStream() - { - return fopen(__DIR__ . '/../assets/image.jpeg', 'r'); - } -} diff --git a/tests/io/GeneralTest.php b/tests/io/GeneralTest.php deleted file mode 100644 index 7d53ab688a..0000000000 --- a/tests/io/GeneralTest.php +++ /dev/null @@ -1,21 +0,0 @@ - false - ]); - assert_response_contents($this, $response, 'pong', [ - 'status' => 200 - ]); - } - - public function testErrorExtraInformation() - { - // TODO: Switch between production and development to add more error information - } -} diff --git a/tests/io/ItemsBatchTest.php b/tests/io/ItemsBatchTest.php deleted file mode 100644 index 18be28d0e7..0000000000 --- a/tests/io/ItemsBatchTest.php +++ /dev/null @@ -1,322 +0,0 @@ - 2, 'name' => 'Old Product', 'price' => 4.99, 'category_id' => 1], - ['status' => 1, 'name' => 'Basic Product', 'price' => 9.99, 'category_id' => 1], - ['status' => 1, 'name' => 'Premium Product', 'price' => 19.99, 'category_id' => 1], - ['status' => 1, 'name' => 'Enterprise Product', 'price' => 49.99] - ]; - - protected static $db; - - public static function resetData() - { - static::$db = create_db_connection(); - - truncate_table(static::$db, 'products_images'); - truncate_table(static::$db, 'products'); - truncate_table(static::$db, 'categories'); - fill_table(static::$db, 'categories', [ - ['name' => 'Old Category'] - ]); - fill_table(static::$db, 'products', static::$data); - $uploadPath = realpath(__DIR__ . '/../../public/uploads/_/originals'); - clear_storage($uploadPath); - - request_patch('fields/products/status', ['options' => [ - 'status_mapping' => [ - '1' => [ - 'name' => 'Published' - ], - 2 => [ - 'name' => 'Draft', - 'published' => false - ] - ] - ]], ['query' => ['access_token' => 'token']]); - } - - public static function setUpBeforeClass() - { - static::resetData(); - } - - public static function tearDownAfterClass() - { - static::resetData(); - } - - public function testCreate() - { - $path = 'items/products'; - $data = [ - [ - 'status' => 1, - 'name' => 'Special Product', - 'price' => 999.99, - 'category_id' => 1 - ], - [ - 'status' => 1, - 'name' => 'Special Product 2', - 'price' => 999.99, - 'category_id' => 1 - ] - ]; - - $response = request_post($path, $data, ['query' => ['access_token' => 'token']]); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 2 - ]); - - $result = response_to_object($response); - foreach ((array)$result->data as $index => $newData) { - $newData = (array)$newData; - unset($data[$index]['price']); - - foreach ($data[$index] as $key => $value) { - $this->assertArrayHasKey($key, $newData); - $this->assertSame($newData[$key], $value, $key); - } - } - } - - public function testUpdate() - { - $path = 'items/products'; - - $data = [ - [ - 'id' => 5, - 'name' => 'Xpecial Product', - ], - [ - 'id' => 6, - 'name' => 'xpecial Product 2' - ] - ]; - - $response = request_patch($path, $data, ['query' => ['access_token' => 'token']]); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 2 - ]); - - $result = response_to_object($response); - foreach ($result->data as $index => $newData) { - $newData = (array)$newData; - - foreach ($data[$index] as $key => $value) { - $this->assertArrayHasKey($key, $newData); - $this->assertSame($newData[$key], $value); - } - } - } - - public function testUpdateSameData() - { - $path = 'items/products/5,6'; - - $data = [ - 'name' => 'Super Xpecial' - ]; - - $response = request_patch($path, $data, ['query' => ['access_token' => 'token']]); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 2 - ]); - - $result = response_to_object($response); - foreach ($result->data as $index => $newData) { - $newData = (array)$newData; - - foreach ($data as $key => $value) { - $this->assertArrayHasKey($key, $newData); - $this->assertSame($newData[$key], $value); - } - } - } - - public function testCreateWithManyToOne() - { - $path = 'items/products'; - $data = [ - [ - 'status' => 1, - 'name' => 'Premium Product 1', - 'price' => 9999.99, - 'category_id' => [ - 'name' => 'Premium Cat 1' - ] - ], - [ - 'status' => 1, - 'name' => 'Premium Product 2', - 'price' => 9999.99, - 'category_id' => [ - 'name' => 'Premium Cat 2' - ] - ] - ]; - - $response = request_post($path, $data, ['query' => ['access_token' => 'token']]); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 2 - ]); - - $response = request_get('items/products/7,8', ['access_token' => 'token', 'fields' => '*, category_id.*']); - $responseData = response_get_data($response); - $this->assertInternalType('array', $responseData); - - foreach ($responseData as $index => $newData) { - unset($data[$index]['price']); - $newData = (array)$newData; - - $categoryId = ArrayUtils::pull($data[$index], 'category_id'); - $this->assertArrayHasKey('category_id', $newData); - $category = ArrayUtils::pull($newData, 'category_id'); - - foreach ($data[$index] as $key => $value) { - $this->assertSame($value, $newData[$key]); - } - - $this->assertInternalType('object', $category); - $this->assertSame($category->name, $categoryId['name']); - } - } - - public function testCreateWithOneToMany() - { - $path = 'items/categories'; - $data = [ - [ - 'name' => 'New Category 1', - 'products' => [[ - 'status' => '1', - 'name' => 'New Product 1', - 'price' => 100, - ]] - ], - [ - 'name' => 'New Category 2', - 'products' => [[ - 'status' => '1', - 'name' => 'New Product 2', - 'price' => 200, - ]] - ] - ]; - - $response = request_post($path, $data, ['query' => ['access_token' => 'token']]); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 2 - ]); - - $response = request_get('items/categories/4,5', ['access_token' => 'token', 'fields' => '*, products.*']); - $responseData = response_get_data($response); - $this->assertInternalType('array', $responseData); - - foreach ($responseData as $index => $newData) { - $newData = (array) $newData; - $this->assertArrayHasKey('products', $newData); - $products = ArrayUtils::pull($newData, 'products'); - $productsRelated = ArrayUtils::pull($data[$index], 'products'); - foreach ($data[$index] as $key => $value) { - $this->assertSame($value, $newData[$key]); - } - - $this->assertInternalType('array', $products); - $this->assertSame($products[0]->name, $productsRelated[0]['name']); - } - } - - public function testCreateWithManyToMany() - { - $path = 'items/products'; - $data = [ - [ - 'status' => 1, - 'name' => 'Limited Product 1', - 'price' => 1010.01, - 'images' => [ - [ - 'file_id' => [ - 'filename' => 'potato1.jpg', - 'title' => 'Image of a fake potato 1', - 'data' => '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAUDBAQEAwUEBAQFBQUGBwwIBwcHBw8LCwkMEQ8SEhEPERETFhwXExQaFRERGCEYGh0dHx8fExciJCIeJBweHx7/2wBDAQUFBQcGBw4ICA4eFBEUHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh7/wAARCAB4AKADASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAX/xAAUEAEAAAAAAAAAAAAAAAAAAAAA/8QAFgEBAQEAAAAAAAAAAAAAAAAAAAUH/8QAFBEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEQMRAD8AugILDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH/9k=' - ] - ] - ] - ], - [ - 'status' => 1, - 'name' => 'Limited Product 2', - 'price' => 1010.01, - 'images' => [ - [ - 'file_id' => [ - 'filename' => 'potato2.jpg', - 'title' => 'Image of a fake potato 2', - 'data' => '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAUDBAQEAwUEBAQFBQUGBwwIBwcHBw8LCwkMEQ8SEhEPERETFhwXExQaFRERGCEYGh0dHx8fExciJCIeJBweHx7/2wBDAQUFBQcGBw4ICA4eFBEUHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh7/wAARCAB4AKADASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAX/xAAUEAEAAAAAAAAAAAAAAAAAAAAA/8QAFgEBAQEAAAAAAAAAAAAAAAAAAAUH/8QAFBEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEQMRAD8AugILDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH/9k=' - ] - ] - ] - ] - ]; - - $response = request_post($path, $data, ['query' => ['access_token' => 'token']]); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 2 - ]); - - $response = request_get('items/products/11,12', ['access_token' => 'token', 'fields' => '*, images.*.*']); - $responseData = response_get_data($response); - $this->assertInternalType('array', $responseData); - - foreach ($responseData as $index => $newData) { - $newData = (array)$newData; - $this->assertArrayHasKey('images', $newData); - $images = ArrayUtils::pull($newData, 'images'); - $imagesRelated = ArrayUtils::pull($data[$index], 'images'); - unset($data[$index]['price']); - foreach ($data[$index] as $key => $value) { - $this->assertSame($value, $newData[$key]); - } - - $this->assertInternalType('array', $images); - $this->assertSame($images[0]->file_id->title, $imagesRelated[0]['file_id']['title']); - } - } - - public function estDelete() - { - $path = 'items/products/5,6,7,8,9'; - $response = request_delete($path, ['query' => ['access_token' => 'token']]); - assert_response_empty($this, $response); - $response = request_get($path, ['access_token' => 'token']); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 0 - ]); - - $path = 'items/categories/3,4'; - $response = request_delete($path, ['query' => ['access_token' => 'token']]); - assert_response_empty($this, $response); - $response = request_get($path, ['access_token' => 'token']); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 0 - ]); - } -} diff --git a/tests/io/ItemsTest.php b/tests/io/ItemsTest.php deleted file mode 100644 index b86ddba3aa..0000000000 --- a/tests/io/ItemsTest.php +++ /dev/null @@ -1,1143 +0,0 @@ - 2, 'name' => 'Old Product', 'price' => 4.99, 'category_id' => 1], - ['status' => 1, 'name' => 'Basic Product', 'price' => 9.99, 'category_id' => 1], - ['status' => 1, 'name' => 'Premium Product', 'price' => 19.99, 'category_id' => 1], - ['status' => 1, 'name' => 'Enterprise Product', 'price' => 49.99] - ]; - - protected static $db; - - public static function resetData() - { - static::$db = create_db_connection(); - - truncate_table(static::$db, 'products_images'); - truncate_table(static::$db, 'products'); - truncate_table(static::$db, 'categories'); - fill_table(static::$db, 'categories', [ - ['name' => 'Old Category'] - ]); - fill_table(static::$db, 'products', static::$data); - $uploadPath = realpath(__DIR__ . '/../../public/uploads/_/originals'); - clear_storage($uploadPath); - - request_patch('fields/products/status', ['options' => [ - 'status_mapping' => [ - '1' => [ - 'name' => 'Published' - ], - 2 => [ - 'name' => 'Draft', - 'published' => false - ] - ] - ]], ['query' => ['access_token' => 'token']]); - } - - public static function setUpBeforeClass() - { - static::resetData(); - } - - public static function tearDownAfterClass() - { - static::resetData(); - } - - public function testNotDirectAccess() - { - // Fetching items - foreach ($this->systemTables as $table) { - $path = 'items/' . $table; - $response = request_error_get($path); - - assert_response_error($this, $response, [ - 'code' => ForbiddenSystemTableDirectAccessException::ERROR_CODE, - 'status' => 401 - ]); - } - - // Creating Item - foreach ($this->systemTables as $table) { - $path = 'items/' . $table; - request_error_post($path, [ - 'code' => ForbiddenSystemTableDirectAccessException::ERROR_CODE, - 'status' => 401 - ]); - } - - // Fetching a Item - foreach ($this->systemTables as $table) { - foreach (['GET', 'PATCH', 'PUT', 'DELETE'] as $method) { - $path = 'items/' . $table . '/1'; - call_user_func('request_error_' . strtolower($method), $path, [ - 'code' => ForbiddenSystemTableDirectAccessException::ERROR_CODE, - 'status' => 401 - ]); - } - } - - // Batch - foreach ($this->systemTables as $table) { - foreach (['POST', 'PATCH', 'PUT', 'DELETE'] as $method) { - $path = 'items/' . $table . '/batch'; - call_user_func('request_error_' . strtolower($method), $path, [ - 'code' => ForbiddenSystemTableDirectAccessException::ERROR_CODE, - 'status' => 401 - ]); - } - } - } - - public function testListFields() - { - $fields = [ - 'id', - 'status', - 'name', - 'price', - 'category_id' - ]; - $path = 'items/products'; - - // ============================================================================= - // GET ALL FIELDS - // ============================================================================= - $response = request_get($path, ['access_token' => 'token']); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 3, - 'fields' => $fields - ]); - - // TODO: Fix casting DECIMAL - // it's converting 9.99 to things like 9.9900000000000002131628207280300557613372802734375 - // assert_response_data_contains($this, $response, static::$data); - - // ============================================================================= - // GET ALL FIELDS WITH ASTERISK - // ============================================================================= - $response = request_get($path, [ - 'fields' => '*', - 'access_token' => 'token' - ]); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 3, - 'fields' => $fields - ]); - - // ============================================================================= - // GET SINGLE FIELD - // ============================================================================= - foreach ($fields as $field) { - // ============================================================================= - // GET ALL FIELDS WITH ASTERISK - // ============================================================================= - $response = request_get($path, [ - 'fields' => $field, - 'access_token' => 'token' - ]); - - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 3, - 'fields' => [ - $field - ] - ]); - } - - // ============================================================================= - // GET ALL FIELDS WITH CSV - // ============================================================================= - $response = request_get($path, [ - 'fields' => implode(',', $fields), - 'access_token' => 'token' - ]); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 3, - 'fields' => $fields - ]); - - // ============================================================================= - // GET SOME FIELDS WITH CSV - // ============================================================================= - $response = request_get($path, [ - 'fields' => 'id, name', - 'access_token' => 'token' - ]); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 3, - 'fields' => ['id', 'name'] - ]); - } - - public function testItemFields() - { - $fields = [ - 'id', - 'status', - 'name', - 'price', - 'category_id' - ]; - $path = 'items/products/2'; - - // ============================================================================= - // GET ALL FIELDS - // ============================================================================= - $response = request_get($path, ['access_token' => 'token']); - assert_response($this, $response, [ - 'fields' => $fields - ]); - - // ============================================================================= - // GET ALL FIELDS WITH ASTERISK - // ============================================================================= - $response = request_get($path, [ - 'fields' => '*', - 'access_token' => 'token' - ]); - assert_response($this, $response, [ - 'fields' => $fields - ]); - - // ============================================================================= - // GET SINGLE FIELD - // ============================================================================= - foreach ($fields as $field) { - // ============================================================================= - // GET ALL FIELDS WITH ASTERISK - // ============================================================================= - $response = request_get($path, [ - 'fields' => $field, - 'access_token' => 'token' - ]); - - assert_response($this, $response, [ - 'fields' => [ - $field - ] - ]); - } - - // ============================================================================= - // GET ALL FIELDS WITH CSV - // ============================================================================= - $response = request_get($path, [ - 'fields' => implode(',', $fields), - 'access_token' => 'token' - ]); - assert_response($this, $response, [ - 'fields' => $fields - ]); - - // ============================================================================= - // GET SOME FIELDS WITH CSV - // ============================================================================= - $response = request_get($path, [ - 'fields' => 'id, name', - 'access_token' => 'token' - ]); - assert_response($this, $response, [ - 'fields' => ['id', 'name'] - ]); - } - - public function testLimit() - { - $path = 'items/products'; - - // ============================================================================= - // TEST LIMIT (lower than items count) - // ============================================================================= - $response = request_get($path, ['access_token' => 'token', 'limit' => 1]); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 1 - ]); - - // ============================================================================= - // TEST LIMIT (higher than items count) - // ============================================================================= - $response = request_get($path, ['access_token' => 'token', 'limit' => 5]); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 3 - ]); - } - - public function testOffset() - { - $path = 'items/products'; - - // ============================================================================= - // TEST LIMIT (lower than items count) - // ============================================================================= - $response = request_get($path, ['access_token' => 'token', 'limit' => 1, 'offset' => 1]); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 1 - ]); - - $result = response_to_object($response); - $data = $result->data; - $first = (array)array_shift($data); - $expected = static::$data[2]; - // because the output is casted wrong - unset($expected['price']); - foreach ($expected as $key => $value) { - $this->assertArrayHasKey($key, $first); - $this->assertSame($value, $first[$key]); - } - } - - public function testId() - { - $path = 'items/products'; - - // ============================================================================= - // FETCH BY ONE ID: Return a single object, not an array of one item - // ============================================================================= - $response = request_get($path . '/2', ['access_token' => 'token']); - assert_response($this, $response); - - // ============================================================================= - // FETCH BY CSV - // ============================================================================= - $response = request_get($path . '/2,3', ['access_token' => 'token']); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 2 - ]); - - // ============================================================================= - // FETCH BY CSV: One non-existent - // ============================================================================= - $response = request_get($path . '/2,3,10', ['access_token' => 'token']); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 2 - ]); - } - - public function testStatus() - { - $path = 'items/products'; - - // ============================================================================= - // TEST WITH ASTERISK: ALL STATUSES - // ============================================================================= - $response = request_get($path, ['access_token' => 'token', 'status' => '*']); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 4 - ]); - - // ============================================================================= - // TEST WITH ONE STATUS - // ============================================================================= - $response = request_get($path, ['access_token' => 'token', 'status' => 1]); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 3 - ]); - - $response = request_get($path, ['access_token' => 'token', 'status' => 2]); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 1 - ]); - - // ============================================================================= - // TEST WITH CSV STATUSES - // ============================================================================= - $response = request_get($path, ['access_token' => 'token', 'status' => '1,2']); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 4 - ]); - - // ============================================================================= - // TEST WITHOUT PARAM - // ============================================================================= - $response = request_get($path, ['access_token' => 'token']); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 3 - ]); - } - - public function testSort() - { - $path = 'items/products'; - - // ============================================================================= - // TEST DEFAULT SORTING - // ============================================================================= - $response = request_get($path, ['access_token' => 'token']); - $result = response_to_object($response); - $data = $result->data; - - $first = array_shift($data); - $last = array_pop($data); - $expectedFirst = static::$data[1]; - $expectedLast = static::$data[3]; - - $this->assertSame($expectedFirst['name'], $first->name); - $this->assertSame($expectedLast['name'], $last->name); - - // ============================================================================= - // TEST DEFAULT SORTING SAME AS ID - // ============================================================================= - $response = request_get($path, ['access_token' => 'token', 'sort' => 'id']); - $result = response_to_object($response); - $data = $result->data; - - $first = array_shift($data); - $last = array_pop($data); - $expectedFirst = static::$data[1]; - $expectedLast = static::$data[3]; - - $this->assertSame($expectedFirst['name'], $first->name); - $this->assertSame($expectedLast['name'], $last->name); - - // ============================================================================= - // TEST DESCENDING SORTING - // ============================================================================= - $response = request_get($path, ['access_token' => 'token', 'sort' => '-id']); - $result = response_to_object($response); - $data = $result->data; - - $first = array_shift($data); - $last = array_pop($data); - $expectedFirst = static::$data[3]; - $expectedLast = static::$data[1]; - - $this->assertSame($expectedFirst['name'], $first->name); - $this->assertSame($expectedLast['name'], $last->name); - } - - public function testQ() - { - $path = 'items/products'; - - $response = request_get($path, ['access_token' => 'token', 'q' => 'Product']); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 3 - ]); - - $response = request_get($path, ['access_token' => 'token', 'q' => 'Basic']); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 1 - ]); - - $response = request_get($path, ['access_token' => 'token', 'q' => 'Old Product']); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 0 - ]); - } - - public function testFilterEqual() - { - $path = 'items/products'; - - // ============================================================================= - // EQUAL ID: HIDDEN STATUS - // ============================================================================= - $response = request_get($path, [ - 'access_token' => 'token', - 'filter' => ['id' => 1] - ]); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 0 - ]); - - // ============================================================================= - // EQUAL ID: VISIBLE STATUS - // ============================================================================= - $response = request_get($path, [ - 'access_token' => 'token', - 'filter' => ['id' => 2] - ]); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 1 - ]); - - // ============================================================================= - // EQUAL NAME - // ============================================================================= - $response = request_get($path, [ - 'access_token' => 'token', - 'filter' => ['name' => 'Basic Product'] - ]); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 1 - ]); - - // ============================================================================= - // EQ - EQUAL ID: HIDDEN STATUS - // ============================================================================= - $response = request_get($path, [ - 'access_token' => 'token', - 'filter' => ['id' => ['eq' => 1]] - ]); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 0 - ]); - - // ============================================================================= - // EQ - EQUAL ID: VISIBLE STATUS - // ============================================================================= - $response = request_get($path, [ - 'access_token' => 'token', - 'filter' => ['id' => ['eq' => 2]] - ]); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 1 - ]); - - // ============================================================================= - // EQ - EQUAL NAME - // ============================================================================= - $response = request_get($path, [ - 'access_token' => 'token', - 'filter' => ['name' => ['eq' => 'Basic Product']] - ]); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 1 - ]); - } - - public function testCreate() - { - $path = 'items/products'; - $data = [ - 'status' => 1, - 'name' => 'Special Product', - 'price' => 999.99, - 'category_id' => 1 - ]; - - $response = request_post($path, $data, ['query' => ['access_token' => 'token']]); - assert_response($this, $response); - - $result = response_to_object($response); - $newData = (array)$result->data; - unset($data['price']); - - foreach ($data as $key => $value) { - $this->assertArrayHasKey($key, $newData); - $this->assertSame($newData[$key], $value); - } - } - - public function testUpdate() - { - $path = 'items/products/5'; - $data = [ - 'name' => 'Xpecial Product', - 'category_id' => 2 - ]; - - $response = request_patch($path, $data, ['query' => ['access_token' => 'token']]); - assert_response($this, $response); - - $result = response_to_object($response); - $newData = (array)$result->data; - unset($data['price']); - - foreach ($data as $key => $value) { - $this->assertArrayHasKey($key, $newData); - $this->assertSame($newData[$key], $value); - } - } - - public function testCreateWithRelation() - { - $path = 'items/products'; - $data = [ - 'status' => 1, - 'name' => 'Premium Product', - 'price' => 9999.99, - 'category_id' => [ - 'name' => 'Premium Cat' - ] - ]; - - $response = request_post($path, $data, ['query' => ['access_token' => 'token']]); - assert_response($this, $response); - - $response = request_get('items/products/6', ['access_token' => 'token', 'fields' => '*, category_id.*']); - $responseDataObject = response_get_data($response); - $this->assertInternalType('object', $responseDataObject); - $responseDataArray = (array) $responseDataObject; - - unset($data['price']); - $categoryId = ArrayUtils::pull($data, 'category_id'); - $this->assertArrayHasKey('category_id', $responseDataArray); - $category = ArrayUtils::pull($responseDataArray, 'category_id'); - foreach ($data as $key => $value) { - $this->assertSame($value, $responseDataArray[$key]); - } - - $this->assertInternalType('object', $category); - $this->assertSame($category->name, $categoryId['name']); - - // ============================================================================= - // TEST O2M - // ============================================================================= - $path = 'items/categories'; - $data = [ - 'name' => 'New Category', - 'products' => [[ - 'status' => 1, - 'name' => 'New Product', - 'price' => 100 - ]] - ]; - - $response = request_post($path, $data, ['query' => ['access_token' => 'token']]); - assert_response($this, $response); - - $response = request_get('items/categories/3', ['access_token' => 'token', 'fields' => '*, products.*']); - $responseDataObject = response_get_data($response); - $this->assertInternalType('object', $responseDataObject); - $responseDataArray = (array) $responseDataObject; - - $this->assertArrayHasKey('products', $responseDataArray); - $products = ArrayUtils::pull($responseDataArray, 'products'); - $productsRelated = ArrayUtils::pull($data, 'products'); - foreach ($data as $key => $value) { - $this->assertSame($value, $responseDataArray[$key]); - } - - $this->assertInternalType('array', $products); - $this->assertSame($products[0]->name, $productsRelated[0]['name']); - - // ============================================================================= - // TEST M2M - // ============================================================================= - $path = 'items/products'; - $data = [ - 'status' => 1, - 'name' => 'Limited Product', - 'price' => 1010.01, - 'images' => [ - [ - 'file_id' => [ - 'filename' => 'potato.jpg', - 'title' => 'Image of a fake potato', - 'data' => '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAUDBAQEAwUEBAQFBQUGBwwIBwcHBw8LCwkMEQ8SEhEPERETFhwXExQaFRERGCEYGh0dHx8fExciJCIeJBweHx7/2wBDAQUFBQcGBw4ICA4eFBEUHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh7/wAARCAB4AKADASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAX/xAAUEAEAAAAAAAAAAAAAAAAAAAAA/8QAFgEBAQEAAAAAAAAAAAAAAAAAAAUH/8QAFBEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEQMRAD8AugILDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH/9k=' - ] - ] - ] - ]; - - $response = request_post($path, $data, ['query' => ['access_token' => 'token']]); - assert_response($this, $response); - - $response = request_get('items/products/8', ['access_token' => 'token', 'fields' => '*, images.*.*']); - $responseDataObject = response_get_data($response); - $this->assertInternalType('object', $responseDataObject); - $responseDataArray = (array) $responseDataObject; - - $this->assertArrayHasKey('images', $responseDataArray); - $images = ArrayUtils::pull($responseDataArray, 'images'); - $imagesRelated = ArrayUtils::pull($data, 'images'); - unset($data['price']); - foreach ($data as $key => $value) { - $this->assertSame($value, $responseDataArray[$key]); - } - - $this->assertInternalType('array', $images); - $this->assertSame($images[0]->file_id->title, $imagesRelated[0]['file_id']['title']); - } - - public function testList() - { - $path = 'items/categories'; - $response = request_get($path, ['access_token' => 'token']); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 3 - ]); - - $path = 'items/products'; - $response = request_get($path, ['access_token' => 'token']); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 7 - ]); - } - - public function testStatusInterfaceMapping() - { - request_patch( - 'fields/products/status', ['options' => null], - ['query' => ['access_token' => 'token'], 'json' => true] - ); - truncate_table(static::$db, 'directus_settings'); - - $response = request_error_get('items/products', ['access_token' => 'token']); - assert_response_error($this, $response); - - // {"status_mapping": {"1":{"name":"Published","published":true},"2":{"name":"Draft","published":false}}} - // Insert global status mapping - $data = [ - 'scope' => 'status', - 'key' => 'status_mapping', - 'value' => json_encode([ - 'one' => [ - 'name' => 'Published' - ], - 'two' => [ - 'name' => 'Draft' - ] - ]) - ]; - request_post('settings', $data, ['query' => ['access_token' => 'token']]); - - $response = request_error_get('items/products', ['access_token' => 'token']); - assert_response_error($this, $response); - - // update global status mapping - $data = [ - 'value' => json_encode([ - '1' => [ - 'name' => 'Published' - ], - '2' => [ - 'name' => 'Draft', - 'published' => false - ] - ]) - ]; - request_patch('settings/1', $data, ['query' => ['access_token' => 'token']]); - - $response = request_get('items/products', ['access_token' => 'token']); - assert_response($this, $response, [ - 'data' => 'array' - ]); - - // update status mapping on field interface with string-type - $options = [ - 'status_mapping' => [ - 'one' => [ - 'name' => 'Published' - ], - 'two' => [ - 'name' => 'Draft' - ] - ] - ]; - request_patch('fields/products/status', ['options' => $options], ['query' => ['access_token' => 'token']]); - - $response = request_error_get('items/products', ['access_token' => 'token']); - assert_response_error($this, $response); - - // update status mapping on field interface with integer-type - $options = [ - 'status_mapping' => [ - 1 => [ - 'name' => 'Published' - ], - 2 => [ - 'name' => 'Draft' - ] - ] - ]; - request_patch('fields/products/status', ['options' => $options], ['query' => ['access_token' => 'token']]); - - $response = request_get('items/products', ['access_token' => 'token']); - assert_response($this, $response, [ - 'data' => 'array' - ]); - - // update status mapping on field interface with numeric-type - $options = [ - 'status_mapping' => [ - '1' => [ - 'name' => 'Published' - ], - '2' => [ - 'name' => 'Draft' - ] - ] - ]; - request_patch('fields/products/status', ['options' => $options], ['query' => ['access_token' => 'token']]); - - $response = request_get('items/products', ['access_token' => 'token']); - assert_response($this, $response, [ - 'data' => 'array' - ]); - } - - public function testDelete() - { - $path = 'items/products/5'; - $response = request_delete($path, ['query' => ['access_token' => 'token']]); - assert_response_empty($this, $response); - - $path = 'items/products/6'; - $response = request_delete($path, ['query' => ['access_token' => 'token']]); - assert_response_empty($this, $response); - - $path = 'items/categories/3'; - $response = request_delete($path, ['query' => ['access_token' => 'token']]); - assert_response_empty($this, $response); - } - - public function testSoftDeleteNonAdmins() - { - $data = array_merge([ - 'role' => 3, - 'collection' => 'products', - 'status' => 1 - ], Acl::PERMISSION_FULL); - - $response = request_post('permissions', $data, ['query' => ['access_token' => 'token']]); - assert_response($this, $response); - - $path = 'items/products'; - $data = ['name' => 'deleted product', 'status' => 0, 'price' => 0]; - $response = request_post($path, $data, ['query' => ['access_token' => 'token']]); - assert_response($this, $response); - - // Admin - $response = request_get($path, ['access_token' => 'token']); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 6 - ]); - - $response = request_get($path, ['access_token' => 'token', 'status' => '*']); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 7 - ]); - - $response = request_get($path . '/9', ['access_token' => 'token', 'status' => '*']); - assert_response($this, $response); - assert_response_data_contains($this, $response, ArrayUtils::omit($data, 'price')); - - // Non-Admin - $response = request_get($path, ['access_token' => 'intern_token']); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 5 - ]); - - $response = request_get($path, ['access_token' => 'intern_token', 'status' => '*']); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 5 - ]); - - $response = request_error_get($path . '/9', ['access_token' => 'intern_token', 'status' => '*']); - assert_response_error($this, $response, [ - 'status' => 404, - 'code' => ItemNotFoundException::ERROR_CODE - ]); - } - - public function testLangOneItem() - { - $path = 'items/news/1'; - $response = request_get($path, ['access_token' => 'token', 'fields' => '*.*']); - $result = response_get_data($response); - - $this->assertObjectHasAttribute('translations', $result); - $this->assertInternalType('array', $result->translations); - $this->assertCount(3, $result->translations); - - // wildcard - $response = request_get($path, ['access_token' => 'token', 'fields' => '*.*', 'lang' => '*']); - $result = response_get_data($response); - - $this->assertObjectHasAttribute('translations', $result); - $this->assertInternalType('array', $result->translations); - $this->assertCount(3, $result->translations); - - // one language - $response = request_get($path, ['access_token' => 'token', 'fields' => '*.*', 'lang' => 'en']); - $result = response_get_data($response); - - $this->assertObjectHasAttribute('translations', $result); - $this->assertInternalType('array', $result->translations); - $this->assertCount(1, $result->translations); - - // non-existing language - $response = request_get($path, ['access_token' => 'token', 'fields' => '*.*', 'lang' => 'de']); - $result = response_get_data($response); - - $this->assertObjectHasAttribute('translations', $result); - $this->assertInternalType('array', $result->translations); - $this->assertCount(0, $result->translations); - } - - public function testLangList() - { - $path = 'items/news'; - $response = request_get($path, ['access_token' => 'token', 'fields' => '*.*']); - $result = response_get_data($response); - - foreach ($result as $item) { - $this->assertObjectHasAttribute('translations', $item); - $this->assertInternalType('array', $item->translations); - } - } - - public function testLangRelatedOneItem() - { - $path = 'items/home/1'; - $response = request_get($path, ['access_token' => 'token', 'fields' => '*.*.*.*']); - $result = response_get_data($response); - - $this->assertObjectHasAttribute('news', $result); - $homeNews = $result->news; - $this->assertInternalType('array', $homeNews); - $this->assertObjectHasAttribute('news_id', $homeNews[0]); - $news = $homeNews[0]->news_id; - $this->assertObjectHasAttribute('translations', $news); - $this->assertInternalType('array', $news->translations); - $this->assertCount(3, $news->translations); - - // wildcard - $response = request_get($path, ['access_token' => 'token', 'fields' => '*.*.*.*', 'lang' => '*']); - $result = response_get_data($response); - - $this->assertObjectHasAttribute('news', $result); - $homeNews = $result->news; - $this->assertInternalType('array', $homeNews); - $this->assertObjectHasAttribute('news_id', $homeNews[0]); - $news = $homeNews[0]->news_id; - $this->assertObjectHasAttribute('translations', $news); - $this->assertInternalType('array', $news->translations); - $this->assertCount(3, $news->translations); - - // one language - $response = request_get($path, ['access_token' => 'token', 'fields' => '*.*.*.*', 'lang' => 'en']); - $result = response_get_data($response); - - $this->assertObjectHasAttribute('news', $result); - $homeNews = $result->news; - $this->assertInternalType('array', $homeNews); - $this->assertObjectHasAttribute('news_id', $homeNews[0]); - $news = $homeNews[0]->news_id; - $this->assertObjectHasAttribute('translations', $news); - $this->assertInternalType('array', $news->translations); - $this->assertCount(1, $news->translations); - - // non-existing language - $response = request_get($path, ['access_token' => 'token', 'fields' => '*.*.*.*', 'lang' => 'de']); - $result = response_get_data($response); - - $this->assertObjectHasAttribute('news', $result); - $homeNews = $result->news; - $this->assertInternalType('array', $homeNews); - $this->assertObjectHasAttribute('news_id', $homeNews[0]); - $news = $homeNews[0]->news_id; - $this->assertObjectHasAttribute('translations', $news); - $this->assertInternalType('array', $news->translations); - $this->assertCount(0, $news->translations); - } - - public function testWithRelationAndParams() - { - $path = 'items/products'; - $data = [ - 'status' => 1, - 'name' => 'Test', - 'price' => 9999.99, - 'category_id' => [ - 'name' => 'Premium Cat' - ] - ]; - - $testM2O = function ($response, $data) { - assert_response($this, $response); - $responseDataObject = response_get_data($response); - $this->assertInternalType('object', $responseDataObject); - $responseDataArray = (array) $responseDataObject; - - unset($data['price']); - $categoryId = ArrayUtils::pull($data, 'category_id'); - $this->assertArrayHasKey('category_id', $responseDataArray); - $category = ArrayUtils::pull($responseDataArray, 'category_id'); - foreach ($data as $key => $value) { - $this->assertSame($value, $responseDataArray[$key]); - } - - $this->assertInternalType('object', $category); - $this->assertSame($category->name, $categoryId['name']); - }; - - $response = request_post($path, $data, ['query' => ['fields' => '*.*', 'access_token' => 'token']]); - $testM2O($response, $data); - $id = response_get_data($response)->id; - - $response = request_get('items/products/' . $id, ['access_token' => 'token', 'fields' => '*, category_id.*']); - $testM2O($response, $data); - - $newData = ['name' => 'Test 2']; - $response = request_patch('items/products/' . $id, $newData, ['query' => ['fields' => '*.*', 'access_token' => 'token']]); - $testM2O($response, array_merge($data, $newData)); - - // TEST O2M - $path = 'items/categories'; - $data = [ - 'name' => 'New Category', - 'products' => [[ - 'status' => 1, - 'name' => 'New Product', - 'price' => 100 - ]] - ]; - - $testO2M = function ($response, $data) { - assert_response($this, $response); - $responseDataObject = response_get_data($response); - $this->assertInternalType('object', $responseDataObject); - $responseDataArray = (array) $responseDataObject; - - $this->assertArrayHasKey('products', $responseDataArray); - $products = ArrayUtils::pull($responseDataArray, 'products'); - $productsRelated = ArrayUtils::pull($data, 'products'); - foreach ($data as $key => $value) { - $this->assertSame($value, $responseDataArray[$key]); - } - - $this->assertInternalType('array', $products); - $this->assertSame($products[0]->name, $productsRelated[0]['name']); - }; - - $response = request_post($path, $data, ['query' => ['access_token' => 'token', 'fields' => '*, products.*']]); - $testO2M($response, $data); - $id = response_get_data($response)->id; - - $response = request_get('items/categories/' . $id, ['access_token' => 'token', 'fields' => '*, products.*']); - $testO2M($response, $data); - - $newData = ['name' => 'New Category 2']; - $response = request_patch('items/categories/' . $id, $newData, ['query' => ['fields' => '*, products.*', 'access_token' => 'token']]); - $testO2M($response, array_merge($data, $newData)); - - // TEST M2M - $path = 'items/products'; - $data = [ - 'status' => 1, - 'name' => 'Limited Product', - 'price' => 1010.01, - 'images' => [ - [ - 'file_id' => [ - 'filename' => 'potato.jpg', - 'title' => 'Image of a fake potato', - 'data' => '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAUDBAQEAwUEBAQFBQUGBwwIBwcHBw8LCwkMEQ8SEhEPERETFhwXExQaFRERGCEYGh0dHx8fExciJCIeJBweHx7/2wBDAQUFBQcGBw4ICA4eFBEUHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh7/wAARCAB4AKADASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAX/xAAUEAEAAAAAAAAAAAAAAAAAAAAA/8QAFgEBAQEAAAAAAAAAAAAAAAAAAAUH/8QAFBEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEQMRAD8AugILDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH/9k=' - ] - ] - ] - ]; - - $testM2M = function ($response, $data) { - assert_response($this, $response); - - $responseDataObject = response_get_data($response); - $this->assertInternalType('object', $responseDataObject); - $responseDataArray = (array) $responseDataObject; - - $this->assertArrayHasKey('images', $responseDataArray); - $images = ArrayUtils::pull($responseDataArray, 'images'); - $imagesRelated = ArrayUtils::pull($data, 'images'); - unset($data['price']); - foreach ($data as $key => $value) { - $this->assertSame($value, $responseDataArray[$key]); - } - - $this->assertInternalType('array', $images); - $this->assertSame($images[0]->file_id->title, $imagesRelated[0]['file_id']['title']); - }; - - $response = request_post($path, $data, ['query' => ['fields' => '*, images.*.*', 'access_token' => 'token']]); - $testM2M($response, $data); - $id = response_get_data($response)->id; - - $response = request_get('items/products/' . $id, ['access_token' => 'token', 'fields' => '*, images.*.*']); - $testM2M($response, $data); - - $newData = ['name' => 'Limited Product 2']; - $response = request_patch('items/products/' . $id, $newData, ['query' => ['fields' => '*, images.*.*', 'access_token' => 'token']]); - $testM2M($response, array_merge($data, $newData)); - } - - public function testListMeta() - { - $path = 'items/products'; - $response = request_get($path, ['access_token' => 'token', 'meta' => '*']); - assert_response($this, $response, [ - 'data' => 'array' - ]); - assert_response_meta($this, $response, [ - 'collection' => 'products', - 'type' => 'collection', - ]); - assert_response_meta_fields($this, $response, [ - 'collection', - 'type', - 'result_count', - 'total_count', - 'status_count', - ]); - } - - public function testItemMeta() - { - $path = 'items/products/1'; - $response = request_get($path, ['access_token' => 'token', 'meta' => '*']); - assert_response($this, $response); - assert_response_meta($this, $response, [ - 'collection' => 'products', - 'type' => 'item', - ]); - assert_response_meta_fields($this, $response, [ - 'collection', - 'type', - ]); - } -} diff --git a/tests/io/PermissionsTest.php b/tests/io/PermissionsTest.php deleted file mode 100644 index 584767858a..0000000000 --- a/tests/io/PermissionsTest.php +++ /dev/null @@ -1,1713 +0,0 @@ - 'token' - ]; - - protected $internQueryParams = [ - 'access_token' => 'intern_token' - ]; - - protected static $db = null; - protected $internGroup = 3; - protected $adminGroup = 1; - - protected static $data = [ - ['status' => 2, 'name' => 'Old Product', 'price' => 4.99, 'category_id' => 1], - ['status' => 1, 'name' => 'Basic Product', 'price' => 9.99, 'category_id' => 1], - ['status' => 1, 'name' => 'Premium Product', 'price' => 19.99, 'category_id' => 1], - ['status' => 1, 'name' => 'Enterprise Product', 'price' => 49.99] - ]; - - public static function resetDatabase() - { - static::$db = $db = create_db_connection(); - reset_table_id($db, 'directus_permissions', 1); - truncate_table($db, 'products'); - truncate_table($db, 'posts'); - truncate_table($db, 'articles'); - fill_table($db, 'products', static::$data); - } - - public static function setUpBeforeClass() - { - static::dropTestTable(); - static::createTestTable(); - static::resetDatabase(); - } - - public static function tearDownAfterClass() - { - static::resetDatabase(); - static::dropTestTable(); - } - - public function testCreate() - { - // Intern can't see products - $response = request_error_get('items/products', $this->internQueryParams); - assert_response_error($this, $response); - - $data = [ - 'role' => 3, - 'collection' => 'products', - 'read' => Acl::LEVEL_FULL - ]; - - $response = request_post('permissions', $data, ['query' => $this->queryParams]); - assert_response($this, $response); - assert_response_data_contains($this, $response, $data); - - // Intern can see products - $response = request_get('items/products', $this->internQueryParams); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 3 - ]); - } - - public function testUpdate() - { - $productData = [ - 'status' => 1, - 'name' => 'Good Product', - 'price' => 10.00 - ]; - request_post('items/products', $productData, ['query' => $this->queryParams]); - - // Intern can't update products - $response = request_error_patch('items/products/5', ['query' => $this->internQueryParams]); - assert_response_error($this, $response); - - $data = [ - 'update' => Acl::LEVEL_FULL - ]; - - $response = request_patch('permissions/1', $data, ['query' => $this->queryParams]); - assert_response($this, $response); - assert_response_data_contains($this, $response, array_merge(['id' => 1], $data)); - - // Intern can update products - $data = [ - 'name' => 'Excellent Product' - ]; - $response = request_patch('items/products/5', $data, ['query' => $this->internQueryParams]); - assert_response($this, $response); - assert_response_data_contains($this, $response, $data); - } - - public function testGetOne() - { - $data = [ - 'id' => 1, - 'collection' => 'products', - 'read' => Acl::LEVEL_FULL, - 'update' => Acl::LEVEL_FULL - ]; - - $response = request_get('permissions/1', $this->queryParams); - assert_response($this, $response); - assert_response_data_contains($this, $response, $data); - } - - public function testReadOneWithMinePermissionsWithoutOwner() - { - $data = [ - 'id' => 1, - 'collection' => 'products', - 'read' => Acl::LEVEL_MINE, - ]; - - $response = request_patch('permissions/1', $data, ['query' => $this->queryParams]); - assert_response($this, $response); - assert_response_data_contains($this, $response, array_merge(['id' => 1], $data)); - - $response = request_error_get('items/products/1', $this->internQueryParams); - assert_response_error($this, $response, [ - 'status' => 404, - 'code' => ItemNotFoundException::ERROR_CODE - ]); - } - - public function testList() - { - $response = request_get('permissions', $this->queryParams); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 1 - ]); - } - - public function testReadAllMineWithoutOwner() - { - $response = request_get('items/products', $this->internQueryParams); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 0 - ]); - } - - public function testGroupPermissions() - { - $params = array_merge([ - 'filter' => [ - 'role' => 3 - ] - ], $this->queryParams); - - $response = request_get('permissions', $params); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 1 - ]); - } - - public function testTablePermissions() - { - $params = array_merge([ - 'filter' => [ - 'collection' => 'products' - ] - ], $this->queryParams); - - $response = request_get('permissions', $params); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 1 - ]); - } - - public function testDelete() - { - $response = request_delete('permissions/1', ['query' => $this->queryParams]); - assert_response_empty($this, $response); - - $response = request_error_get('permissions/1', $this->queryParams); - assert_response_error($this, $response, [ - 'code' => ItemNotFoundException::ERROR_CODE, - 'status' => 404 - ]); - - // Intern can't see products - $response = request_error_get('items/products', $this->internQueryParams); - assert_response_error($this, $response); - } - - public function testCreateAndRead() - { - truncate_table(static::$db, 'directus_permissions'); - // Intern can't read posts - $response = request_error_get('items/posts', $this->internQueryParams); - assert_response_error($this, $response); - - // Intern can't create posts - $data = [ - 'title' => 'Post 1' - ]; - - $response = request_error_post('items/posts', $data, ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionCreateException::ERROR_CODE - ]); - - // ---------------------------------------------------------------------------- - // Intern CAN create but CANNOT READ - $this->addPermissionTo($this->internGroup, 'posts', [ - 'create' => Acl::LEVEL_MINE - ]); - - $data = [ - 'title' => 'Post 1', - 'status' => 1 - ]; - - $response = request_post('items/posts', $data, ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - - // Intern cannot read posts - $response = request_error_get('items/products/1', $this->internQueryParams); - assert_response_error($this, $response, [ - 'status' => 404, - 'code' => ItemNotFoundException::ERROR_CODE - ]); - - // ---------------------------------------------------------------------------- - // Intern Can read their items - $this->updatePermission(1, [ - 'read' => Acl::LEVEL_MINE - ]); - - // Intern can read posts - $response = request_get('items/posts/1', $this->internQueryParams); - assert_response($this, $response); - - $data = ['title' => 'Post 2']; - $response = request_post('items/posts', $data, ['query' => $this->internQueryParams]); - assert_response($this, $response); - assert_response_data_contains($this, $response, $data); - } - - public function testStatusCreate() - { - $this->tryStatusCreate('posts', 2, 1); - } - - public function testStringStatusCreate() - { - $this->tryStatusCreate('articles', 'draft', 'published'); - } - - public function testStatusRead() - { - $publishedStatus = 1; - $draftStatus = 2; - $noPermissionStatusOne = 0; - $noPermissionStatusTwo = 3; - $this->tryStatusRead('posts', $publishedStatus, $draftStatus, $noPermissionStatusOne, $noPermissionStatusTwo); - } - - public function testStringStatusRead() - { - $publishedStatus = 'published'; - $draftStatus = 'draft'; - $noPermissionStatusOne = 'deleted'; - $noPermissionStatusTwo = 'under_review'; - $this->tryStatusRead('articles', $publishedStatus, $draftStatus, $noPermissionStatusOne, $noPermissionStatusTwo); - } - - public function testStatusUpdate() - { - $this->tryStatusUpdate('posts'); - } - - public function testStringUpdate() - { - $this->tryStatusUpdate('articles'); - } - - public function testStatusDelete() - { - $this->tryStatusDelete('posts'); - } - - public function testStringStatusDelete() - { - $this->tryStatusDelete('articles'); - } - - public function tryStatusDelete($collection) - { - truncate_table(static::$db, 'directus_permissions'); - $this->resetTestItems($collection); - $data = $this->getItemsData($this->getStatuses($collection)); - - // ---------------------------------------------------------------------------- - // Intern CANNOT delete posts - - $response = request_error_delete('items/'.$collection.'/1', ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionDeleteException::ERROR_CODE - ]); - - $response = request_error_delete('items/'.$collection.'/5', ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionDeleteException::ERROR_CODE - ]); - - $response = request_error_delete('items/'.$collection.'/9', ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionDeleteException::ERROR_CODE - ]); - - // ---------------------------------------------------------------------------- - // Intern CAN delete their own posts BUT CANNOT read any posts - $this->addPermissionTo($this->internGroup, $collection, [ - 'status' => null, - 'delete' => Acl::LEVEL_MINE - ]); - - $response = request_delete('items/'.$collection.'/1', ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - table_insert(static::$db, $collection, array_merge(['id' => 1], $data['data0'])); - - $response = request_error_delete('items/'.$collection.'/5', ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionDeleteException::ERROR_CODE - ]); - - $response = request_error_delete('items/'.$collection.'/9', ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionDeleteException::ERROR_CODE - ]); - - // ---------------------------------------------------------------------------- - // Intern CAN update their own group posts BUT CANNOT read any posts - $this->updatePermission(1, [ - 'delete' => Acl::LEVEL_ROLE - ]); - - $response = request_delete('items/'.$collection.'/1', ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - table_insert(static::$db, $collection, array_merge(['id' => 1], $data['data0'])); - - $response = request_error_delete('items/'.$collection.'/5', ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionDeleteException::ERROR_CODE - ]); - - $response = request_delete('items/'.$collection.'/9', ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - table_insert(static::$db, $collection, array_merge(['id' => 9], $data['data8'])); - - // ---------------------------------------------------------------------------- - // Intern CAN update any posts BUT CANNOT read any posts - $this->updatePermission(1, [ - 'delete' => Acl::LEVEL_FULL - ]); - - $response = request_delete('items/'.$collection.'/1', ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - table_insert(static::$db, $collection, array_merge(['id' => 1], $data['data0'])); - - $response = request_delete('items/'.$collection.'/5', ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - table_insert(static::$db, $collection, array_merge(['id' => 5], $data['data4'])); - - $response = request_delete('items/'.$collection.'/9', ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - table_insert(static::$db, $collection, array_merge(['id' => 9], $data['data8'])); - - // ---------------------------------------------------------------------------- - // UPDATE + READ PERMISSION - // ---------------------------------------------------------------------------- - - // ---------------------------------------------------------------------------- - // Intern CAN update any posts BUT CAN only read their own posts - $this->updatePermission(1, [ - 'delete' => Acl::LEVEL_FULL, - 'read' => Acl::LEVEL_MINE - ]); - - $response = request_delete('items/'.$collection.'/1', ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - table_insert(static::$db, $collection, array_merge(['id' => 1], $data['data0'])); - - $response = request_delete('items/'.$collection.'/5', ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - table_insert(static::$db, $collection, array_merge(['id' => 5], $data['data4'])); - - $response = request_delete('items/'.$collection.'/9', ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - table_insert(static::$db, $collection, array_merge(['id' => 9], $data['data8'])); - - // ---------------------------------------------------------------------------- - // Intern CAN update any posts BUT CAN only read their own group posts - $this->updatePermission(1, [ - 'delete' => Acl::LEVEL_FULL, - 'read' => Acl::LEVEL_ROLE - ]); - - $response = request_delete('items/'.$collection.'/1', ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - table_insert(static::$db, $collection, array_merge(['id' => 1], $data['data0'])); - - $response = request_delete('items/'.$collection.'/5', ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - table_insert(static::$db, $collection, array_merge(['id' => 5], $data['data4'])); - - $response = request_delete('items/'.$collection.'/9', ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - table_insert(static::$db, $collection, array_merge(['id' => 9], $data['data8'])); - - // ---------------------------------------------------------------------------- - // Intern CAN update any posts AND CAN read any posts - $this->updatePermission(1, [ - 'delete' => Acl::LEVEL_FULL, - 'read' => Acl::LEVEL_FULL - ]); - - $response = request_delete('items/'.$collection.'/1', ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - table_insert(static::$db, $collection, array_merge(['id' => 1], $data['data0'])); - - $response = request_delete('items/'.$collection.'/5', ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - table_insert(static::$db, $collection, array_merge(['id' => 5], $data['data4'])); - - $response = request_delete('items/'.$collection.'/9', ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - table_insert(static::$db, $collection, array_merge(['id' => 9], $data['data8'])); - - // ---------------------------------------------------------------------------- - // PERMISSION BY STATUS - // ---------------------------------------------------------------------------- - truncate_table(static::$db, 'directus_permissions'); - - // ---------------------------------------------------------------------------- - // Intern CANNOT update posts with any status - $statuses = $this->getStatuses($collection); - foreach ($statuses as $status) { - $this->addPermissionTo($this->internGroup, $collection, [ - 'status' => $status, - 'delete' => Acl::LEVEL_NONE - ]); - } - - $response = request_error_delete('items/'.$collection.'/1', ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionDeleteException::ERROR_CODE - ]); - - $response = request_error_delete('items/'.$collection.'/2', ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionDeleteException::ERROR_CODE - ]); - - $response = request_error_delete('items/'.$collection.'/3', ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionDeleteException::ERROR_CODE - ]); - - $response = request_error_delete('items/'.$collection.'/4', ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionDeleteException::ERROR_CODE - ]); - - $response = request_error_delete('items/'.$collection.'/5', ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionDeleteException::ERROR_CODE - ]); - - $response = request_error_delete('items/'.$collection.'/6', ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionDeleteException::ERROR_CODE - ]); - - $response = request_error_delete('items/'.$collection.'/7', ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionDeleteException::ERROR_CODE - ]); - - $response = request_error_delete('items/'.$collection.'/8', ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionDeleteException::ERROR_CODE - ]); - - // ---------------------------------------------------------------------------- - // WITH STATUS: 0 - // ---------------------------------------------------------------------------- - // Intern CAN update their own posts with status = 0 - $currentStatus = $statuses[0]; - $this->updatePermission(1, [ - 'status' => $currentStatus, - 'delete' => Acl::LEVEL_MINE - ]); - - $response = request_delete('items/'.$collection.'/1', ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - table_insert(static::$db, $collection, array_merge(['id' => 1], $data['data0'])); - - $response = request_error_delete('items/'.$collection.'/2', ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionDeleteException::ERROR_CODE - ]); - - $response = request_error_delete('items/'.$collection.'/5', ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionDeleteException::ERROR_CODE - ]); - - $response = request_error_delete('items/'.$collection.'/9', ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionDeleteException::ERROR_CODE - ]); - - // ---------------------------------------------------------------------------- - // Intern CAN update their own group posts with status = 0 - $this->updatePermission(1, [ - 'status' => $currentStatus, - 'delete' => Acl::LEVEL_ROLE - ]); - - $response = request_delete('items/'.$collection.'/1', ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - table_insert(static::$db, $collection, array_merge(['id' => 1], $data['data0'])); - - $response = request_error_delete('items/'.$collection.'/5', ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionDeleteException::ERROR_CODE - ]); - - $response = request_delete('items/'.$collection.'/9', ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - table_insert(static::$db, $collection, array_merge(['id' => 9], $data['data8'])); - - // ---------------------------------------------------------------------------- - // Intern CAN update any posts with status = 0 - $this->updatePermission(1, [ - 'status' => $currentStatus, - 'delete' => Acl::LEVEL_FULL - ]); - - $response = request_delete('items/'.$collection.'/1', ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - table_insert(static::$db, $collection, array_merge(['id' => 1], $data['data0'])); - - $response = request_error_delete('items/'.$collection.'/2', ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionDeleteException::ERROR_CODE - ]); - - $response = request_delete('items/'.$collection.'/5', ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - table_insert(static::$db, $collection, array_merge(['id' => 5], $data['data4'])); - - $response = request_delete('items/'.$collection.'/9', ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - table_insert(static::$db, $collection, array_merge(['id' => 9], $data['data8'])); - - // ---------------------------------------------------------------------------- - // WITH STATUS: 1 - // ---------------------------------------------------------------------------- - // Intern CAN update their own posts with status = 1 - $currentStatus = $statuses[1]; - $this->updatePermission(2, [ - 'status' => $currentStatus, - 'delete' => Acl::LEVEL_MINE - ]); - - $response = request_delete('items/'.$collection.'/2', ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - table_insert(static::$db, $collection, array_merge(['id' => 2], $data['data1'])); - - $response = request_error_delete('items/'.$collection.'/3', ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionDeleteException::ERROR_CODE - ]); - - $response = request_error_delete('items/'.$collection.'/6', ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionDeleteException::ERROR_CODE - ]); - - $response = request_error_delete('items/'.$collection.'/10', ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionDeleteException::ERROR_CODE - ]); - - // ---------------------------------------------------------------------------- - // Intern CAN update their own group posts with status = 1 - $this->updatePermission(2, [ - 'status' => $currentStatus, - 'delete' => Acl::LEVEL_ROLE - ]); - - $response = request_delete('items/'.$collection.'/2', ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - table_insert(static::$db, $collection, array_merge(['id' => 2], $data['data1'])); - - $response = request_error_delete('items/'.$collection.'/6', ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionDeleteException::ERROR_CODE - ]); - - $response = request_delete('items/'.$collection.'/10', ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - table_insert(static::$db, $collection, array_merge(['id' => 10], $data['data9'])); - - // ---------------------------------------------------------------------------- - // Intern CAN update any posts with status = 1 - $this->updatePermission(2, [ - 'status' => $currentStatus, - 'delete' => Acl::LEVEL_FULL - ]); - - $response = request_delete('items/'.$collection.'/2', ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - table_insert(static::$db, $collection, array_merge(['id' => 2], $data['data1'])); - - $response = request_delete('items/'.$collection.'/6', ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - table_insert(static::$db, $collection, array_merge(['id' => 6], $data['data5'])); - - $response = request_delete('items/'.$collection.'/10', ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - table_insert(static::$db, $collection, array_merge(['id' => 10], $data['data9'])); - - // ---------------------------------------------------------------------------- - // WITH STATUS: 2 - // ---------------------------------------------------------------------------- - // Intern CAN update their own posts with status = 0 - $currentStatus = $statuses[2]; - $this->updatePermission(3, [ - 'status' => $currentStatus, - 'delete' => Acl::LEVEL_MINE - ]); - - $response = request_delete('items/'.$collection.'/3', ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - table_insert(static::$db, $collection, array_merge(['id' => 3], $data['data2'])); - - $response = request_error_delete('items/'.$collection.'/7', ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionDeleteException::ERROR_CODE - ]); - - $response = request_error_delete('items/'.$collection.'/11', ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionDeleteException::ERROR_CODE - ]); - - // ---------------------------------------------------------------------------- - // Intern CAN update their own group posts with status = 0 - $this->updatePermission(3, [ - 'status' => $currentStatus, - 'delete' => Acl::LEVEL_ROLE - ]); - - $response = request_delete('items/'.$collection.'/3', ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - table_insert(static::$db, $collection, array_merge(['id' => 3], $data['data2'])); - - $response = request_error_delete('items/'.$collection.'/7', ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionDeleteException::ERROR_CODE - ]); - - $response = request_delete('items/'.$collection.'/11', ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - table_insert(static::$db, $collection, array_merge(['id' => 11], $data['data10'])); - - // ---------------------------------------------------------------------------- - // Intern CAN update any posts with status = 0 - $this->updatePermission(3, [ - 'status' => $currentStatus, - 'delete' => Acl::LEVEL_FULL - ]); - - $response = request_delete('items/'.$collection.'/3', ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - table_insert(static::$db, $collection, array_merge(['id' => 3], $data['data2'])); - - $response = request_delete('items/'.$collection.'/7', ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - table_insert(static::$db, $collection, array_merge(['id' => 7], $data['data6'])); - - $response = request_delete('items/'.$collection.'/11', ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - table_insert(static::$db, $collection, array_merge(['id' => 11], $data['data10'])); - } - - public function testFieldBlacklist() - { - $this->resetTestPosts(); - truncate_table(static::$db, 'directus_permissions'); - $this->addPermissionTo($this->internGroup, 'posts', [ - 'create' => Acl::LEVEL_MINE, - 'read' => Acl::LEVEL_MINE, - // 'write_field_blacklist' => 'author,status', - 'read_field_blacklist' => ['status', 'author'] - ]); - - $response = request_post('items/posts', ['title' => 'one'], ['query' => $this->internQueryParams]); - assert_response($this, $response); - assert_response_data_fields($this, $response, ['id', 'title']); - - $response = request_get('items/posts/2', array_merge( - $this->internQueryParams, - ['fields' => 'id,title,author'] - )); - - assert_response($this, $response); - assert_response_data_fields($this, $response, ['id', 'title']); - - $this->updatePermission(1, [ - 'read_field_blacklist' => ['author'] - ]); - - $response = request_get('items/posts/2', $this->internQueryParams); - assert_response($this, $response, [ - 'has_fields' => true, - 'fields' => ['id', 'title', 'status'] - ]); - - assert_response($this, $response); - assert_response_data_fields($this, $response, ['id', 'title', 'status']); - - $response = request_get('items/posts/2', array_merge( - $this->internQueryParams, - ['fields' => 'id,title,author,status'] - )); - assert_response($this, $response); - assert_response_data_fields($this, $response, ['id', 'title', 'status']); - } - - public function testStatusFieldBlacklist() - { - $this->resetTestPosts(); - truncate_table(static::$db, 'directus_permissions'); - - $this->addPermissionTo($this->internGroup, 'posts', [ - 'status' => 0, - 'read' => Acl::LEVEL_MINE, - 'write_field_blacklist' => ['author' , 'status'], - 'read_field_blacklist' => ['status', 'author'] - ]); - - $this->addPermissionTo($this->internGroup, 'posts', [ - 'status' => 1, - 'read' => Acl::LEVEL_MINE, - 'write_field_blacklist' => ['author', 'status'], - 'read_field_blacklist' => ['status', 'author'] - ]); - - $this->addPermissionTo($this->internGroup, 'posts', [ - 'status' => 2, - 'read' => Acl::LEVEL_MINE, - 'write_field_blacklist' => ['author', 'status'], - 'read_field_blacklist' => ['status'] - ]); - - $this->addPermissionTo($this->internGroup, 'posts', [ - 'status' => 3, - 'read' => Acl::LEVEL_MINE, - 'read_field_blacklist' => ['id', 'status', 'title', 'author'] - ]); - - // ---------------------------------------------------------------------------- - // STATUS: 0 - // ---------------------------------------------------------------------------- - // Read - // ---------------------------------------------------------------------------- - $response = request_error_get('items/posts/1', $this->internQueryParams); - assert_response_error($this, $response); - // assert_response_data_fields($this, $response, ['id', 'title']); - // ---------------------------------------------------------------------------- - // Write - // ---------------------------------------------------------------------------- - $data = ['status' => 0, 'title' => 'Post 1', 'author' => 1]; - $response = request_error_post('items/posts', $data, $this->internQueryParams); - assert_response_error($this, $response); - - $data = ['status' => 0, 'title' => 'Post 1']; - $response = request_error_post('items/posts', $data, $this->internQueryParams); - assert_response_error($this, $response); - - // ---------------------------------------------------------------------------- - // STATUS: 1 - // ---------------------------------------------------------------------------- - // Read - // ---------------------------------------------------------------------------- - $response = request_get('items/posts/2', $this->internQueryParams); - assert_response($this, $response); - assert_response_data_fields($this, $response, ['id', 'title']); - // ---------------------------------------------------------------------------- - // Write - // ---------------------------------------------------------------------------- - $data = ['status' => 1, 'title' => 'Post 1', 'author' => 1]; - $response = request_error_post('items/posts', $data, $this->internQueryParams); - assert_response_error($this, $response); - - $data = ['status' => 1, 'title' => 'Post 1']; - $response = request_error_post('items/posts', $data, $this->internQueryParams); - assert_response_error($this, $response); - - // ---------------------------------------------------------------------------- - // STATUS: 2 - // ---------------------------------------------------------------------------- - // Read - // ---------------------------------------------------------------------------- - $response = request_get('items/posts/3', $this->internQueryParams); - assert_response($this, $response); - assert_response_data_fields($this, $response, ['id', 'title', 'author']); - // ---------------------------------------------------------------------------- - // Write - // ---------------------------------------------------------------------------- - $data = ['status' => 2, 'title' => 'Post 1', 'author' => 1]; - $response = request_error_post('items/posts', $data, $this->internQueryParams); - assert_response_error($this, $response); - - $data = ['status' => 2, 'title' => 'Post 1']; - $response = request_error_post('items/posts', $data, $this->internQueryParams); - assert_response_error($this, $response); - - - // ---------------------------------------------------------------------------- - // STATUS: 3 - // ---------------------------------------------------------------------------- - // Read - // ---------------------------------------------------------------------------- - $response = request_error_get('items/posts/4', $this->internQueryParams); - assert_response_error($this, $response); - - // FETCH ALL - // Status 3 should be removed as the user cannot read any fields - $response = request_get('items/posts', array_merge(['status' => '*'], $this->internQueryParams)); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 2 - ]); - - $items = response_get_data($response); - $item0 = $items[0]; - assert_data_fields($this, $item0, ['id', 'title']); - - $item1 = $items[1]; - assert_data_fields($this, $item1, ['id', 'title', 'author']); - - $this->resetTestPosts(); - truncate_table(static::$db, 'directus_permissions'); - - $this->addPermissionTo($this->internGroup, 'posts', [ - 'status' => null, - 'read' => Acl::LEVEL_MINE, - 'write_field_blacklist' => ['author', 'status'], - 'read_field_blacklist' => ['status', 'author'] - ]); - - $data = ['status' => 2, 'title' => 'Post 1', 'author' => 1]; - $response = request_error_post('items/posts', $data, $this->internQueryParams); - assert_response_error($this, $response); - - $data = ['status' => 2, 'title' => 'Post 1']; - $response = request_error_post('items/posts', $data, $this->internQueryParams); - assert_response_error($this, $response); - - $data = ['title' => 'Post 1', 'author' => 1]; - $response = request_error_post('items/posts', $data, $this->internQueryParams); - assert_response_error($this, $response); - - // One item - $response = request_get('items/posts/2', $this->internQueryParams); - assert_response($this, $response); - assert_response_data_fields($this, $response, ['id', 'title']); - - // List of items - $response = request_get('items/posts', $this->internQueryParams); - assert_response($this, $response, [ - 'data' => 'array' - ]); - assert_response_data_fields($this, $response, ['id', 'title']); - } - - public function testPublicList() - { - $response = request_error_get('items/products'); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionReadException::ERROR_CODE - ]); - - $data = [ - 'role' => 2, - 'collection' => 'products', - 'read' => Acl::LEVEL_FULL, - ]; - - $response = request_post('permissions', $data, ['query' => $this->queryParams]); - assert_response($this, $response); - assert_response_data_contains($this, $response, array_merge(['id' => 2], $data)); - - $response = request_get('items/products'); - assert_response($this, $response, [ - 'public' => true, - 'data' => 'array' - ]); - } - - protected function addPermissionTo($group, $collection, array $data) - { - $data = array_merge($data, [ - 'role' => $group, - 'collection' => $collection - ]); - - $response = request_post('permissions', $data, ['query' => $this->queryParams]); - assert_response($this, $response); - assert_response_data_contains($this, $response, $data, false); - } - - protected function updatePermission($id, $data) - { - $response = request_patch('permissions/' . $id, $data, ['query' => $this->queryParams]); - assert_response($this, $response); - assert_response_data_contains($this, $response, $data, false); - } - - protected function tryStatusCreate($collection, $statusWithPermission, $statusWithoutPermission) - { - truncate_table(static::$db, 'directus_permissions'); - - // Intern CAN create draft but CANNOT READ any items - $this->addPermissionTo($this->internGroup, $collection, [ - 'status' => $statusWithPermission, - 'create' => Acl::LEVEL_MINE - ]); - - // Intern cannot create draft posts - $data = [ - 'title' => 'Post 1', - 'status' => $statusWithoutPermission - ]; - - $response = request_error_post('items/' . $collection, $data, ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionCreateException::ERROR_CODE - ]); - - // Intern can create posts with default status (because it is 2) - $data = [ - 'title' => 'Post 1' - ]; - - $response = request_post('items/' . $collection, $data, ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - - // Intern CAN create draft and CAN READ their own posts - $this->updatePermission(1, [ - 'create' => Acl::LEVEL_MINE, - 'read' => Acl::LEVEL_MINE - ]); - - $data = [ - 'title' => 'Post 1', - 'status' => $statusWithPermission - ]; - - $response = request_post('items/' . $collection, $data, ['query' => $this->internQueryParams]); - assert_response($this, $response); - assert_response_data_contains($this, $response, $data); - } - - protected function tryStatusRead($collection, $publishedStatus, $draftStatus, $noPermissionStatusOne, $noPermissionStatusTwo) - { - truncate_table(static::$db, 'directus_permissions'); - truncate_table(static::$db, $collection); - - // Intern CAN read draft and published (1) but CANNOT READ deleted (0) - $this->addPermissionTo($this->internGroup, $collection, [ - 'status' => $publishedStatus, - 'read' => Acl::LEVEL_MINE - ]); - - $this->addPermissionTo($this->internGroup, $collection, [ - 'status' => $draftStatus, - 'read' => Acl::LEVEL_MINE - ]); - - $data0 = ['title' => 'Deleted Post', 'status' => $noPermissionStatusOne, 'author' => 2]; - table_insert(static::$db, $collection, $data0); - - $data1 = ['title' => 'Published Post', 'status' => $publishedStatus, 'author' => 2]; - table_insert(static::$db, $collection, $data1); - - $data2 = ['title' => 'Draft Post', 'status' => $draftStatus, 'author' => 2]; - table_insert(static::$db, $collection, $data2); - - $data3 = ['title' => 'Under Review Post', 'status' => $noPermissionStatusTwo, 'author' => 2]; - table_insert(static::$db, $collection, $data3); - - $response = request_error_get('items/'.$collection.'/1', $this->internQueryParams); - assert_response_error($this, $response, [ - 'status' => 404, - 'code' => ItemNotFoundException::ERROR_CODE - ]); - - $response = request_get('items/'.$collection.'/2', $this->internQueryParams); - assert_response($this, $response); - assert_response_data_contains($this, $response, $data1); - - $response = request_get('items/'.$collection.'/3', $this->internQueryParams); - assert_response($this, $response); - assert_response_data_contains($this, $response, $data2); - - $response = request_error_get('items/'.$collection.'/4', $this->internQueryParams); - assert_response_error($this, $response, [ - 'status' => 404, - 'code' => ItemNotFoundException::ERROR_CODE - ]); - - $response = request_get('items/' . $collection, $this->internQueryParams); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 1 - ]); - - $response = request_get('items/' . $collection, $this->queryParams); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 1 - ]); - - $statuses = implode(',', [ - $noPermissionStatusOne, - $publishedStatus, - $draftStatus - ]); - $response = request_get('items/' . $collection, array_merge($this->internQueryParams, ['status' => $statuses])); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 2 - ]); - - $response = request_get('items/' . $collection, array_merge($this->queryParams, ['status' => $statuses])); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 3 - ]); - } - - protected function tryStatusUpdate($collection) - { - truncate_table(static::$db, 'directus_permissions'); - truncate_table(static::$db, $collection); - - $this->resetTestItems($collection); - - // ---------------------------------------------------------------------------- - // Intern CANNOT update posts - $data = [ - 'title' => 'Post title changed' - ]; - - $response = request_error_patch('items/'.$collection.'/1', $data, ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionUpdateException::ERROR_CODE - ]); - - $response = request_error_patch('items/'.$collection.'/5', $data, ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionUpdateException::ERROR_CODE - ]); - - $response = request_error_patch('items/'.$collection.'/9', $data, ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionUpdateException::ERROR_CODE - ]); - - // ---------------------------------------------------------------------------- - // Intern CAN update their own posts BUT CANNOT read any posts - $this->addPermissionTo($this->internGroup, $collection, [ - 'status' => null, - 'update' => Acl::LEVEL_MINE - ]); - - $response = request_patch('items/'.$collection.'/1', $data, ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - - $response = request_error_patch('items/'.$collection.'/5', $data, ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionUpdateException::ERROR_CODE - ]); - - $response = request_error_patch('items/'.$collection.'/9', $data, ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionUpdateException::ERROR_CODE - ]); - - // ---------------------------------------------------------------------------- - // Intern CAN update their own group posts BUT CANNOT read any posts - $this->updatePermission(1, [ - 'update' => Acl::LEVEL_ROLE - ]); - - $response = request_patch('items/'.$collection.'/1', $data, ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - - $response = request_error_patch('items/'.$collection.'/5', $data, ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionUpdateException::ERROR_CODE - ]); - - $response = request_patch('items/'.$collection.'/9', $data, ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - - // ---------------------------------------------------------------------------- - // Intern CAN update any posts BUT CANNOT read any posts - $this->updatePermission(1, [ - 'update' => Acl::LEVEL_FULL - ]); - - $response = request_patch('items/'.$collection.'/1', $data, ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - - $response = request_patch('items/'.$collection.'/5', $data, ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - - $response = request_patch('items/'.$collection.'/9', $data, ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - - // ---------------------------------------------------------------------------- - // UPDATE + READ PERMISSION - // ---------------------------------------------------------------------------- - - // ---------------------------------------------------------------------------- - // Intern CAN update any posts BUT CAN only read their own posts - $this->updatePermission(1, [ - 'update' => Acl::LEVEL_FULL, - 'read' => Acl::LEVEL_MINE - ]); - - $response = request_patch('items/'.$collection.'/1', $data, ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - - $response = request_patch('items/'.$collection.'/5', $data, ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - - $response = request_patch('items/'.$collection.'/9', $data, ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - - // ---------------------------------------------------------------------------- - // Intern CAN update any posts BUT CAN only read their own group posts - $this->updatePermission(1, [ - 'update' => Acl::LEVEL_FULL, - 'read' => Acl::LEVEL_ROLE - ]); - - $response = request_patch('items/'.$collection.'/1', $data, ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - - $response = request_patch('items/'.$collection.'/5', $data, ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - - $response = request_patch('items/'.$collection.'/9', $data, ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - - // ---------------------------------------------------------------------------- - // Intern CAN update any posts AND CAN read any posts - $this->updatePermission(1, [ - 'update' => Acl::LEVEL_FULL, - 'read' => Acl::LEVEL_FULL - ]); - - $response = request_patch('items/'.$collection.'/1', $data, ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - - $response = request_patch('items/'.$collection.'/5', $data, ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - - $response = request_patch('items/'.$collection.'/9', $data, ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - - // ---------------------------------------------------------------------------- - // PERMISSION BY STATUS - // ---------------------------------------------------------------------------- - truncate_table(static::$db, 'directus_permissions'); - - $statuses = $this->getStatuses($collection); - // ---------------------------------------------------------------------------- - // Intern CANNOT update posts with any status - foreach ($statuses as $status) { - $this->addPermissionTo($this->internGroup, $collection, [ - 'status' => $status, - 'update' => Acl::LEVEL_NONE - ]); - } - - $data = [ - 'title' => 'Post title changed' - ]; - - $response = request_error_patch('items/'.$collection.'/1', $data, ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionUpdateException::ERROR_CODE - ]); - - $response = request_error_patch('items/'.$collection.'/2', $data, ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionUpdateException::ERROR_CODE - ]); - - $response = request_error_patch('items/'.$collection.'/3', $data, ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionUpdateException::ERROR_CODE - ]); - - $response = request_error_patch('items/'.$collection.'/4', $data, ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionUpdateException::ERROR_CODE - ]); - - $response = request_error_patch('items/'.$collection.'/5', $data, ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionUpdateException::ERROR_CODE - ]); - - $response = request_error_patch('items/'.$collection.'/6', $data, ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionUpdateException::ERROR_CODE - ]); - - $response = request_error_patch('items/'.$collection.'/7', $data, ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionUpdateException::ERROR_CODE - ]); - - $response = request_error_patch('items/'.$collection.'/8', $data, ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionUpdateException::ERROR_CODE - ]); - - // ---------------------------------------------------------------------------- - // WITH STATUS: 0 - // ---------------------------------------------------------------------------- - // Intern CAN update their own posts with status = 0 - $currentStatus = $statuses[0]; - $this->updatePermission(1, [ - 'status' => $currentStatus, - 'update' => Acl::LEVEL_MINE - ]); - - $data = [ - 'title' => 'Post title changed' - ]; - - $response = request_patch('items/'.$collection.'/1', $data, ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - - $response = request_error_patch('items/'.$collection.'/2', $data, ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionUpdateException::ERROR_CODE - ]); - - $response = request_error_patch('items/'.$collection.'/5', $data, ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionUpdateException::ERROR_CODE - ]); - - $response = request_error_patch('items/'.$collection.'/9', $data, ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionUpdateException::ERROR_CODE - ]); - - // ---------------------------------------------------------------------------- - // Intern CAN update their own group posts with status = 0 - $this->updatePermission(1, [ - 'status' => $currentStatus, - 'update' => Acl::LEVEL_ROLE - ]); - - $data = [ - 'title' => 'Post title changed' - ]; - - $response = request_patch('items/'.$collection.'/1', $data, ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - - $response = request_error_patch('items/'.$collection.'/5', $data, ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionUpdateException::ERROR_CODE - ]); - - $response = request_patch('items/'.$collection.'/9', $data, ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - - // ---------------------------------------------------------------------------- - // Intern CAN update any posts with status = 0 - $this->updatePermission(1, [ - 'status' => $currentStatus, - 'update' => Acl::LEVEL_FULL - ]); - - $data = [ - 'title' => 'Post title changed' - ]; - - $response = request_patch('items/'.$collection.'/1', $data, ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - - $response = request_error_patch('items/'.$collection.'/2', $data, ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionUpdateException::ERROR_CODE - ]); - - $response = request_patch('items/'.$collection.'/5', $data, ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - - $response = request_patch('items/'.$collection.'/9', $data, ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - - // ---------------------------------------------------------------------------- - // WITH STATUS: 1 - // ---------------------------------------------------------------------------- - // Intern CAN update their own posts with status = 1 - $currentStatus = $statuses[1]; - $this->updatePermission(2, [ - 'status' => $currentStatus, - 'update' => Acl::LEVEL_MINE - ]); - - $data = [ - 'title' => 'Post title changed' - ]; - - $response = request_patch('items/'.$collection.'/2', $data, ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - - $response = request_error_patch('items/'.$collection.'/3', $data, ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionUpdateException::ERROR_CODE - ]); - - $response = request_error_patch('items/'.$collection.'/6', $data, ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionUpdateException::ERROR_CODE - ]); - - $response = request_error_patch('items/'.$collection.'/10', $data, ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionUpdateException::ERROR_CODE - ]); - - // ---------------------------------------------------------------------------- - // Intern CAN update their own group posts with status = 1 - $this->updatePermission(2, [ - 'status' => $currentStatus, - 'update' => Acl::LEVEL_ROLE - ]); - - $data = [ - 'title' => 'Post title changed' - ]; - - $response = request_patch('items/'.$collection.'/2', $data, ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - - $response = request_error_patch('items/'.$collection.'/6', $data, ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionUpdateException::ERROR_CODE - ]); - - $response = request_patch('items/'.$collection.'/10', $data, ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - - // ---------------------------------------------------------------------------- - // Intern CAN update any posts with status = 1 - $this->updatePermission(2, [ - 'status' => $currentStatus, - 'update' => Acl::LEVEL_FULL - ]); - - $data = [ - 'title' => 'Post title changed' - ]; - - $response = request_patch('items/'.$collection.'/2', $data, ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - - $response = request_patch('items/'.$collection.'/6', $data, ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - - $response = request_patch('items/'.$collection.'/10', $data, ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - - // ---------------------------------------------------------------------------- - // WITH STATUS: 2 - // ---------------------------------------------------------------------------- - // Intern CAN update their own posts with status = 2 - $currentStatus = $statuses[2]; - $this->updatePermission(3, [ - 'status' => $currentStatus, - 'update' => Acl::LEVEL_MINE - ]); - - $data = [ - 'title' => 'Post title changed' - ]; - - $response = request_patch('items/'.$collection.'/3', $data, ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - - $response = request_error_patch('items/'.$collection.'/7', $data, ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionUpdateException::ERROR_CODE - ]); - - $response = request_error_patch('items/'.$collection.'/11', $data, ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionUpdateException::ERROR_CODE - ]); - - // ---------------------------------------------------------------------------- - // Intern CAN update their own group posts with status = 2 - $this->updatePermission(3, [ - 'status' => $currentStatus, - 'update' => Acl::LEVEL_ROLE - ]); - - $data = [ - 'title' => 'Post title changed' - ]; - - $response = request_patch('items/'.$collection.'/3', $data, ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - - $response = request_error_patch('items/posts/7', $data, ['query' => $this->internQueryParams]); - assert_response_error($this, $response, [ - 'status' => 403, - 'code' => ForbiddenCollectionUpdateException::ERROR_CODE - ]); - - $response = request_patch('items/'.$collection.'/11', $data, ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - - // ---------------------------------------------------------------------------- - // Intern CAN update any posts with status = 2 - $this->updatePermission(3, [ - 'status' => $currentStatus, - 'update' => Acl::LEVEL_FULL - ]); - - $data = [ - 'title' => 'Post title changed' - ]; - - $response = request_patch('items/'.$collection.'/3', $data, ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - - $response = request_patch('items/'.$collection.'/7', $data, ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - - $response = request_patch('items/'.$collection.'/11', $data, ['query' => $this->internQueryParams]); - assert_response_empty($this, $response); - } - - protected static function createTestTable() - { - $statusOptions = [ - 'status_mapping' => [ - 2 => ['name' => 'Draft', 'published' => false], - 1 => ['name' => 'Published'] - ] - ]; - $data = [ - 'collection' => 'posts', - 'fields' => [ - ['field' => 'id', 'interface' => 'primary_key', 'type' => 'integer', 'datatype' => 'integer', 'primary_key' => true, 'auto_increment' => true, 'length' => 10], - ['field' => 'status', 'interface' => 'status', 'type' => 'status', 'datatype' => 'integer', 'length' => 10, 'default_value' => 2, 'options' => $statusOptions], - ['field' => 'title', 'interface' => 'text_input', 'type' => 'string', 'datatype' => 'varchar', 'length' => 100], - ['field' => 'author', 'type' => 'user_created', 'interface' => 'user_created', 'datatype' => 'integer', 'length' => 10], - ] - ]; - - $response = request_post('collections', $data, ['query' => ['access_token' => 'token']]); - - $statusOptions = [ - 'status_mapping' => [ - 'draft' => ['name' => 'Draft', 'published' => false], - 'published' => ['name' => 'Published'] - ] - ]; - $data = [ - 'collection' => 'articles', - 'fields' => [ - ['field' => 'id', 'interface' => 'primary_key', 'type' => 'integer', 'datatype' => 'integer', 'primary_key' => true, 'auto_increment' => true, 'length' => 10], - ['field' => 'status', 'interface' => 'status', 'type' => 'status', 'datatype' => 'varchar', 'length' => 16, 'default_value' => 'draft', 'options' => $statusOptions], - ['field' => 'title', 'interface' => 'text_input', 'type' => 'string', 'datatype' => 'varchar', 'length' => 100], - ['field' => 'author', 'type' => 'user_created', 'interface' => 'user_created', 'datatype' => 'integer', 'length' => 10], - ] - ]; - - $response = request_post('collections', $data, ['query' => ['access_token' => 'token']]); - } - - protected static function dropTestTable() - { - $response = request_error_delete('collections/posts', ['query' => ['access_token' => 'token']]); - $response = request_error_delete('collections/articles', ['query' => ['access_token' => 'token']]); - } - - protected function getStatuses($collection) - { - switch ($collection) { - case 'articles': - $statuses = ['deleted', 'published', 'draft', 'under_review']; - break; - default: - $statuses = [0, 1, 2, 3]; - } - - return $statuses; - } - - protected function getPostsData() - { - return $this->getItemsData($this->getStatuses('posts')); - } - - protected function getArticlesData() - { - return $this->getItemsData($this->getStatuses('articles')); - } - - protected function getItemsData(array $statuses) - { - $statusOne = array_shift($statuses); - $statusTwo = array_shift($statuses); - $statusThree = array_shift($statuses); - $statusFour = array_shift($statuses); - // ---------------------------------------------------------------------------- - // Intern user - // ---------------------------------------------------------------------------- - $data0 = ['title' => 'Deleted Post', 'status' => $statusOne, 'author' => 2]; - $data1 = ['title' => 'Published Post', 'status' => $statusTwo, 'author' => 2]; - $data2 = ['title' => 'Draft Post', 'status' => $statusThree, 'author' => 2]; - $data3 = ['title' => 'Under Review Post', 'status' => $statusFour, 'author' => 2]; - - // ---------------------------------------------------------------------------- - // Admin group - // ---------------------------------------------------------------------------- - $data4 = ['title' => 'Deleted Post', 'status' => $statusOne, 'author' => 1]; - $data5 = ['title' => 'Published Post', 'status' => $statusTwo, 'author' => 1]; - $data6 = ['title' => 'Draft Post', 'status' => $statusThree, 'author' => 1]; - $data7 = ['title' => 'Under Review Post', 'status' => $statusFour, 'author' => 1]; - - // ---------------------------------------------------------------------------- - // Group user - // ---------------------------------------------------------------------------- - $data8 = ['title' => 'Deleted Post', 'status' => $statusOne, 'author' => 3]; - $data9 = ['title' => 'Published Post', 'status' => $statusTwo, 'author' => 3]; - $data10 = ['title' => 'Draft Post', 'status' => $statusThree, 'author' => 3]; - $data11 = ['title' => 'Under Review Post', 'status' => $statusFour, 'author' => 3]; - - $variables = []; - for ($i = 0; $i <= 11; $i++) { - $variables[] = 'data' . $i; - } - - return compact( - $variables - ); - } - - protected function resetTestPosts() - { - $this->resetTestItems('posts'); - } - - protected function resetTestArticles() - { - $this->resetTestItems('articles'); - } - - protected function resetTestItems($collection) - { - truncate_table(static::$db, $collection); - - if ($collection == 'articles' ) { - $data = $this->getArticlesData(); - } else { - $data = $this->getPostsData(); - } - extract($data); - - // ---------------------------------------------------------------------------- - // Intern user - // ---------------------------------------------------------------------------- - // $data0 = ['title' => 'Deleted Post', 'status' => 0, 'author' => 2]; - table_insert(static::$db, $collection, $data0); - - // $data1 = ['title' => 'Published Post', 'status' => 1, 'author' => 2]; - table_insert(static::$db, $collection, $data1); - - // $data2 = ['title' => 'Draft Post', 'status' => 2, 'author' => 2]; - table_insert(static::$db, $collection, $data2); - - // $data3 = ['title' => 'Under Review Post', 'status' => 3, 'author' => 2]; - table_insert(static::$db, $collection, $data3); - - // ---------------------------------------------------------------------------- - // Admin group - // ---------------------------------------------------------------------------- - // $data4 = ['title' => 'Deleted Post', 'status' => 0, 'author' => 1]; - table_insert(static::$db, $collection, $data4); - - // $data5 = ['title' => 'Published Post', 'status' => 1, 'author' => 1]; - table_insert(static::$db, $collection, $data5); - - // $data6 = ['title' => 'Draft Post', 'status' => 2, 'author' => 1]; - table_insert(static::$db, $collection, $data6); - - // $data7 = ['title' => 'Under Review Post', 'status' => 3, 'author' => 1]; - table_insert(static::$db, $collection, $data7); - - // ---------------------------------------------------------------------------- - // Group user - // ---------------------------------------------------------------------------- - // $data8 = ['title' => 'Deleted Post', 'status' => 0, 'author' => 3]; - table_insert(static::$db, $collection, $data8); - - // $data9 = ['title' => 'Published Post', 'status' => 1, 'author' => 3]; - table_insert(static::$db, $collection, $data9); - - // $data10 = ['title' => 'Draft Post', 'status' => 2, 'author' => 3]; - table_insert(static::$db, $collection, $data10); - - // $data11 = ['title' => 'Under Review Post', 'status' => 3, 'author' => 3]; - table_insert(static::$db, $collection, $data11); - } -} diff --git a/tests/io/RevisionsTest.php b/tests/io/RevisionsTest.php deleted file mode 100644 index ac30fa57e1..0000000000 --- a/tests/io/RevisionsTest.php +++ /dev/null @@ -1,144 +0,0 @@ -assertSame(1, 1); - } - - public function testTwo() - { - $this->assertSame(1, 1); - } - - public function testNewItem() - { - $this->assertSame(0, table_count(static::$db, 'directus_revisions')); - - $response = request_post('items/test', ['name' => 'test 1'], ['query' => ['access_token' => 'token']]); - assert_response($this, $response); - $this->assertSame(1, table_count(static::$db, 'directus_revisions')); - - request_post('items/test', ['name' => 'test 2'], ['query' => ['access_token' => 'token']]); - assert_response($this, $response); - $this->assertSame(2, table_count(static::$db, 'directus_revisions')); - - request_post('items/test', ['name' => 'test 3'], ['query' => ['access_token' => 'token']]); - assert_response($this, $response); - $this->assertSame(3, table_count(static::$db, 'directus_revisions')); - } - - public function testUpdateItem() - { - $count = table_count(static::$db, 'directus_revisions'); - - $response = request_patch('items/test/1', ['name' => 'test one'], ['query' => ['access_token' => 'token']]); - assert_response($this, $response); - $this->assertSame($count+1, table_count(static::$db, 'directus_revisions')); - } - - public function testDeleteItem() - { - // Delete does not create revision - $count = table_count(static::$db, 'directus_revisions'); - - $response = request_delete('items/test/2', ['query' => ['access_token' => 'token']]); - assert_response_empty($this, $response); - $this->assertSame($count, table_count(static::$db, 'directus_revisions')); - } - - public function testItemRevisionsCount() - { - $response = request_get('items/test/1/revisions', ['access_token' => 'token']); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 2 - ]); - } - - public function testItemRevisionsOffset() - { - $response = request_get('items/test/1/revisions/0', ['access_token' => 'token']); - assert_response($this, $response, [ - 'data' => 'object' - ]); - - $data = response_get_data($response); - $this->assertInternalType('object', $data->delta); - $this->assertSame('test 1', $data->delta->name); - - // second revision - $response = request_get('items/test/1/revisions/1', ['access_token' => 'token']); - assert_response($this, $response, [ - 'data' => 'object' - ]); - - $data = response_get_data($response); - $this->assertInternalType('object', $data->delta); - $this->assertSame('test one', $data->delta->name); - } - - public function testItemRevisionRevert() - { - $response = request_get('items/test/1/revisions/0', ['access_token' => 'token']); - assert_response($this, $response, [ - 'data' => 'object' - ]); - - $originalData = response_get_data($response); - $this->assertInternalType('object', $originalData->delta); - - $response = request_patch('items/test/1/revert/1', [], ['query' => ['access_token' => 'token']]); - assert_response($this, $response); - - $currentData = response_get_data($response); - $this->assertSame($originalData->delta->name, $currentData->name); - } - - protected static function truncateTable() - { - truncate_table(static::$db, 'directus_activity'); - truncate_table(static::$db, 'directus_revisions'); - } - - protected static function createSampleTables() - { - if (!static::$db) { - return; - } - - create_table(static::$db, 'test'); - table_insert(static::$db, 'directus_collections', [ - 'collection' => 'test' - ]); - } - - protected static function dropSampleTables() - { - drop_table(static::$db, 'test'); - } -} diff --git a/tests/io/RolesTest.php b/tests/io/RolesTest.php deleted file mode 100644 index f9c5782b9e..0000000000 --- a/tests/io/RolesTest.php +++ /dev/null @@ -1,84 +0,0 @@ - 'token' - ]; - - public static function resetDatabase() - { - reset_table_id(create_db_connection(), 'directus_roles', 4); - } - - public static function setUpBeforeClass() - { - static::resetDatabase(); - } - - public static function tearDownAfterClass() - { - static::resetDatabase(); - } - - public function testCreate() - { - $data = [ - 'name' => 'Manager' - ]; - - $response = request_post('roles', $data, ['query' => $this->queryParams]); - assert_response($this, $response); - assert_response_data_contains($this, $response, $data); - } - - public function testUpdate() - { - $data = [ - 'name' => 'Manager Team', - 'description' => 'All Manager users' - ]; - - $response = request_patch('roles/4', $data, ['query' => $this->queryParams]); - assert_response($this, $response); - assert_response_data_contains($this, $response, array_merge(['id' => 4], $data)); - } - - public function testGetOne() - { - $data = [ - 'id' => 4, - 'name' => 'Manager Team', - 'description' => 'All Manager users' - ]; - - $response = request_get('roles/4', $this->queryParams); - assert_response($this, $response); - assert_response_data_contains($this, $response, $data); - } - - public function testList() - { - $response = request_get('roles', $this->queryParams); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 4 - ]); - } - - public function testDelete() - { - $response = request_delete('roles/4', ['query' => $this->queryParams]); - assert_response_empty($this, $response); - - $response = request_error_get('roles/4', $this->queryParams); - assert_response_error($this, $response, [ - 'code' => ItemNotFoundException::ERROR_CODE, - 'status' => 404 - ]); - } -} diff --git a/tests/io/SettingsTest.php b/tests/io/SettingsTest.php deleted file mode 100644 index 24a93fba29..0000000000 --- a/tests/io/SettingsTest.php +++ /dev/null @@ -1,93 +0,0 @@ - 'token']; - $path = 'settings'; - - $data = [ - 'scope' => 'global', - 'key' => 'map_source', - 'value' => 'google' - ]; - - $response = request_post($path, $data, ['query' => $queryParams]); - assert_response($this, $response); - assert_response_data_contains($this, $response, $data); - } - - public function testUpdate() - { - $queryParams = ['access_token' => 'token']; - $path = 'settings/1'; - - $data = [ - 'value' => 'new-value' - ]; - - $response = request_patch($path, $data, ['query' => $queryParams]); - assert_response($this, $response); - assert_response_data_contains($this, $response, $data); - } - - public function testList() - { - $queryParams = ['access_token' => 'token']; - $path = 'settings'; - - $response = request_get($path, $queryParams); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 1 - ]); - } - - public function testGetOne() - { - $queryParams = ['access_token' => 'token']; - $path = 'settings/1'; - - $response = request_get($path, $queryParams); - assert_response($this, $response, [ - 'has_fields' => true, - 'fields' => ['scope', 'key', 'value'] - ]); - } - - public function testDelete() - { - $queryParams = ['access_token' => 'token']; - $path = 'settings/1'; - - $response = request_delete($path, ['query' => $queryParams]); - assert_response_empty($this, $response); - - $response = request_error_get($path, $queryParams); - assert_response_error($this, $response, [ - 'code' => ItemNotFoundException::ERROR_CODE, - 'status' => 404 - ]); - } - - public function testFields() - { - $queryParams = ['access_token' => 'token']; - $path = 'settings/fields'; - - $response = request_get($path, $queryParams); - assert_response($this, $response, [ - 'data' => 'array' - ]); - } -} diff --git a/tests/io/UsersTest.php b/tests/io/UsersTest.php deleted file mode 100644 index e12231f60b..0000000000 --- a/tests/io/UsersTest.php +++ /dev/null @@ -1,171 +0,0 @@ - 'token']; - $path = 'users'; - - $email = 'john@getdirectus.com'; - $password = 'password'; - $data = [ - 'first_name' => 'John', - 'last_name' => 'Doe', - 'status' => DirectusUsersTableGateway::STATUS_DRAFT, - 'email' => $email, - 'password' => $password - ]; - - $response = request_post($path, $data, ['query' => $queryParams]); - assert_response($this, $response); - assert_response_data_contains($this, $response, [ - 'email' => $email - ]); - $data = response_get_data($response); - $this->assertSame($email, $data->email); - } - - public function testUpdate() - { - $queryParams = ['access_token' => 'token']; - - $response = request_get('users/4', $queryParams); - $currentData = response_get_data($response); - - $email = 'john2@getdirectus.com'; - $password = 'new-password'; - $data = [ - 'email' => $email, - 'password' => $password - ]; - - $path = 'users/4'; - $response = request_patch($path, $data, ['query' => $queryParams]); - assert_response($this, $response); - assert_response_data_contains($this, $response, [ - 'id' => 4, - 'email' => $email - ]); - - $data = response_get_data($response); - - $this->assertSame($email, $data->email); - } - - public function testList() - { - $queryParams = ['access_token' => 'token']; - - // Fetch only "published" items, which are all users with "active" status - $response = request_get('users', $queryParams); - assert_response($this, $response, [ - 'data' => 'array', - 'count' => 3 - ]); - } - - public function testGetOne() - { - $queryParams = ['access_token' => 'token']; - - $response = request_get('users/4', $queryParams); - assert_response($this, $response); - - assert_response_data_contains($this, $response, [ - 'id' => 4, - 'email' => 'john2@getdirectus.com' - ]); - - $response = request_error_get('users/5', $queryParams); - assert_response_error($this, $response, [ - 'code' => ItemNotFoundException::ERROR_CODE, - 'status' => 404 - ]); - } - - public function testInvitation() - { - // TODO: Make the mailing works again - // This fails due to the use of Bootstrap - // $queryParams = ['access_token' => 'token']; - // - // $assertInvitationResponse = function (ResponseInterface $response) { - // $items = response_get_data($response); - // foreach ($items as $item) { - // $this->assertNotEmpty($item->invite_token); - // $this->assertNotEmpty($item->invite_date); - // $this->assertNotEmpty($item->invite_sender); - // $this->assertNotEmpty($item->invite_accepted); - // $this->assertSame(0, $item->invite_accepted); - // $this->assertSame(2, $item->status); - // } - // }; - // - // $data = ['email' => 'intern@getdirectus.com']; - // $response = request_post('users/invite', $data, ['query' => $queryParams]); - // assert_response($this, $response, [ - // 'data' => 'array', - // 'count' => 1 - // ]); - // - // $assertInvitationResponse($response); - // - // $data = ['email' => 'intern1@getdirectus.com, intern2@getdirectus.com']; - // $response = request_post('users/invite', $data, ['query' => $queryParams]); - // assert_response($this, $response, [ - // 'data' => 'array', - // 'count' => 2 - // ]); - // - // $assertInvitationResponse($response); - } - - public function testDelete() - { - $queryParams = ['access_token' => 'token']; - - $response = request_delete('users/4', ['query' => $queryParams]); - assert_response_empty($this, $response); - - $response = request_error_get('users/4', $queryParams); - assert_response_error($this, $response, [ - 'code' => ItemNotFoundException::ERROR_CODE, - 'status' => 404 - ]); - } - - public function testMe() - { - $queryParams = ['access_token' => 'token']; - - $response = request_get('users/me', $queryParams); - assert_response($this, $response); - assert_response_data_contains($this, $response, [ - 'email' => 'admin@getdirectus.com' - ]); - } -} diff --git a/tests/io/UtilsTest.php b/tests/io/UtilsTest.php deleted file mode 100644 index c8bb94057f..0000000000 --- a/tests/io/UtilsTest.php +++ /dev/null @@ -1,174 +0,0 @@ -tryHashWith($string); - - foreach ($this->availableHashers as $hasher) { - $this->tryHashWith($string, $hasher); - } - - $data = [ - 'string' => $string - ]; - - $path = 'utils/hash'; - $data['hasher'] = 'none'; - $response = request_error_post($path, $data, ['query' => [ - 'access_token' => 'token' - ]]); - - assert_response_error($this, $response, [ - 'code' => HasherNotFoundException::ERROR_CODE, - 'status' => 422 - ]); - - // Empty string passed - $response = request_error_post($path, ['string' => ''], ['query' => [ - 'access_token' => 'token' - ]]); - - assert_response_error($this, $response, [ - 'code' => InvalidRequestException::ERROR_CODE, - 'status' => 422 - ]); - - // Not string passed - $response = request_error_post($path, [], ['query' => [ - 'access_token' => 'token' - ]]); - - assert_response_error($this, $response, [ - 'code' => InvalidRequestException::ERROR_CODE, - 'status' => 422 - ]); - } - - public function testHashMatch() - { - $string = 'secret'; - - $this->tryHashMatchWith($string); - - foreach ($this->availableHashers as $hasher) { - $this->tryHashMatchWith($string, $hasher); - } - - $data = [ - 'string' => $string - ]; - - $path = 'utils/hash/match'; - $data['hasher'] = 'none'; - $data['hash'] = 'invalid-hash'; - $response = request_error_post($path, $data, ['query' => [ - 'access_token' => 'token' - ]]); - - assert_response_error($this, $response, [ - 'code' => HasherNotFoundException::ERROR_CODE, - 'status' => 422 - ]); - - // Empty string passed - $response = request_error_post($path, ['string' => ''], ['query' => [ - 'access_token' => 'token' - ]]); - - assert_response_error($this, $response, [ - 'code' => InvalidRequestException::ERROR_CODE, - 'status' => 422 - ]); - - // Not string passed - $response = request_error_post($path, [], ['query' => [ - 'access_token' => 'token' - ]]); - - assert_response_error($this, $response, [ - 'code' => InvalidRequestException::ERROR_CODE, - 'status' => 422 - ]); - } - - public function testRandomString() - { - $path = 'utils/random/string'; - $queryParams = ['access_token' => 'token']; - - // default length - $data = []; - $response = request_post($path, $data, ['query' => $queryParams]); - assert_response($this, $response); - $result = response_to_object($response); - $data = $result->data; - $this->assertTrue(strlen($data->random) === 32); - - // specifying the length - $data = ['length' => 16]; - $response = request_post($path, $data, ['query' => $queryParams]); - assert_response($this, $response); - $result = response_to_object($response); - $data = $result->data; - $this->assertTrue(strlen($data->random) === 16); - - // Length not numeric passed - $response = request_error_post($path, ['length' => 'a'], ['query' => $queryParams]); - assert_response_error($this, $response, [ - 'code' => InvalidRequestException::ERROR_CODE, - 'status' => 422 - ]); - } - - protected function tryHashWith($string, $hasher = null) - { - $path = 'utils/hash'; - $queryParams = ['access_token' => 'token']; - $data = ['string' => $string, 'hasher' => $hasher]; - - $response = request_post($path, $data, ['query' => $queryParams]); - assert_response($this, $response); - - $result = response_to_object($response); - - $data = $result->data; - $this->assertInternalType('string', $data->hash); - - return $data->hash; - } - - protected function tryHashMatchWith($string, $hasher = null) - { - $hash = $this->tryHashWith($string, $hasher); - - $path = 'utils/hash/match'; - $queryParams = ['access_token' => 'token']; - - $data = ['string' => $string, 'hasher' => $hasher, 'hash' => $hash]; - $response = request_post($path, $data, ['query' => $queryParams]); - assert_response($this, $response); - - $result = response_to_object($response); - $this->assertTrue($result->data->valid); - } -} diff --git a/tests/utils/assert.php b/tests/utils/assert.php deleted file mode 100644 index 292f8ebbf9..0000000000 --- a/tests/utils/assert.php +++ /dev/null @@ -1,208 +0,0 @@ -assertObjectHasAttribute('data', $result); - $testCase->assertObjectNotHasAttribute('error', $result); - - $dataType = \Directus\Util\ArrayUtils::get($options, 'data') === 'array' ? 'array' : 'object'; - $testCase->assertInternalType($dataType, $result->data); - - if (\Directus\Util\ArrayUtils::get($options, 'public', false)) { - $testCase->assertObjectHasAttribute('public', $result); - } else { - $testCase->assertObjectNotHasAttribute('public', $result); - } - - if (isset($options['count'])) { - $testCase->assertCount($options['count'], $result->data); - } - - if (isset($options['empty']) && $options['empty'] == true) { - $testCase->assertEmpty($result->data); - } - - // ============================================================================= - // Assert HTTP STATUS CODE - // ============================================================================= - $statusCode = isset($options['status']) ? $options['status'] : 200; - $testCase->assertSame($statusCode, $response->getStatusCode()); - - if (isset($options['fields'])) { - $hasFields = isset($options['has_fields']) ? (bool)$options['has_fields'] : false; - $data = (array)$result->data; - $fields = $options['fields']; - - if ($dataType === 'object') { - $data = [$data]; - } - - if ($hasFields === true) { - foreach ($fields as $field) { - foreach ($data as $item) { - $testCase->assertTrue(in_array($field, array_keys($item))); - } - } - } else { - foreach ($data as $item) { - foreach ($item as $key => $value) { - $testCase->assertTrue(in_array($key, $fields)); - } - } - } - } -} - -/** - * Tests whether the response content match a given content - * - * @param PHPUnit_Framework_TestCase $testCase - * @param ResponseInterface $response - * @param string $content - * @param array $options - */ -function assert_response_contents(TestCase $testCase, ResponseInterface $response, $content, array $options = []) -{ - $bodyContent = response_get_body_contents($response); - $testCase->assertSame($content, $bodyContent); - - if (isset($options['status'])) { - $testCase->assertSame($options['status'], $response->getStatusCode()); - } -} - -/** - * @param TestCase $testCase - * @param ResponseInterface $response - */ -function assert_response_empty(TestCase $testCase, ResponseInterface $response) -{ - $result = response_to_object($response); - - $testCase->assertEmpty((array)$result); -} - -/** - * @param TestCase $testCase - * @param ResponseInterface $response - * @param array $options - */ -function assert_response_meta(TestCase $testCase, ResponseInterface $response, array $options = []) -{ - $result = response_to_object($response); - $testCase->assertObjectHasAttribute('meta', $result); - $testCase->assertObjectNotHasAttribute('error', $result); - $meta = $result->meta; - - // TODO: Check for 204 status code - foreach ($options as $key => $option) { - $testCase->assertObjectHasAttribute($key, $meta); - $testCase->assertSame($option, $meta->{$key}); - } -} - -/** - * @param TestCase $testCase - * @param ResponseInterface $response - * @param array $fields - */ -function assert_response_meta_fields(TestCase $testCase, ResponseInterface $response, array $fields = []) -{ - $result = response_to_object($response); - $testCase->assertObjectHasAttribute('meta', $result); - $testCase->assertObjectNotHasAttribute('error', $result); - $meta = $result->meta; - - // TODO: Check for 204 status code - foreach ($fields as $field) { - $testCase->assertObjectHasAttribute($field, $meta); - } -} - -/** - * @param TestCase $testCase - * @param ResponseInterface $response - * @param array $expectedData - * @param bool $strict - */ -function assert_response_data_contains(TestCase $testCase, ResponseInterface $response, array $expectedData, $strict = true) -{ - $result = response_to_object($response); - $data = (array)$result->data; - - foreach ($expectedData as $key => $value) { - $testCase->assertArrayHasKey($key, $data); - if ($strict) { - $testCase->assertSame($value, $data[$key]); - } else { - $testCase->assertEquals($value, $data[$key]); - } - } -} - -/** - * @param PHPUnit_Framework_TestCase $testCase - * @param ResponseInterface $response - * @param array $expectedKeys - */ -function assert_response_data_fields(TestCase $testCase, ResponseInterface $response, array $expectedKeys) -{ - $result = response_to_object($response); - - assert_data_fields($testCase, $result->data, $expectedKeys); -} - -/** - * @param PHPUnit_Framework_TestCase $testCase - * @param array|object $data - * @param array $expectedKeys - */ -function assert_data_fields(TestCase $testCase, $data, array $expectedKeys) -{ - if (is_object($data)) { - $data = [(array)$data]; - } - - foreach ($data as $row) { - $testCase->assertCount(count($expectedKeys), (array)$row, 'Expected fields are exactly on each data row'); - - foreach ($row as $field => $value) { - $testCase->assertTrue(in_array($field, $expectedKeys)); - } - } -} - -/** - * @param TestCase $testCase - * @param ResponseInterface $response - * @param array $options - */ -function assert_response_error(TestCase $testCase, ResponseInterface $response, array $options = []) -{ - $result = response_to_object($response); - - $testCase->assertObjectHasAttribute('error', $result); - $testCase->assertObjectNotHasAttribute('data', $result); - - $error = $result->error; - $testCase->assertObjectHasAttribute('code', $error); - $testCase->assertObjectHasAttribute('message', $error); - - if (isset($options['code'])) { - $testCase->assertSame($options['code'], $error->code); - } - - if (isset($options['status'])) { - $testCase->assertSame($options['status'], $response->getStatusCode()); - } -} diff --git a/tests/utils/database.php b/tests/utils/database.php deleted file mode 100644 index e80f7cedbd..0000000000 --- a/tests/utils/database.php +++ /dev/null @@ -1,224 +0,0 @@ - 'Pdo_mysql', - 'host' => \Directus\env('DB_HOST', 'localhost'), - 'port' => \Directus\env('DB_PORT', 3306), - 'database' => \Directus\env('DB_NAME', 'directus_test'), - 'username' => \Directus\env('DB_USERNAME', 'root'), - 'password' => \Directus\env('DB_PASSWORD', null), - 'charset' => $charset, - \PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true, - \PDO::MYSQL_ATTR_INIT_COMMAND => sprintf('SET NAMES "%s"', $charset) - ]); -} - -/** - * Creates a table - * - * @param Connection $db - * @param string $name - */ -function create_table(Connection $db, $name) -{ - $query = sprintf('CREATE TABLE `%s` ( - `id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `name` varchar(100) NOT NULL, - PRIMARY KEY (`id`) - ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;', $name); - - $db->execute($query); -} - -/** - * Fill a table with a array of key values - * - * @param Connection $db - * @param string $table - * @param array $items - */ -function fill_table(Connection $db, $table, array $items) -{ - $gateway = new \Zend\Db\TableGateway\TableGateway($table, $db); - - foreach ($items as $item) { - $gateway->insert($item); - } -} - -/** - * @param Connection $db - * @param string $table - */ -function truncate_table(Connection $db, $table) -{ - $query = 'TRUNCATE `%s`;'; - $db->execute(sprintf($query, $table)); -} - -/** - * @param Connection $db - * @param $table - * - * @return bool - */ -function table_exists(Connection $db, $table) -{ - $query = 'SHOW TABLES LIKE "%s";'; - - $result = $db->execute(sprintf($query, $table)); - - return $result->count() === 1; -} - -/** - * Checks whether a given column exists in a table - * - * @param Connection $db - * @param $table - * @param $column - * - * @return bool - */ -function column_exists(Connection $db, $table, $column) -{ - $query = 'SHOW COLUMNS IN `%s` LIKE "%s";'; - - $result = $db->execute(sprintf($query, $table, $column)); - - return $result->count() === 1; -} - -/** - * @param Connection $db - * @param $table - * @param array $conditions - * - * @return array - */ -function table_find(Connection $db, $table, array $conditions) -{ - $gateway = new \Zend\Db\TableGateway\TableGateway($table, $db); - $result = $gateway->select($conditions); - - return $result->toArray(); -} - -/** - * @param Connection $db - * @param $table - * @param array $conditions - * - * @return int - */ -function delete_item(Connection $db, $table, array $conditions) -{ - $gateway = new \Zend\Db\TableGateway\TableGateway($table, $db); - - return $gateway->delete($conditions); -} - -function table_insert(Connection $db, $table, array $data) -{ - $query = 'INSERT INTO `%s` (%s) VALUES (%s)'; - - $columns = array_map(function ($column) { - return sprintf('`%s`', $column); - }, array_keys($data)); - - $values = array_map(function ($value) { - if (is_string($value)) { - $value = sprintf('"%s"', $value); - } else if (is_null($value)) { - $value = 'NULL'; - } - - return $value; - }, $data); - - $db->execute(sprintf($query, $table, implode(', ', $columns), implode(', ', $values))); -} - -/** - * @param Connection $db - * @param string $table - */ -function drop_table(Connection $db, $table) -{ - $query = 'DROP TABLE IF EXISTS `%s`;'; - $db->execute(sprintf($query, $table)); - - delete_item($db, 'directus_collections', [ - 'collection' => $table - ]); - - delete_item($db, 'directus_fields', [ - 'collection' => $table - ]); -} - -/** - * @param Connection $db - * @param string $table - * @param int $value - */ -function reset_autoincrement(Connection $db, $table, $value = 1) -{ - $query = 'ALTER TABLE `%s` AUTO_INCREMENT = %d;'; - - $db->execute(sprintf($query, $table, $value)); -} - -/** - * Resets a table to a given id - * - * Removes every item after the $nextId - * - * @param Connection $db - * @param $table - * @param $nextId - */ -function reset_table_id(Connection $db, $table, $nextId) -{ - $deleteQueryFormat = 'DELETE FROM `%s` WHERE `id` >= %d;'; - $db->execute(sprintf( - $deleteQueryFormat, - $table, - $nextId - )); - - reset_autoincrement($db, $table, $nextId); -} - -/** - * Returns the table record count - * - * @param Connection $db - * @param string $table - * - * @return int - */ -function table_count(Connection $db, $table) -{ - $gateway = new \Zend\Db\TableGateway\TableGateway($table, $db); - $select = $gateway->getSql()->select(); - $select->columns(array('count' => new \Zend\Db\Sql\Expression('COUNT(*)'))); - - $result = $gateway->selectWith($select); - - return (int) $result->current()->count; -} diff --git a/tests/utils/helper.php b/tests/utils/helper.php deleted file mode 100644 index 6c1555c221..0000000000 --- a/tests/utils/helper.php +++ /dev/null @@ -1,58 +0,0 @@ -getBody()->rewind(); - - return json_decode($response->getBody()->getContents()); -} - -/** - * Gets the response object data - * - * @param \Psr\Http\Message\ResponseInterface $response - * - * @return array|object - */ -function response_get_data(\Psr\Http\Message\ResponseInterface $response) -{ - $object = response_to_object($response); - - return $object->data; -} - -/** - * Gets the request body contents - * - * @param \Psr\Http\Message\ResponseInterface $response - * - * @return string - */ -function response_get_body_contents(\Psr\Http\Message\ResponseInterface $response) -{ - $response->getBody()->rewind(); - - return $response->getBody()->getContents(); -} - -function clear_storage($basePath) -{ - $uploadsOmit = ['.gitignore', '.htaccess']; - foreach (glob($basePath . "/*") as $filename) { - $name = basename($filename); - if (is_dir($filename) || in_array($name, $uploadsOmit)) { - continue; - } - - unlink($filename); - } -} diff --git a/tests/utils/io_functions.php b/tests/utils/io_functions.php deleted file mode 100644 index f249b6b077..0000000000 --- a/tests/utils/io_functions.php +++ /dev/null @@ -1,6 +0,0 @@ - \Directus\env('API_URL', 'http://localhost/api') - ]); - - // if json is set to true, it means we want the body to be a JSON - if (isset($options['form_params']) && isset($options['json']) && $options['json'] === true) { - $options['json'] = $options['form_params']; - unset($options['form_params']); - } - - $projectName = isset($options['project']) ? $options['project'] : '_'; - if ($projectName !== false) { - $path = sprintf('%s/%s', $projectName, $path); - } - - $response = $http->request($method, $path, $options); - - return $response; -} - -/** - * @param string $path - * @param array $params - * @param array $options - * - * @return \Psr\Http\Message\ResponseInterface - */ -function request_get($path, array $params = [], array $options = []) -{ - $options['query'] = $params; - - return request('GET', $path, $options); -} - -/** - * @param string $path - * @param array $body - * @param array $options - * - * @return \Psr\Http\Message\ResponseInterface - */ -function request_post($path, array $body = [], array $options = []) -{ - $options['form_params'] = $body; - - return request('POST', $path, $options); -} - -/** - * @param string $path - * @param array $body - * @param array $options - * - * @return \Psr\Http\Message\ResponseInterface - */ -function request_patch($path, array $body = [], array $options = []) -{ - $options['form_params'] = $body; - - return request('PATCH', $path, $options); -} - -/** - * @param string $path - * @param array $options - * - * @return \Psr\Http\Message\ResponseInterface - */ -function request_delete($path, array $options = []) -{ - return request('DELETE', $path, $options); -} - -/** - * @param string $method - * @param string $path - * @param array $options - * - * @return \Psr\Http\Message\ResponseInterface - */ -function request_error($method, $path, array $options = []) -{ - try { - $response = request($method, $path, $options); - } catch (\GuzzleHttp\Exception\BadResponseException$e) { - $response = $e->getResponse(); - } - - return $response; -} - -/** - * @param string $path - * @param array $params - * @param array $options - * - * @return \Psr\Http\Message\ResponseInterface - */ -function request_error_get($path, array $params = [], array $options = []) -{ - $options['query'] = $params; - - return request_error('GET', $path, $options); -} - -/** - * @param string $path - * @param array $body - * @param array $options - * - * @return \Psr\Http\Message\ResponseInterface - */ -function request_error_post($path, array $body, array $options = []) -{ - $options['form_params'] = $body; - - return request_error('POST', $path, $options); -} - -/** - * @param string $path - * @param array $body - * @param array $options - * - * @return \Psr\Http\Message\ResponseInterface - */ -function request_error_put($path, array $body, array $options = []) -{ - $options['form_params'] = $body; - - return request_error('PUT', $path, $options); -} - -/** - * @param string $path - * @param array $body - * @param array $options - * - * @return \Psr\Http\Message\ResponseInterface - */ -function request_error_patch($path, array $body, array $options = []) -{ - $options['form_params'] = $body; - - return request_error('PATCH', $path, $options); -} - -/** - * @param $path - * @param array $options - * - * @return \Psr\Http\Message\ResponseInterface - */ -function request_error_delete($path, array $options = []) -{ - return request_error('DELETE', $path, $options); -}