diff --git a/.gitignore b/.gitignore index c73b3bb995771865a07100f434f082168c124986..6aac9a0efe1869a89405108040bfe493a24bfc8a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ /.idea/ /vendor/ -/build/ \ No newline at end of file +/build/ +.phpunit.result.cache \ No newline at end of file diff --git a/README.md b/README.md index 2140373a86e2870d71266dbec55d3c5e13ff6d38..13650de1119ed248fa68b3a98607e4dc99ed2dc8 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,7 @@ # simplesamlphp-module-accounting SimpleSAMLphp module providing user accounting functionality + +## TODO +- [ ] MySQL store +- [ ] MySQL Job Store +- [ ] Cron hooks \ No newline at end of file diff --git a/composer.json b/composer.json index 90a1ddffc215bec6702c6ca69f29868b6f308e97..a746b29462019d758f722b2bb95f732a2dbba331 100644 --- a/composer.json +++ b/composer.json @@ -29,6 +29,7 @@ "ext-pdo": "*", "ext-pdo_mysql": "*", "ext-pdo_sqlite": "*", + "doctrine/dbal": "^3", "simplesamlphp/composer-module-installer": "^1" }, "require-dev": { @@ -37,5 +38,12 @@ "squizlabs/php_codesniffer": "^3", "simplesamlphp/simplesamlphp": "^2@beta", "simplesamlphp/simplesamlphp-test-framework": "^1" + }, + "scripts": { + "pre-commit": [ + "vendor/bin/phpcs -p", + "vendor/bin/psalm", + "vendor/bin/phpunit" + ] } } diff --git a/composer.lock b/composer.lock index 868770c465f055a41ac222f08ecbbb7c8eb779b8..0c8514b945ace5ebb9e720450585f7d3023e946a 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "1de774adafcb72fec83aa2a75d809c3f", + "content-hash": "c3bebdab1f5cd01e6c038f6defc7bdbe", "packages": [ { "name": "composer/ca-bundle", @@ -559,6 +559,347 @@ ], "time": "2022-02-25T21:32:43+00:00" }, + { + "name": "doctrine/cache", + "version": "2.2.0", + "source": { + "type": "git", + "url": "https://github.com/doctrine/cache.git", + "reference": "1ca8f21980e770095a31456042471a57bc4c68fb" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/doctrine/cache/zipball/1ca8f21980e770095a31456042471a57bc4c68fb", + "reference": "1ca8f21980e770095a31456042471a57bc4c68fb", + "shasum": "" + }, + "require": { + "php": "~7.1 || ^8.0" + }, + "conflict": { + "doctrine/common": ">2.2,<2.4" + }, + "require-dev": { + "cache/integration-tests": "dev-master", + "doctrine/coding-standard": "^9", + "phpunit/phpunit": "^7.5 || ^8.5 || ^9.5", + "psr/cache": "^1.0 || ^2.0 || ^3.0", + "symfony/cache": "^4.4 || ^5.4 || ^6", + "symfony/var-exporter": "^4.4 || ^5.4 || ^6" + }, + "type": "library", + "autoload": { + "psr-4": { + "Doctrine\\Common\\Cache\\": "lib/Doctrine/Common/Cache" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Guilherme Blanco", + "email": "guilhermeblanco@gmail.com" + }, + { + "name": "Roman Borschel", + "email": "roman@code-factory.org" + }, + { + "name": "Benjamin Eberlei", + "email": "kontakt@beberlei.de" + }, + { + "name": "Jonathan Wage", + "email": "jonwage@gmail.com" + }, + { + "name": "Johannes Schmitt", + "email": "schmittjoh@gmail.com" + } + ], + "description": "PHP Doctrine Cache library is a popular cache implementation that supports many different drivers such as redis, memcache, apc, mongodb and others.", + "homepage": "https://www.doctrine-project.org/projects/cache.html", + "keywords": [ + "abstraction", + "apcu", + "cache", + "caching", + "couchdb", + "memcached", + "php", + "redis", + "xcache" + ], + "support": { + "issues": "https://github.com/doctrine/cache/issues", + "source": "https://github.com/doctrine/cache/tree/2.2.0" + }, + "funding": [ + { + "url": "https://www.doctrine-project.org/sponsorship.html", + "type": "custom" + }, + { + "url": "https://www.patreon.com/phpdoctrine", + "type": "patreon" + }, + { + "url": "https://tidelift.com/funding/github/packagist/doctrine%2Fcache", + "type": "tidelift" + } + ], + "time": "2022-05-20T20:07:39+00:00" + }, + { + "name": "doctrine/dbal", + "version": "3.3.6", + "source": { + "type": "git", + "url": "https://github.com/doctrine/dbal.git", + "reference": "9e7f76dd1cde81c62574fdffa5a9c655c847ad21" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/doctrine/dbal/zipball/9e7f76dd1cde81c62574fdffa5a9c655c847ad21", + "reference": "9e7f76dd1cde81c62574fdffa5a9c655c847ad21", + "shasum": "" + }, + "require": { + "composer-runtime-api": "^2", + "doctrine/cache": "^1.11|^2.0", + "doctrine/deprecations": "^0.5.3|^1", + "doctrine/event-manager": "^1.0", + "php": "^7.3 || ^8.0", + "psr/cache": "^1|^2|^3", + "psr/log": "^1|^2|^3" + }, + "require-dev": { + "doctrine/coding-standard": "9.0.0", + "jetbrains/phpstorm-stubs": "2022.1", + "phpstan/phpstan": "1.6.3", + "phpstan/phpstan-strict-rules": "^1.2", + "phpunit/phpunit": "9.5.20", + "psalm/plugin-phpunit": "0.16.1", + "squizlabs/php_codesniffer": "3.6.2", + "symfony/cache": "^5.2|^6.0", + "symfony/console": "^2.7|^3.0|^4.0|^5.0|^6.0", + "vimeo/psalm": "4.23.0" + }, + "suggest": { + "symfony/console": "For helpful console commands such as SQL execution and import of files." + }, + "bin": [ + "bin/doctrine-dbal" + ], + "type": "library", + "autoload": { + "psr-4": { + "Doctrine\\DBAL\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Guilherme Blanco", + "email": "guilhermeblanco@gmail.com" + }, + { + "name": "Roman Borschel", + "email": "roman@code-factory.org" + }, + { + "name": "Benjamin Eberlei", + "email": "kontakt@beberlei.de" + }, + { + "name": "Jonathan Wage", + "email": "jonwage@gmail.com" + } + ], + "description": "Powerful PHP database abstraction layer (DBAL) with many features for database schema introspection and management.", + "homepage": "https://www.doctrine-project.org/projects/dbal.html", + "keywords": [ + "abstraction", + "database", + "db2", + "dbal", + "mariadb", + "mssql", + "mysql", + "oci8", + "oracle", + "pdo", + "pgsql", + "postgresql", + "queryobject", + "sasql", + "sql", + "sqlite", + "sqlserver", + "sqlsrv" + ], + "support": { + "issues": "https://github.com/doctrine/dbal/issues", + "source": "https://github.com/doctrine/dbal/tree/3.3.6" + }, + "funding": [ + { + "url": "https://www.doctrine-project.org/sponsorship.html", + "type": "custom" + }, + { + "url": "https://www.patreon.com/phpdoctrine", + "type": "patreon" + }, + { + "url": "https://tidelift.com/funding/github/packagist/doctrine%2Fdbal", + "type": "tidelift" + } + ], + "time": "2022-05-02T17:21:01+00:00" + }, + { + "name": "doctrine/deprecations", + "version": "v1.0.0", + "source": { + "type": "git", + "url": "https://github.com/doctrine/deprecations.git", + "reference": "0e2a4f1f8cdfc7a92ec3b01c9334898c806b30de" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/doctrine/deprecations/zipball/0e2a4f1f8cdfc7a92ec3b01c9334898c806b30de", + "reference": "0e2a4f1f8cdfc7a92ec3b01c9334898c806b30de", + "shasum": "" + }, + "require": { + "php": "^7.1|^8.0" + }, + "require-dev": { + "doctrine/coding-standard": "^9", + "phpunit/phpunit": "^7.5|^8.5|^9.5", + "psr/log": "^1|^2|^3" + }, + "suggest": { + "psr/log": "Allows logging deprecations via PSR-3 logger implementation" + }, + "type": "library", + "autoload": { + "psr-4": { + "Doctrine\\Deprecations\\": "lib/Doctrine/Deprecations" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "A small layer on top of trigger_error(E_USER_DEPRECATED) or PSR-3 logging with options to disable all deprecations or selectively for packages.", + "homepage": "https://www.doctrine-project.org/", + "support": { + "issues": "https://github.com/doctrine/deprecations/issues", + "source": "https://github.com/doctrine/deprecations/tree/v1.0.0" + }, + "time": "2022-05-02T15:47:09+00:00" + }, + { + "name": "doctrine/event-manager", + "version": "1.1.1", + "source": { + "type": "git", + "url": "https://github.com/doctrine/event-manager.git", + "reference": "41370af6a30faa9dc0368c4a6814d596e81aba7f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/doctrine/event-manager/zipball/41370af6a30faa9dc0368c4a6814d596e81aba7f", + "reference": "41370af6a30faa9dc0368c4a6814d596e81aba7f", + "shasum": "" + }, + "require": { + "php": "^7.1 || ^8.0" + }, + "conflict": { + "doctrine/common": "<2.9@dev" + }, + "require-dev": { + "doctrine/coding-standard": "^6.0", + "phpunit/phpunit": "^7.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Doctrine\\Common\\": "lib/Doctrine/Common" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Guilherme Blanco", + "email": "guilhermeblanco@gmail.com" + }, + { + "name": "Roman Borschel", + "email": "roman@code-factory.org" + }, + { + "name": "Benjamin Eberlei", + "email": "kontakt@beberlei.de" + }, + { + "name": "Jonathan Wage", + "email": "jonwage@gmail.com" + }, + { + "name": "Johannes Schmitt", + "email": "schmittjoh@gmail.com" + }, + { + "name": "Marco Pivetta", + "email": "ocramius@gmail.com" + } + ], + "description": "The Doctrine Event Manager is a simple PHP event system that was built to be used with the various Doctrine projects.", + "homepage": "https://www.doctrine-project.org/projects/event-manager.html", + "keywords": [ + "event", + "event dispatcher", + "event manager", + "event system", + "events" + ], + "support": { + "issues": "https://github.com/doctrine/event-manager/issues", + "source": "https://github.com/doctrine/event-manager/tree/1.1.x" + }, + "funding": [ + { + "url": "https://www.doctrine-project.org/sponsorship.html", + "type": "custom" + }, + { + "url": "https://www.patreon.com/phpdoctrine", + "type": "patreon" + }, + { + "url": "https://tidelift.com/funding/github/packagist/doctrine%2Fevent-manager", + "type": "tidelift" + } + ], + "time": "2020-05-29T18:28:51+00:00" + }, { "name": "gettext/gettext", "version": "v5.6.1", @@ -853,16 +1194,16 @@ }, { "name": "phpmailer/phpmailer", - "version": "v6.6.0", + "version": "v6.6.2", "source": { "type": "git", "url": "https://github.com/PHPMailer/PHPMailer.git", - "reference": "e43bac82edc26ca04b36143a48bde1c051cfd5b1" + "reference": "b52ed06864fdda81b82ec8bf564cf15d45ed4f95" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/PHPMailer/PHPMailer/zipball/e43bac82edc26ca04b36143a48bde1c051cfd5b1", - "reference": "e43bac82edc26ca04b36143a48bde1c051cfd5b1", + "url": "https://api.github.com/repos/PHPMailer/PHPMailer/zipball/b52ed06864fdda81b82ec8bf564cf15d45ed4f95", + "reference": "b52ed06864fdda81b82ec8bf564cf15d45ed4f95", "shasum": "" }, "require": { @@ -874,8 +1215,8 @@ "require-dev": { "dealerdirect/phpcodesniffer-composer-installer": "^0.7.0", "doctrine/annotations": "^1.2", - "php-parallel-lint/php-console-highlighter": "^0.5.0", - "php-parallel-lint/php-parallel-lint": "^1.3.1", + "php-parallel-lint/php-console-highlighter": "^1.0.0", + "php-parallel-lint/php-parallel-lint": "^1.3.2", "phpcompatibility/php-compatibility": "^9.3.5", "roave/security-advisories": "dev-latest", "squizlabs/php_codesniffer": "^3.6.2", @@ -919,7 +1260,7 @@ "description": "PHPMailer is a full-featured email creation and transfer class for PHP", "support": { "issues": "https://github.com/PHPMailer/PHPMailer/issues", - "source": "https://github.com/PHPMailer/PHPMailer/tree/v6.6.0" + "source": "https://github.com/PHPMailer/PHPMailer/tree/v6.6.2" }, "funding": [ { @@ -927,7 +1268,7 @@ "type": "github" } ], - "time": "2022-02-28T15:31:21+00:00" + "time": "2022-06-14T09:27:21+00:00" }, { "name": "psr/cache", @@ -1450,16 +1791,16 @@ }, { "name": "simplesamlphp/saml2", - "version": "v4.6.1", + "version": "v4.6.3", "source": { "type": "git", "url": "https://github.com/simplesamlphp/saml2.git", - "reference": "5e46819fdb76657f13e05a8f264d06efd9163c3d" + "reference": "bfc9c79dd6b728a41d1de988f545f6e64728a51d" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/simplesamlphp/saml2/zipball/5e46819fdb76657f13e05a8f264d06efd9163c3d", - "reference": "5e46819fdb76657f13e05a8f264d06efd9163c3d", + "url": "https://api.github.com/repos/simplesamlphp/saml2/zipball/bfc9c79dd6b728a41d1de988f545f6e64728a51d", + "reference": "bfc9c79dd6b728a41d1de988f545f6e64728a51d", "shasum": "" }, "require": { @@ -1467,7 +1808,7 @@ "ext-openssl": "*", "ext-zlib": "*", "php": ">=7.1 || ^8.0", - "psr/log": "~1.1", + "psr/log": "~1.1 || ^2.0 || ^3.0", "robrichards/xmlseclibs": "^3.1.1", "webmozart/assert": "^1.9" }, @@ -1502,9 +1843,9 @@ "description": "SAML2 PHP library from SimpleSAMLphp", "support": { "issues": "https://github.com/simplesamlphp/saml2/issues", - "source": "https://github.com/simplesamlphp/saml2/tree/v4.6.1" + "source": "https://github.com/simplesamlphp/saml2/tree/v4.6.3" }, - "time": "2022-05-23T20:49:55+00:00" + "time": "2022-06-13T14:04:10+00:00" }, { "name": "simplesamlphp/simplesamlphp", @@ -6899,16 +7240,16 @@ }, { "name": "squizlabs/php_codesniffer", - "version": "3.6.2", + "version": "3.7.0", "source": { "type": "git", "url": "https://github.com/squizlabs/PHP_CodeSniffer.git", - "reference": "5e4e71592f69da17871dba6e80dd51bce74a351a" + "reference": "a2cd51b45bcaef9c1f2a4bda48f2dd2fa2b95563" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/squizlabs/PHP_CodeSniffer/zipball/5e4e71592f69da17871dba6e80dd51bce74a351a", - "reference": "5e4e71592f69da17871dba6e80dd51bce74a351a", + "url": "https://api.github.com/repos/squizlabs/PHP_CodeSniffer/zipball/a2cd51b45bcaef9c1f2a4bda48f2dd2fa2b95563", + "reference": "a2cd51b45bcaef9c1f2a4bda48f2dd2fa2b95563", "shasum": "" }, "require": { @@ -6951,7 +7292,7 @@ "source": "https://github.com/squizlabs/PHP_CodeSniffer", "wiki": "https://github.com/squizlabs/PHP_CodeSniffer/wiki" }, - "time": "2021-12-12T21:44:58+00:00" + "time": "2022-06-13T06:31:38+00:00" }, { "name": "symfony/phpunit-bridge", diff --git a/config-templates/module_accounting.php b/config-templates/module_accounting.php index 29497c1408b560e20d0af32af9f85340f549b679..0c00e1055b3b39d7af18c79b0b2f3c5de5098293 100644 --- a/config-templates/module_accounting.php +++ b/config-templates/module_accounting.php @@ -1,5 +1,76 @@ <?php +declare(strict_types=1); + +use SimpleSAML\Module\accounting\ModuleConfiguration; +use SimpleSAML\Module\accounting\Stores; + $config = [ - 'test-config' => 'test-value', + /** + * User ID attribute, one that is always available and that is unique to all users. + * If this attribute is not available, accounting will not be performed for that user. + * + * Examples: + * urn:oasis:names:tc:SAML:attribute:subject-id + * eduPersonUniqueId + * eduPersonPrincipalName + */ + ModuleConfiguration::OPTION_USER_ID_ATTRIBUTE => 'urn:oasis:names:tc:SAML:attribute:subject-id', + + /** + * Accounting processing type. There are two possible types: 'synchronous' and 'asynchronous'. + * - 'synchronous': accounting processing will be performed during authentication itself (slower) + * - 'asynchronous': for each authentication event a new job will be created for later processing (faster, + * but requires setting up job storage and a cron entry). + */ + ModuleConfiguration::OPTION_ACCOUNTING_PROCESSING_TYPE => + ModuleConfiguration\AccountingProcessingType::VALUE_SYNCHRONOUS, + + /** + * Jobs store. Determines which of the available stores will be used to store jobs in case the 'asynchronous' + * accounting processing type was set. + */ + ModuleConfiguration::OPTION_JOBS_STORE => Stores\Jobs\DoctrineDbal\JobsStore::class, + + /** + * Store connection for particular store. Can be used to set different connections for different stores. + */ + ModuleConfiguration::OPTION_STORE_TO_CONNECTION_KEY_MAP => [ + Stores\Jobs\DoctrineDbal\JobsStore::class => 'doctrine_dbal_pdo_mysql', + ], + + /** + * Store connections and their parameters. + * + * Any compatible Doctrine DBAL implementation can be used: + * https://www.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/configuration.html + * There are additional parameters for: table prefix. + * Examples for mysql and sqlite are provided below. + */ + ModuleConfiguration::OPTION_ALL_STORE_CONNECTIONS_AND_PARAMETERS => [ + 'doctrine_dbal_pdo_mysql' => [ + 'driver' => 'pdo_mysql', // (string): The built-in driver implementation to use + 'user' => 'user', // (string): Username to use when connecting to the database. + 'password' => 'password', // (string): Password to use when connecting to the database. + 'host' => 'host', // (string): Hostname of the database to connect to. + 'port' => 3306, // (integer): Port of the database to connect to. + 'dbname' => 'dbname', // (string): Name of the database/schema to connect to. + //'unix_socket' => 'unix_socet', // (string): Name of the socket used to connect to the database. + 'charset' => 'utf8', // (string): The charset used when connecting to the database. + //'url' => 'mysql://user:secret@localhost/mydb?charset=utf8', // ...alternative way of providing parameters. + // Additional parameters not originaly avaliable in Doctrine DBAL + 'table_prefix' => '', // (string): Prefix for each table. + ], + 'doctrine_dbal_pdo_sqlite' => [ + 'driver' => 'pdo_sqlite', // (string): The built-in driver implementation to use + 'path' => '/path/to/db.sqlite', // (string): The filesystem path to the database file. + // Mutually exclusive with memory. path takes precedence. + 'memory' => false, // (boolean): True if the SQLite database should be in-memory (non-persistent). + // Mutually exclusive with path. path takes precedence. + //'url' => 'sqlite:////path/to/db.sqlite // ...alternative way of providing path parameter. + //'url' => 'sqlite:///:memory:' // ...alternative way of providing memory parameter. + // Additional parameters not originaly avaliable in Doctrine DBAL + 'table_prefix' => '', // (string): Prefix for each table. + ], + ], ]; diff --git a/src/Controller/Test.php b/src/Controller/Test.php index ec6d040d4025084b4b4cda58547303172babe48e..1098829918603cf8d2ac0ee624573250ce031860 100644 --- a/src/Controller/Test.php +++ b/src/Controller/Test.php @@ -1,5 +1,7 @@ <?php +declare(strict_types=1); + namespace SimpleSAML\Module\accounting\Controller; use SimpleSAML\Configuration; diff --git a/src/Exceptions/InvalidConfigurationException.php b/src/Exceptions/InvalidConfigurationException.php new file mode 100644 index 0000000000000000000000000000000000000000..24cf0ebad073769cb93f711c7c3cabfca2d6c85a --- /dev/null +++ b/src/Exceptions/InvalidConfigurationException.php @@ -0,0 +1,9 @@ +<?php + +declare(strict_types=1); + +namespace SimpleSAML\Module\accounting\Exceptions; + +class InvalidConfigurationException extends \ValueError +{ +} diff --git a/src/Exceptions/InvalidValueException.php b/src/Exceptions/InvalidValueException.php new file mode 100644 index 0000000000000000000000000000000000000000..81be77ef32ec586e4f48c1eafa3fd6a54e5f9d58 --- /dev/null +++ b/src/Exceptions/InvalidValueException.php @@ -0,0 +1,9 @@ +<?php + +declare(strict_types=1); + +namespace SimpleSAML\Module\accounting\Exceptions; + +class InvalidValueException extends \ValueError +{ +} diff --git a/src/Exceptions/MigrationException.php b/src/Exceptions/MigrationException.php new file mode 100644 index 0000000000000000000000000000000000000000..5afd8a7d8453c6c54f320690856b1eada1aa7019 --- /dev/null +++ b/src/Exceptions/MigrationException.php @@ -0,0 +1,9 @@ +<?php + +declare(strict_types=1); + +namespace SimpleSAML\Module\accounting\Exceptions; + +class MigrationException extends \Exception +{ +} diff --git a/src/Exceptions/ModuleConfiguration/InvalidConfigurationNameException.php b/src/Exceptions/ModuleConfiguration/InvalidConfigurationNameException.php deleted file mode 100644 index 51cb2435eb7b7a7b2798fba0fd18cffcbac2f33b..0000000000000000000000000000000000000000 --- a/src/Exceptions/ModuleConfiguration/InvalidConfigurationNameException.php +++ /dev/null @@ -1,7 +0,0 @@ -<?php - -namespace SimpleSAML\Module\accounting\Exceptions\ModuleConfiguration; - -class InvalidConfigurationNameException extends \InvalidArgumentException -{ -} diff --git a/src/Helpers/FilesystemHelper.php b/src/Helpers/FilesystemHelper.php new file mode 100644 index 0000000000000000000000000000000000000000..a33fd0ac1105e0e88627490a407b41e15dcd8d9c --- /dev/null +++ b/src/Helpers/FilesystemHelper.php @@ -0,0 +1,21 @@ +<?php + +declare(strict_types=1); + +namespace SimpleSAML\Module\accounting\Helpers; + +use SimpleSAML\Module\accounting\Exceptions\InvalidValueException; + +class FilesystemHelper +{ + public static function getRealPath(string $path): string + { + $path = realpath($path); + + if ($path === false || ! (is_dir($path) || is_file($path))) { + throw new InvalidValueException('Given path can not be translated to real path.'); + } + + return $path; + } +} diff --git a/src/ModuleConfiguration.php b/src/ModuleConfiguration.php index 4f22576400de13b5e32bed8c518726a5be9c3bb3..1dcbe138067458f6c3481fd5e4cef86cc91aa036 100644 --- a/src/ModuleConfiguration.php +++ b/src/ModuleConfiguration.php @@ -1,18 +1,33 @@ <?php +declare(strict_types=1); + namespace SimpleSAML\Module\accounting; +use Exception; use SimpleSAML\Configuration; -use SimpleSAML\Module\accounting\Exceptions\ModuleConfiguration\InvalidConfigurationNameException; +use SimpleSAML\Module\accounting\Exceptions\InvalidConfigurationException; class ModuleConfiguration { - protected Configuration $configuration; - + /** + * Default file name for module configuration. Can be overridden, for example, for testing purposes. + */ public const FILE_NAME = 'module_accounting.php'; + public const OPTION_USER_ID_ATTRIBUTE = 'user_id_attribute'; + public const OPTION_ACCOUNTING_PROCESSING_TYPE = 'accounting_processing_type'; + public const OPTION_JOBS_STORE = 'jobs_store'; + public const OPTION_ALL_STORE_CONNECTIONS_AND_PARAMETERS = 'all_store_connection_and_parameters'; + public const OPTION_STORE_TO_CONNECTION_KEY_MAP = 'store_to_connection_key_map'; + /** - * @throws \Exception + * Contains configuration from module configuration file. + */ + protected Configuration $configuration; + + /** + * @throws Exception */ public function __construct(string $fileName = null) { @@ -22,23 +37,75 @@ class ModuleConfiguration } /** - * @param string $name + * Get configuration option from module configuration file. + * + * @param string $option * @return mixed */ - public function getValue(string $name) + public function get(string $option) { - if (! $this->configuration->hasValue($name)) { - throw new InvalidConfigurationNameException(sprintf('Config name does not exist (%s).', $name)); + if (! $this->configuration->hasValue($option)) { + throw new InvalidConfigurationException( + sprintf('Configuration option does not exist (%s).', $option) + ); } - return $this->configuration->getValue($name); + return $this->configuration->getValue($option); } /** + * Get underlying SimpleSAMLphp Configuration instance. + * * @return Configuration */ public function getConfiguration(): Configuration { return $this->configuration; } + + public function getStoreConnection(string $store): string + { + $connectionMap = $this->getStoreToConnectionMap(); + + if (! isset($connectionMap[$store])) { + throw new InvalidConfigurationException( + sprintf('Connection for store %s is not set.', $store) + ); + } + + return (string) $connectionMap[$store]; + } + + public function getStoreToConnectionMap(): array + { + return $this->getConfiguration()->getArray(self::OPTION_STORE_TO_CONNECTION_KEY_MAP); + } + + public function getAllStoreConnectionsAndParameters(): array + { + return $this->getConfiguration()->getArray(self::OPTION_ALL_STORE_CONNECTIONS_AND_PARAMETERS); + } + + public function getStoreConnectionParameters(string $connection): array + { + $connections = $this->getAllStoreConnectionsAndParameters(); + + if (! isset($connections[$connection]) || ! is_array($connections[$connection])) { + throw new InvalidConfigurationException( + sprintf('Settings for connection %s not set', $connection) + ); + } + + return $connections[$connection]; + } + + public function getModuleSourceDirectory(): string + { + return __DIR__; + } + + public function getModuleRootDirectory(): string + { + return dirname(__DIR__); + } } diff --git a/src/ModuleConfiguration/AccountingProcessingType.php b/src/ModuleConfiguration/AccountingProcessingType.php new file mode 100644 index 0000000000000000000000000000000000000000..53c88fe84b6178a04b461bb6f24e9e99fd231059 --- /dev/null +++ b/src/ModuleConfiguration/AccountingProcessingType.php @@ -0,0 +1,16 @@ +<?php + +declare(strict_types=1); + +namespace SimpleSAML\Module\accounting\ModuleConfiguration; + +class AccountingProcessingType +{ + public const VALUE_SYNCHRONOUS = 'synchronous'; + public const VALUE_ASYNCHRONOUS = 'asynchronous'; + + public const VALID_OPTIONS = [ + self::VALUE_SYNCHRONOUS, + self::VALUE_ASYNCHRONOUS, + ]; +} diff --git a/src/Services/LoggerService.php b/src/Services/LoggerService.php new file mode 100644 index 0000000000000000000000000000000000000000..5dc711e67a4c2c6d20e68fa0331cce1bb956befd --- /dev/null +++ b/src/Services/LoggerService.php @@ -0,0 +1,98 @@ +<?php + +namespace SimpleSAML\Module\accounting\Services; + +use SimpleSAML\Logger; + +class LoggerService +{ + /** + * Log an emergency message. + * + * @param string $message The message to log. + */ + public function emergency(string $message): void + { + Logger::emergency($message); + } + + /** + * Log a critical message. + * + * @param string $message The message to log. + */ + public function critical(string $message): void + { + Logger::critical($message); + } + + /** + * Log an alert message. + * + * @param string $message The message to log. + */ + public function alert(string $message): void + { + Logger::alert($message); + } + + /** + * Log an error message. + * + * @param string $message The message to log. + */ + public function error(string $message): void + { + Logger::error($message); + } + + /** + * Log a warning message. + * + * @param string $message The message to log. + */ + public function warning(string $message): void + { + Logger::warning($message); + } + + /** + * Log a notice message. + * + * @param string $message The message to log. + */ + public function notice(string $message): void + { + Logger::notice($message); + } + + /** + * Log an info message (a bit less verbose than debug messages). + * + * @param string $message The message to log. + */ + public function info(string $message): void + { + Logger::info($message); + } + + /** + * Log a debug message (very verbose messages). + * + * @param string $message The message to log. + */ + public function debug(string $message): void + { + Logger::debug($message); + } + + /** + * Log a statistics message. + * + * @param string $message The message to log. + */ + public function stats(string $message): void + { + Logger::stats($message); + } +} diff --git a/src/Stores/Connections/Bases/AbstractMigrator.php b/src/Stores/Connections/Bases/AbstractMigrator.php new file mode 100644 index 0000000000000000000000000000000000000000..0a68d56f216a1236861540eea483b763f3ef43f0 --- /dev/null +++ b/src/Stores/Connections/Bases/AbstractMigrator.php @@ -0,0 +1,127 @@ +<?php + +declare(strict_types=1); + +namespace SimpleSAML\Module\accounting\Stores\Connections\Bases; + +use SimpleSAML\Module\accounting\Exceptions\InvalidValueException; +use SimpleSAML\Module\accounting\Exceptions\MigrationException; +use SimpleSAML\Module\accounting\Helpers\FilesystemHelper; +use SimpleSAML\Module\accounting\Stores\Interfaces\MigrationInterface; + +abstract class AbstractMigrator +{ + public const DEFAULT_MIGRATIONS_DIRECTORY_NAME = 'Migrations'; + + /** + * @param string $directory + * @param string $namespace + * @return class-string[] + */ + public function gatherMigrationClassesFromDirectory(string $directory, string $namespace): array + { + $directory = FilesystemHelper::getRealPath($directory); + + // Get files without dot directories + $files = array_values(array_diff(scandir($directory), ['..', '.'])); + + array_walk($files, function (string &$file) use ($namespace) { + // Remove .php extension from filename + $file = basename($file, '.php'); + // Prepend namespace for each entry + $file = $namespace . '\\' . $file; + }); + + // Migration classes must follow proper interfaces, so do validate each of them and discard invalid ones. + /** @var class-string[] $migrationClasses */ + $migrationClasses = array_filter($files, function (string $file) { + try { + $this->validateMigrationClass($file); + return true; + } catch (InvalidValueException $exception) { + return false; + } + }); + + return $migrationClasses; + } + + /** + * @param class-string[] $migrationClasses + * @return void + */ + public function runMigrationClasses(array $migrationClasses): void + { + foreach ($migrationClasses as $migrationClass) { + $this->validateMigrationClass($migrationClass); + + $migration = $this->buildMigrationClassInstance($migrationClass); + + try { + $migration->run(); + } catch (\Throwable $exception) { + $message = sprintf( + 'Could not run migration class %s. Error was: %s', + $migrationClass, + $exception->getMessage() + ); + + throw new MigrationException($message); + } + + $this->markImplementedMigrationClass($migrationClass); + } + } + + /** + * @return class-string[] + */ + public function getNonImplementedMigrationClasses(string $directory, string $namespace): array + { + return array_diff( + $this->gatherMigrationClassesFromDirectory($directory, $namespace), + $this->getImplementedMigrationClasses() + ); + } + + /** + * @param string $directory + * @param string $namespace + * @return bool + */ + public function hasNonImplementedMigrationClasses(string $directory, string $namespace): bool + { + return ! empty($this->getNonImplementedMigrationClasses($directory, $namespace)); + } + + public function runNonImplementedMigrationClasses(string $directory, string $namespace): void + { + $this->runMigrationClasses($this->getNonImplementedMigrationClasses($directory, $namespace)); + } + + public function validateMigrationClass(string $migrationClass): void + { + if (! is_subclass_of($migrationClass, MigrationInterface::class)) { + throw new InvalidValueException( + sprintf('Migration class does not implement MigrationInterface (%s)', $migrationClass) + ); + } + } + + /** + * @param class-string $migrationClass + * @return MigrationInterface + */ + abstract protected function buildMigrationClassInstance(string $migrationClass): MigrationInterface; + + /** + * @param class-string $migrationClass + * @return void + */ + abstract protected function markImplementedMigrationClass(string $migrationClass): void; + + /** + * @return class-string[] + */ + abstract public function getImplementedMigrationClasses(): array; +} diff --git a/src/Stores/Connections/DoctrineDbal/Bases/AbstractMigration.php b/src/Stores/Connections/DoctrineDbal/Bases/AbstractMigration.php new file mode 100644 index 0000000000000000000000000000000000000000..f64b7113690f1372ca2ef8ca9ec9ba9d5a4bee20 --- /dev/null +++ b/src/Stores/Connections/DoctrineDbal/Bases/AbstractMigration.php @@ -0,0 +1,19 @@ +<?php + +namespace SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal\Bases; + +use Doctrine\DBAL\Schema\AbstractSchemaManager; +use SimpleSAML\Module\accounting\Stores\Interfaces\MigrationInterface; +use SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal\Connection; + +abstract class AbstractMigration implements MigrationInterface +{ + protected Connection $connection; + protected AbstractSchemaManager $schemaManager; + + public function __construct(Connection $connection) + { + $this->connection = $connection; + $this->schemaManager = $this->connection->dbal()->createSchemaManager(); + } +} diff --git a/src/Stores/Connections/DoctrineDbal/Connection.php b/src/Stores/Connections/DoctrineDbal/Connection.php new file mode 100644 index 0000000000000000000000000000000000000000..69c6202cb4c370a4ff7af039c8d1730a11786491 --- /dev/null +++ b/src/Stores/Connections/DoctrineDbal/Connection.php @@ -0,0 +1,60 @@ +<?php + +declare(strict_types=1); + +namespace SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal; + +use Doctrine\DBAL\DriverManager; +use Doctrine\DBAL\Exception; +use SimpleSAML\Module\accounting\Exceptions\InvalidConfigurationException; +use SimpleSAML\Module\accounting\Stores\Interfaces\ConnectionInterface; + +class Connection implements ConnectionInterface +{ + public const PARAMETER_TABLE_PREFIX = 'table_prefix'; + + protected \Doctrine\DBAL\Connection $dbal; + protected ?string $tablePrefix; + + public function __construct(array $parameters) + { + try { + /** @psalm-suppress MixedArgumentTypeCoercion */ + $this->dbal = DriverManager::getConnection($parameters); + } catch (Exception $e) { + throw new InvalidConfigurationException( + 'Could not initiate Doctrine DBAL connection with given parameters.' + ); + } + + $this->tablePrefix = $this->getTablePrefixFromParameters($parameters); + } + + public function getTablePrefix(): string + { + return $this->tablePrefix ?? ''; + } + + public function dbal(): \Doctrine\DBAL\Connection + { + return $this->dbal; + } + + protected function getTablePrefixFromParameters(array $settings): ?string + { + if (! isset($settings[self::PARAMETER_TABLE_PREFIX])) { + return null; + } + + if (! is_string($settings[self::PARAMETER_TABLE_PREFIX])) { + throw new InvalidConfigurationException('Connection table prefix must be string (if set).'); + } + + return $settings[self::PARAMETER_TABLE_PREFIX]; + } + + public function preparePrefixedTableName(string $tableName): string + { + return $this->getTablePrefix() . $tableName; + } +} diff --git a/src/Stores/Connections/DoctrineDbal/Factory.php b/src/Stores/Connections/DoctrineDbal/Factory.php new file mode 100644 index 0000000000000000000000000000000000000000..6c2af906f32431080113f9235d128c734de93eaf --- /dev/null +++ b/src/Stores/Connections/DoctrineDbal/Factory.php @@ -0,0 +1,28 @@ +<?php + +namespace SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal; + +use SimpleSAML\Module\accounting\ModuleConfiguration; +use SimpleSAML\Module\accounting\Services\LoggerService; + +class Factory +{ + protected ModuleConfiguration $moduleConfiguration; + protected LoggerService $loggerService; + + public function __construct(ModuleConfiguration $moduleConfiguration, LoggerService $loggerService) + { + $this->moduleConfiguration = $moduleConfiguration; + $this->loggerService = $loggerService; + } + + public function buildConnection(string $connectionKey): Connection + { + return new Connection($this->moduleConfiguration->getStoreConnectionParameters($connectionKey)); + } + + public function buildMigrator(Connection $connection, LoggerService $loggerService = null): Migrator + { + return new Migrator($connection, $loggerService ?? $this->loggerService); + } +} diff --git a/src/Stores/Connections/DoctrineDbal/Migrator.php b/src/Stores/Connections/DoctrineDbal/Migrator.php new file mode 100644 index 0000000000000000000000000000000000000000..39861c7d6875690af664c705420acdd2431ff63d --- /dev/null +++ b/src/Stores/Connections/DoctrineDbal/Migrator.php @@ -0,0 +1,122 @@ +<?php + +namespace SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal; + +use Doctrine\DBAL\Schema\AbstractSchemaManager; +use Doctrine\DBAL\Schema\Table; +use Doctrine\DBAL\Types\Types; +use SimpleSAML\Module\accounting\Exceptions\InvalidValueException; +use SimpleSAML\Module\accounting\Services\LoggerService; +use SimpleSAML\Module\accounting\Stores\Connections\Bases\AbstractMigrator; +use SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal\Bases\AbstractMigration; +use SimpleSAML\Module\accounting\Stores\Interfaces\MigrationInterface; + +class Migrator extends AbstractMigrator +{ + public const TABLE_NAME = 'migrations'; + + public const COLUMN_NAME_ID = 'id'; + public const COLUMN_NAME_VERSION = 'version'; + public const COLUMN_NAME_CREATED_AT = 'created_at'; + + protected Connection $connection; + protected LoggerService $loggerService; + + protected AbstractSchemaManager $schemaManager; + protected string $prefixedTableName; + + public function __construct(Connection $connection, LoggerService $loggerService) + { + $this->connection = $connection; + $this->loggerService = $loggerService; + + $this->schemaManager = $this->connection->dbal()->createSchemaManager(); + $this->prefixedTableName = $this->connection->preparePrefixedTableName(self::TABLE_NAME); + } + + public function needsSetup(): bool + { + return ! $this->schemaManager->tablesExist([$this->prefixedTableName]); + } + + public function runSetup(): void + { + if (! $this->needsSetup()) { + $this->loggerService->warning('Migrator setup has been called, however setup is not needed.'); + return; + } + + $this->createMigrationsTable(); + } + + protected function createMigrationsTable(): void + { + $table = new Table($this->prefixedTableName); + + $table->addColumn(self::COLUMN_NAME_ID, Types::BIGINT) + ->setAutoincrement(true) + ->setUnsigned(true); + $table->addColumn(self::COLUMN_NAME_VERSION, Types::STRING); + $table->addColumn(self::COLUMN_NAME_CREATED_AT, Types::DATETIMETZ_IMMUTABLE); + + $table->setPrimaryKey(['id']); + $table->addUniqueIndex([self::COLUMN_NAME_VERSION]); + + $this->schemaManager->createTable($table); + } + + protected function buildMigrationClassInstance(string $migrationClass): MigrationInterface + { + $this->validateDoctrineDbalMigrationClass($migrationClass); + + /** @var MigrationInterface $migration */ + $migration = (new \ReflectionClass($migrationClass))->newInstance($this->connection); + + return $migration; + } + + protected function validateDoctrineDbalMigrationClass(string $migrationClass): void + { + if (! is_subclass_of($migrationClass, AbstractMigration::class)) { + throw new InvalidValueException('Migration class is not Doctrine DBAL migration.'); + } + } + + protected function markImplementedMigrationClass(string $migrationClass): void + { + $queryBuilder = $this->connection->dbal()->createQueryBuilder(); + + $queryBuilder->insert($this->prefixedTableName) + ->values( + [ + self::COLUMN_NAME_VERSION => ':' . self::COLUMN_NAME_VERSION, + self::COLUMN_NAME_CREATED_AT => ':' . self::COLUMN_NAME_CREATED_AT, + ] + ) + ->setParameters( + [ + self::COLUMN_NAME_VERSION => $migrationClass, + self::COLUMN_NAME_CREATED_AT => new \DateTimeImmutable(), + ], + [ + self::COLUMN_NAME_VERSION => Types::STRING, + self::COLUMN_NAME_CREATED_AT => Types::DATETIMETZ_IMMUTABLE + ] + ); + + $queryBuilder->executeStatement(); + } + + public function getImplementedMigrationClasses(): array + { + $queryBuilder = $this->connection->dbal()->createQueryBuilder(); + + $queryBuilder->select(self::COLUMN_NAME_VERSION) + ->from($this->prefixedTableName); + + /** @var class-string[] $migrationClasses */ + $migrationClasses = $queryBuilder->executeQuery()->fetchFirstColumn(); + + return $migrationClasses; + } +} diff --git a/src/Stores/Interfaces/ConnectionInterface.php b/src/Stores/Interfaces/ConnectionInterface.php new file mode 100644 index 0000000000000000000000000000000000000000..359c817b5dfd45cfab9ada2daeddc0cc0801bc61 --- /dev/null +++ b/src/Stores/Interfaces/ConnectionInterface.php @@ -0,0 +1,7 @@ +<?php + +namespace SimpleSAML\Module\accounting\Stores\Interfaces; + +interface ConnectionInterface +{ +} diff --git a/src/Stores/Interfaces/DataStoreInterface.php b/src/Stores/Interfaces/DataStoreInterface.php new file mode 100644 index 0000000000000000000000000000000000000000..b091acf1197ead3a12f744764e8a984b9f31f911 --- /dev/null +++ b/src/Stores/Interfaces/DataStoreInterface.php @@ -0,0 +1,7 @@ +<?php + +namespace SimpleSAML\Module\accounting\Stores\Interfaces; + +interface DataStoreInterface extends StoreInterface +{ +} diff --git a/src/Stores/Interfaces/JobsStoreInterface.php b/src/Stores/Interfaces/JobsStoreInterface.php new file mode 100644 index 0000000000000000000000000000000000000000..3dd0b57bf05c7bc0aec7c69250f25564af415ec0 --- /dev/null +++ b/src/Stores/Interfaces/JobsStoreInterface.php @@ -0,0 +1,7 @@ +<?php + +namespace SimpleSAML\Module\accounting\Stores\Interfaces; + +interface JobsStoreInterface extends StoreInterface +{ +} diff --git a/src/Stores/Interfaces/MigrationInterface.php b/src/Stores/Interfaces/MigrationInterface.php new file mode 100644 index 0000000000000000000000000000000000000000..ea52b88a626c4d4c69a2372e0e7158b87d989af9 --- /dev/null +++ b/src/Stores/Interfaces/MigrationInterface.php @@ -0,0 +1,20 @@ +<?php + +namespace SimpleSAML\Module\accounting\Stores\Interfaces; + +interface MigrationInterface +{ + /** + * Run migration forward. + * + * @return void + */ + public function run(): void; + + /** + * Run migration backward. + * + * @return void + */ + public function revert(): void; +} diff --git a/src/Stores/Interfaces/StoreInterface.php b/src/Stores/Interfaces/StoreInterface.php new file mode 100644 index 0000000000000000000000000000000000000000..082ee53080fce20782c10fd04a26243b1080f292 --- /dev/null +++ b/src/Stores/Interfaces/StoreInterface.php @@ -0,0 +1,8 @@ +<?php + +namespace SimpleSAML\Module\accounting\Stores\Interfaces; + +interface StoreInterface +{ + public function needsSetUp(): bool; +} diff --git a/src/Stores/Jobs/DoctrineDbal/JobsStore.php b/src/Stores/Jobs/DoctrineDbal/JobsStore.php new file mode 100644 index 0000000000000000000000000000000000000000..25590c8883b91bb05c460a5164277bb562ea951d --- /dev/null +++ b/src/Stores/Jobs/DoctrineDbal/JobsStore.php @@ -0,0 +1,49 @@ +<?php + +declare(strict_types=1); + +namespace SimpleSAML\Module\accounting\Stores\Jobs\DoctrineDbal; + +use SimpleSAML\Module\accounting\ModuleConfiguration; +use SimpleSAML\Module\accounting\Stores\Jobs\Interfaces\JobsStoreInterface; +use SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal\Connection; +use SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal\Factory; +use SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal\Migrator; + +class JobsStore implements JobsStoreInterface +{ + public const TABLE_NAME_JOBS = 'jobs'; + public const TABLE_NAME_FAILED_JOBS = 'failed_jobs'; + + protected ModuleConfiguration $moduleConfiguration; + protected Connection $connection; + protected string $prefixedTableNameJobs; + protected string $prefixedTableNameFailedJobs; + protected Migrator $migrator; + + public function __construct(ModuleConfiguration $moduleConfiguration, Factory $factory) + { + $this->moduleConfiguration = $moduleConfiguration; + $this->connection = $factory->buildConnection($moduleConfiguration->getStoreConnection(self::class)); + $this->migrator = $factory->buildMigrator($this->connection); + + $this->prefixedTableNameJobs = $this->connection->preparePrefixedTableName(self::TABLE_NAME_JOBS); + $this->prefixedTableNameFailedJobs = $this->connection->preparePrefixedTableName(self::TABLE_NAME_FAILED_JOBS); + } + + public function needsSetUp(): bool + { + // TODO mivanci dovrši + return true; + } + + public function getPrefixedTableNameJobs(): string + { + return $this->prefixedTableNameJobs; + } + + public function getPrefixedTableNameFailedJobs(): string + { + return $this->prefixedTableNameFailedJobs; + } +} diff --git a/src/Stores/Jobs/DoctrineDbal/JobsStore/Migrations/Version20220601000000CreateJobsTable.php b/src/Stores/Jobs/DoctrineDbal/JobsStore/Migrations/Version20220601000000CreateJobsTable.php new file mode 100644 index 0000000000000000000000000000000000000000..b0e7581ee8212e5717f74b09b337bfadc9f3e060 --- /dev/null +++ b/src/Stores/Jobs/DoctrineDbal/JobsStore/Migrations/Version20220601000000CreateJobsTable.php @@ -0,0 +1,37 @@ +<?php + +namespace SimpleSAML\Module\accounting\Stores\Jobs\DoctrineDbal\JobsStore\Migrations; + +use Doctrine\DBAL\Schema\Table; +use Doctrine\DBAL\Types\Types; +use SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal\Bases\AbstractMigration; +use SimpleSAML\Module\accounting\Stores\Jobs\DoctrineDbal\JobsStore; + +class Version20220601000000CreateJobsTable extends AbstractMigration +{ + public function run(): void + { + $tableName = $this->connection->preparePrefixedTableName(JobsStore::TABLE_NAME_JOBS); + $table = new Table($tableName); + + $table->addColumn('id', Types::BIGINT) + ->setUnsigned(true) + ->setAutoincrement(true); + + $table->addColumn('payload', Types::TEXT); + $table->addColumn('created_at', Types::DATETIMETZ_IMMUTABLE); + $table->addColumn('reserved_at', Types::DATETIMETZ_IMMUTABLE)->setNotnull(false); + $table->addColumn('attempts', Types::INTEGER)->setNotnull(false); + + $table->setPrimaryKey(['id']); + + $this->schemaManager->createTable($table); + } + + public function revert(): void + { + $tableName = $this->connection->preparePrefixedTableName(JobsStore::TABLE_NAME_JOBS); + + $this->schemaManager->dropTable($tableName); + } +} diff --git a/src/Stores/Jobs/DoctrineDbal/JobsStore/Migrations/Version20220601000100CreateFailedJobsTable.php b/src/Stores/Jobs/DoctrineDbal/JobsStore/Migrations/Version20220601000100CreateFailedJobsTable.php new file mode 100644 index 0000000000000000000000000000000000000000..e965025d763da8eda7fbc875b8bf7f9403080844 --- /dev/null +++ b/src/Stores/Jobs/DoctrineDbal/JobsStore/Migrations/Version20220601000100CreateFailedJobsTable.php @@ -0,0 +1,35 @@ +<?php + +namespace SimpleSAML\Module\accounting\Stores\Jobs\DoctrineDbal\JobsStore\Migrations; + +use Doctrine\DBAL\Schema\Table; +use Doctrine\DBAL\Types\Types; +use SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal\Bases\AbstractMigration; +use SimpleSAML\Module\accounting\Stores\Jobs\DoctrineDbal\JobsStore; + +class Version20220601000100CreateFailedJobsTable extends AbstractMigration +{ + public function run(): void + { + $tableName = $this->connection->preparePrefixedTableName(JobsStore::TABLE_NAME_FAILED_JOBS); + $table = new Table($tableName); + + $table->addColumn('id', Types::BIGINT) + ->setUnsigned(true) + ->setAutoincrement(true); + + $table->addColumn('payload', Types::TEXT); + $table->addColumn('created_at', Types::DATETIMETZ_IMMUTABLE); + + $table->setPrimaryKey(['id']); + + $this->schemaManager->createTable($table); + } + + public function revert(): void + { + $tableName = $this->connection->preparePrefixedTableName(JobsStore::TABLE_NAME_FAILED_JOBS); + + $this->schemaManager->dropTable($tableName); + } +} diff --git a/src/Stores/Jobs/Interfaces/JobsStoreInterface.php b/src/Stores/Jobs/Interfaces/JobsStoreInterface.php new file mode 100644 index 0000000000000000000000000000000000000000..d7ef16b1d6a60b99087a02f5d0e208d2d6e39e05 --- /dev/null +++ b/src/Stores/Jobs/Interfaces/JobsStoreInterface.php @@ -0,0 +1,7 @@ +<?php + +namespace SimpleSAML\Module\accounting\Stores\Jobs\Interfaces; + +interface JobsStoreInterface +{ +} diff --git a/src/Stores/Jobs/Interfaces/JobsStoreMigrationInterface.php b/src/Stores/Jobs/Interfaces/JobsStoreMigrationInterface.php new file mode 100644 index 0000000000000000000000000000000000000000..9a935152ec7dcb368c10afbc01c092d46abb17c0 --- /dev/null +++ b/src/Stores/Jobs/Interfaces/JobsStoreMigrationInterface.php @@ -0,0 +1,12 @@ +<?php + +namespace SimpleSAML\Module\accounting\Stores\Jobs\Interfaces; + +interface JobsStoreMigrationInterface +{ + /** + * Run this jobs store migration. + * @return void + */ + public function run(): void; +} diff --git a/tests/config-templates/config.php b/tests/config-templates/config.php new file mode 100644 index 0000000000000000000000000000000000000000..c27decf2ca22267f2a3549033d38d2019bb7055f --- /dev/null +++ b/tests/config-templates/config.php @@ -0,0 +1,1161 @@ +<?php + +/** + * The configuration of SimpleSAMLphp + */ + +$httpUtils = new \SimpleSAML\Utils\HTTP(); + +$config = [ + + /******************************* + | BASIC CONFIGURATION OPTIONS | + *******************************/ + + /* + * Setup the following parameters to match your installation. + * See the user manual for more details. + */ + + /* + * baseurlpath is a *URL path* (not a filesystem path). + * A valid format for 'baseurlpath' is: + * [(http|https)://(hostname|fqdn)[:port]]/[path/to/simplesaml/] + * + * The full url format is useful if your SimpleSAMLphp setup is hosted behind + * a reverse proxy. In that case you can specify the external url here. + * + * Please note that SimpleSAMLphp will then redirect all queries to the + * external url, no matter where you come from (direct access or via the + * reverse proxy). + */ + 'baseurlpath' => 'simplesaml/', + + /* + * The 'application' configuration array groups a set configuration options + * relative to an application protected by SimpleSAMLphp. + */ + //'application' => [ + /* + * The 'baseURL' configuration option allows you to specify a protocol, + * host and optionally a port that serves as the canonical base for all + * your application's URLs. This is useful when the environment + * observed in the server differs from the one observed by end users, + * for example, when using a load balancer to offload TLS. + * + * Note that this configuration option does not allow setting a path as + * part of the URL. If your setup involves URL rewriting or any other + * tricks that would result in SimpleSAMLphp observing a URL for your + * application's scripts different than the canonical one, you will + * need to compute the right URLs yourself and pass them dynamically + * to SimpleSAMLphp's API. + */ + //'baseURL' => 'https://example.com', + //], + + /* + * The following settings are *filesystem paths* which define where + * SimpleSAMLphp can find or write the following things: + * - 'certdir': The base directory for certificate and key material. + * - 'loggingdir': Where to write logs. + * - 'datadir': Storage of general data. + * - 'tempdir': Saving temporary files. SimpleSAMLphp will attempt to create + * this directory if it doesn't exist. + * When specified as a relative path, this is relative to the SimpleSAMLphp + * root directory. + */ + 'certdir' => 'cert/', + 'loggingdir' => 'log/', + 'datadir' => 'data/', + 'tempdir' => '/tmp/simplesaml', + + /* + * Some information about the technical persons running this installation. + * The email address will be used as the recipient address for error reports, and + * also as the technical contact in generated metadata. + */ + 'technicalcontact_name' => 'Administrator', + 'technicalcontact_email' => 'na@example.org', + + /* + * (Optional) The method by which email is delivered. Defaults to mail which utilizes the + * PHP mail() function. + * + * Valid options are: mail, sendmail and smtp. + */ + //'mail.transport.method' => 'smtp', + + /* + * Set the transport options for the transport method specified. The valid settings are relative to the + * selected transport method. + */ + // // smtp mail transport options + // 'mail.transport.options' => [ + // 'host' => 'mail.example.org', // required + // 'port' => 25, // optional + // 'username' => 'user@example.org', // optional: if set, enables smtp authentication + // 'password' => 'password', // optional: if set, enables smtp authentication + // 'security' => 'tls', // optional: defaults to no smtp security + // 'smtpOptions' => [], // optional: passed to stream_context_create when connecting via SMTP + // ], + // // sendmail mail transport options + // 'mail.transport.options' => [ + // 'path' => '/usr/sbin/sendmail' // optional: defaults to php.ini path + // ], + + /* + * The envelope from address for outgoing emails. + * This should be in a domain that has your application's IP addresses in its SPF record + * to prevent it from being rejected by mail filters. + */ + //'sendmail_from' => 'no-reply@example.org', + + /* + * The timezone of the server. This option should be set to the timezone you want + * SimpleSAMLphp to report the time in. The default is to guess the timezone based + * on your system timezone. + * + * See this page for a list of valid timezones: http://php.net/manual/en/timezones.php + */ + 'timezone' => null, + + + + /********************************** + | SECURITY CONFIGURATION OPTIONS | + **********************************/ + + /* + * This is a secret salt used by SimpleSAMLphp when it needs to generate a secure hash + * of a value. It must be changed from its default value to a secret value. The value of + * 'secretsalt' can be any valid string of any length. + * + * A possible way to generate a random salt is by running the following command from a unix shell: + * LC_ALL=C tr -c -d '0123456789abcdefghijklmnopqrstuvwxyz' </dev/urandom | dd bs=32 count=1 2>/dev/null;echo + */ + 'secretsalt' => 'defaultsecretsalt', + + /* + * This password must be kept secret, and modified from the default value 123. + * This password will give access to the installation page of SimpleSAMLphp with + * metadata listing and diagnostics pages. + * You can also put a hash here; run "bin/pwgen.php" to generate one. + */ + 'auth.adminpassword' => '123', + + /* + * Set this option to true if you want to require administrator password to access the metadata. + */ + 'admin.protectmetadata' => false, + + /* + * Set this option to false if you don't want SimpleSAMLphp to check for new stable releases when + * visiting the configuration tab in the web interface. + */ + 'admin.checkforupdates' => true, + + /* + * Array of domains that are allowed when generating links or redirects + * to URLs. SimpleSAMLphp will use this option to determine whether to + * to consider a given URL valid or not, but you should always validate + * URLs obtained from the input on your own (i.e. ReturnTo or RelayState + * parameters obtained from the $_REQUEST array). + * + * SimpleSAMLphp will automatically add your own domain (either by checking + * it dynamically, or by using the domain defined in the 'baseurlpath' + * directive, the latter having precedence) to the list of trusted domains, + * in case this option is NOT set to NULL. In that case, you are explicitly + * telling SimpleSAMLphp to verify URLs. + * + * Set to an empty array to disallow ALL redirects or links pointing to + * an external URL other than your own domain. This is the default behaviour. + * + * Set to NULL to disable checking of URLs. DO NOT DO THIS UNLESS YOU KNOW + * WHAT YOU ARE DOING! + * + * Example: + * 'trusted.url.domains' => ['sp.example.com', 'app.example.com'], + */ + 'trusted.url.domains' => [], + + /* + * Enable regular expression matching of trusted.url.domains. + * + * Set to true to treat the values in trusted.url.domains as regular + * expressions. Set to false to do exact string matching. + * + * If enabled, the start and end delimiters ('^' and '$') will be added to + * all regular expressions in trusted.url.domains. + */ + 'trusted.url.regex' => false, + + /* + * Enable secure POST from HTTPS to HTTP. + * + * If you have some SP's on HTTP and IdP is normally on HTTPS, this option + * enables secure POSTing to HTTP endpoint without warning from browser. + * + * For this to work, module.php/core/postredirect.php must be accessible + * also via HTTP on IdP, e.g. if your IdP is on + * https://idp.example.org/ssp/, then + * http://idp.example.org/ssp/module.php/core/postredirect.php must be accessible. + */ + 'enable.http_post' => false, + + /* + * Set the allowed clock skew between encrypting/decrypting assertions + * + * If you have an server that is constantly out of sync, this option + * allows you to adjust the allowed clock-skew. + * + * Allowed range: 180 - 300 + * Defaults to 180. + */ + 'assertion.allowed_clock_skew' => 180, + + + /************************ + | ERRORS AND DEBUGGING | + ************************/ + + /* + * The 'debug' option allows you to control how SimpleSAMLphp behaves in certain + * situations where further action may be taken + * + * It can be left unset, in which case, debugging is switched off for all actions. + * If set, it MUST be an array containing the actions that you want to enable, or + * alternatively a hashed array where the keys are the actions and their + * corresponding values are booleans enabling or disabling each particular action. + * + * SimpleSAMLphp provides some pre-defined actions, though modules could add new + * actions here. Refer to the documentation of every module to learn if they + * allow you to set any more debugging actions. + * + * The pre-defined actions are: + * + * - 'saml': this action controls the logging of SAML messages exchanged with other + * entities. When enabled ('saml' is present in this option, or set to true), all + * SAML messages will be logged, including plaintext versions of encrypted + * messages. + * + * - 'backtraces': this action controls the logging of error backtraces so you + * can debug any possible errors happening in SimpleSAMLphp. + * + * - 'validatexml': this action allows you to validate SAML documents against all + * the relevant XML schemas. SAML 1.1 messages or SAML metadata parsed with + * the XML to SimpleSAMLphp metadata converter or the metaedit module will + * validate the SAML documents if this option is enabled. + * + * If you want to disable debugging completely, unset this option or set it to an + * empty array. + */ + 'debug' => [ + 'saml' => false, + 'backtraces' => true, + 'validatexml' => false, + ], + + /* + * When 'showerrors' is enabled, all error messages and stack traces will be output + * to the browser. + * + * When 'errorreporting' is enabled, a form will be presented for the user to report + * the error to 'technicalcontact_email'. + */ + 'showerrors' => true, + 'errorreporting' => true, + + /* + * Custom error show function called from SimpleSAML\Error\Error::show. + * See docs/simplesamlphp-errorhandling.txt for function code example. + * + * Example: + * 'errors.show_function' => ['SimpleSAML\Module\example\Error', 'show'], + */ + + + + /************************** + | LOGGING AND STATISTICS | + **************************/ + + /* + * Define the minimum log level to log. Available levels: + * - SimpleSAML\Logger::ERR No statistics, only errors + * - SimpleSAML\Logger::WARNING No statistics, only warnings/errors + * - SimpleSAML\Logger::NOTICE Statistics and errors + * - SimpleSAML\Logger::INFO Verbose logs + * - SimpleSAML\Logger::DEBUG Full debug logs - not recommended for production + * + * Choose logging handler. + * + * Options: [syslog,file,errorlog,stderr] + * + */ + 'logging.level' => SimpleSAML\Logger::NOTICE, + 'logging.handler' => 'syslog', + + /* + * Specify the format of the logs. Its use varies depending on the log handler used (for instance, you cannot + * control here how dates are displayed when using the syslog or errorlog handlers), but in general the options + * are: + * + * - %date{<format>}: the date and time, with its format specified inside the brackets. See the PHP documentation + * of the date() function for more information on the format. If the brackets are omitted, the standard + * format is applied. This can be useful if you just want to control the placement of the date, but don't care + * about the format. + * + * - %process: the name of the SimpleSAMLphp process. Remember you can configure this in the 'logging.processname' + * option below. + * + * - %level: the log level (name or number depending on the handler used). + * + * - %stat: if the log entry is intended for statistical purposes, it will print the string 'STAT ' (bear in mind + * the trailing space). + * + * - %trackid: the track ID, an identifier that allows you to track a single session. + * + * - %srcip: the IP address of the client. If you are behind a proxy, make sure to modify the + * $_SERVER['REMOTE_ADDR'] variable on your code accordingly to the X-Forwarded-For header. + * + * - %msg: the message to be logged. + * + */ + //'logging.format' => '%date{M j H:i:s} %process %level %stat[%trackid] %msg', + + /* + * Choose which facility should be used when logging with syslog. + * + * These can be used for filtering the syslog output from SimpleSAMLphp into its + * own file by configuring the syslog daemon. + * + * See the documentation for openlog (http://php.net/manual/en/function.openlog.php) for available + * facilities. Note that only LOG_USER is valid on windows. + * + * The default is to use LOG_LOCAL5 if available, and fall back to LOG_USER if not. + */ + 'logging.facility' => defined('LOG_LOCAL5') ? constant('LOG_LOCAL5') : LOG_USER, + + /* + * The process name that should be used when logging to syslog. + * The value is also written out by the other logging handlers. + */ + 'logging.processname' => 'simplesamlphp', + + /* + * Logging: file - Logfilename in the loggingdir from above. + */ + 'logging.logfile' => 'simplesamlphp.log', + + /* + * This is an array of outputs. Each output has at least a 'class' option, which + * selects the output. + */ + 'statistics.out' => [// Log statistics to the normal log. + /* + [ + 'class' => 'core:Log', + 'level' => 'notice', + ], + */ + // Log statistics to files in a directory. One file per day. + /* + [ + 'class' => 'core:File', + 'directory' => '/var/log/stats', + ], + */ + ], + + + + /*********************** + | PROXY CONFIGURATION | + ***********************/ + + /* + * Proxy to use for retrieving URLs. + * + * Example: + * 'proxy' => 'tcp://proxy.example.com:5100' + */ + 'proxy' => null, + + /* + * Username/password authentication to proxy (Proxy-Authorization: Basic) + * Example: + * 'proxy.auth' = 'myuser:password' + */ + //'proxy.auth' => 'myuser:password', + + + + /************************** + | DATABASE CONFIGURATION | + **************************/ + + /* + * This database configuration is optional. If you are not using + * core functionality or modules that require a database, you can + * skip this configuration. + */ + + /* + * Database connection string. + * Ensure that you have the required PDO database driver installed + * for your connection string. + */ + 'database.dsn' => 'mysql:host=localhost;dbname=saml', + + /* + * SQL database credentials + */ + 'database.username' => 'simplesamlphp', + 'database.password' => 'secret', + 'database.options' => [], + + /* + * (Optional) Table prefix + */ + 'database.prefix' => '', + + /* + * (Optional) Driver options + */ + 'database.driver_options' => [], + + /* + * True or false if you would like a persistent database connection + */ + 'database.persistent' => false, + + /* + * Database secondary configuration is optional as well. If you are only + * running a single database server, leave this blank. If you have + * a primary/secondary configuration, you can define as many secondary servers + * as you want here. Secondaries will be picked at random to be queried from. + * + * Configuration options in the secondary array are exactly the same as the + * options for the primary (shown above) with the exception of the table + * prefix and driver options. + */ + 'database.secondaries' => [ + /* + [ + 'dsn' => 'mysql:host=mysecondary;dbname=saml', + 'username' => 'simplesamlphp', + 'password' => 'secret', + 'persistent' => false, + ], + */ + ], + + + + /************* + | PROTOCOLS | + *************/ + + /* + * Which functionality in SimpleSAMLphp do you want to enable. Normally you would enable only + * one of the functionalities below, but in some cases you could run multiple functionalities. + * In example when you are setting up a federation bridge. + */ + 'enable.saml20-idp' => false, + 'enable.adfs-idp' => false, + + + + /*********** + | MODULES | + ***********/ + + /* + * Configuration for enabling/disabling modules. By default the 'core', 'admin' and 'saml' modules are enabled. + * + * Example: + * + * 'module.enable' => [ + * 'exampleauth' => true, // Setting to TRUE enables. + * 'consent' => false, // Setting to FALSE disables. + * 'core' => null, // Unset or NULL uses default. + * ], + */ + + 'module.enable' => [ + 'exampleauth' => false, + 'core' => true, + 'admin' => true, + 'saml' => true + ], + + + /************************* + | SESSION CONFIGURATION | + *************************/ + + /* + * This value is the duration of the session in seconds. Make sure that the time duration of + * cookies both at the SP and the IdP exceeds this duration. + */ + 'session.duration' => 8 * (60 * 60), // 8 hours. + + /* + * Sets the duration, in seconds, data should be stored in the datastore. As the data store is used for + * login and logout requests, this option will control the maximum time these operations can take. + * The default is 4 hours (4*60*60) seconds, which should be more than enough for these operations. + */ + 'session.datastore.timeout' => (4 * 60 * 60), // 4 hours + + /* + * Sets the duration, in seconds, auth state should be stored. + */ + 'session.state.timeout' => (60 * 60), // 1 hour + + /* + * Option to override the default settings for the session cookie name + */ + 'session.cookie.name' => 'SimpleSAMLSessionID', + + /* + * Expiration time for the session cookie, in seconds. + * + * Defaults to 0, which means that the cookie expires when the browser is closed. + * + * Example: + * 'session.cookie.lifetime' => 30*60, + */ + 'session.cookie.lifetime' => 0, + + /* + * Limit the path of the cookies. + * + * Can be used to limit the path of the cookies to a specific subdirectory. + * + * Example: + * 'session.cookie.path' => '/simplesaml/', + */ + 'session.cookie.path' => '/', + + /* + * Cookie domain. + * + * Can be used to make the session cookie available to several domains. + * + * Example: + * 'session.cookie.domain' => '.example.org', + */ + 'session.cookie.domain' => '', + + /* + * Set the secure flag in the cookie. + * + * Set this to TRUE if the user only accesses your service + * through https. If the user can access the service through + * both http and https, this must be set to FALSE. + */ + 'session.cookie.secure' => true, + + /* + * Set the SameSite attribute in the cookie. + * + * You can set this to the strings 'None', 'Lax', or 'Strict' to support + * the RFC6265bis SameSite cookie attribute. If set to null, no SameSite + * attribute will be sent. + * + * A value of "None" is required to properly support cross-domain POST + * requests which are used by different SAML bindings. Because some older + * browsers do not support this value, the canSetSameSiteNone function + * can be called to only set it for compatible browsers. + * + * You must also set the 'session.cookie.secure' value above to true. + * + * Example: + * 'session.cookie.samesite' => 'None', + */ + 'session.cookie.samesite' => $httpUtils->canSetSameSiteNone() ? 'None' : null, + + /* + * Options to override the default settings for php sessions. + */ + 'session.phpsession.cookiename' => 'SimpleSAML', + 'session.phpsession.savepath' => null, + 'session.phpsession.httponly' => true, + + /* + * Option to override the default settings for the auth token cookie + */ + 'session.authtoken.cookiename' => 'SimpleSAMLAuthToken', + + /* + * Options for remember me feature for IdP sessions. Remember me feature + * has to be also implemented in authentication source used. + * + * Option 'session.cookie.lifetime' should be set to zero (0), i.e. cookie + * expires on browser session if remember me is not checked. + * + * Session duration ('session.duration' option) should be set according to + * 'session.rememberme.lifetime' option. + * + * It's advised to use remember me feature with session checking function + * defined with 'session.check_function' option. + */ + 'session.rememberme.enable' => false, + 'session.rememberme.checked' => false, + 'session.rememberme.lifetime' => (14 * 86400), + + /* + * Custom function for session checking called on session init and loading. + * See docs/simplesamlphp-advancedfeatures.txt for function code example. + * + * Example: + * 'session.check_function' => ['\SimpleSAML\Module\example\Util', 'checkSession'], + */ + + + + /************************** + | MEMCACHE CONFIGURATION | + **************************/ + + /* + * Configuration for the 'memcache' session store. This allows you to store + * multiple redundant copies of sessions on different memcache servers. + * + * 'memcache_store.servers' is an array of server groups. Every data + * item will be mirrored in every server group. + * + * Each server group is an array of servers. The data items will be + * load-balanced between all servers in each server group. + * + * Each server is an array of parameters for the server. The following + * options are available: + * - 'hostname': This is the hostname or ip address where the + * memcache server runs. This is the only required option. + * - 'port': This is the port number of the memcache server. If this + * option isn't set, then we will use the 'memcache.default_port' + * ini setting. This is 11211 by default. + * + * When using the "memcache" extension, the following options are also + * supported: + * - 'weight': This sets the weight of this server in this server + * group. http://php.net/manual/en/function.Memcache-addServer.php + * contains more information about the weight option. + * - 'timeout': The timeout for this server. By default, the timeout + * is 3 seconds. + * + * Example of redundant configuration with load balancing: + * This configuration makes it possible to lose both servers in the + * a-group or both servers in the b-group without losing any sessions. + * Note that sessions will be lost if one server is lost from both the + * a-group and the b-group. + * + * 'memcache_store.servers' => [ + * [ + * ['hostname' => 'mc_a1'], + * ['hostname' => 'mc_a2'], + * ], + * [ + * ['hostname' => 'mc_b1'], + * ['hostname' => 'mc_b2'], + * ], + * ], + * + * Example of simple configuration with only one memcache server, + * running on the same computer as the web server: + * Note that all sessions will be lost if the memcache server crashes. + * + * 'memcache_store.servers' => [ + * [ + * ['hostname' => 'localhost'], + * ], + * ], + * + * Additionally, when using the "memcached" extension, unique keys must + * be provided for each group of servers if persistent connections are + * desired. Each server group can also have an "options" indexed array + * with the options desired for the given group: + * + * 'memcache_store.servers' => [ + * 'memcache_group_1' => [ + * 'options' => [ + * \Memcached::OPT_BINARY_PROTOCOL => true, + * \Memcached::OPT_NO_BLOCK => true, + * \Memcached::OPT_TCP_NODELAY => true, + * \Memcached::OPT_LIBKETAMA_COMPATIBLE => true, + * ], + * ['hostname' => '127.0.0.1', 'port' => 11211], + * ['hostname' => '127.0.0.2', 'port' => 11211], + * ], + * + * 'memcache_group_2' => [ + * 'options' => [ + * \Memcached::OPT_BINARY_PROTOCOL => true, + * \Memcached::OPT_NO_BLOCK => true, + * \Memcached::OPT_TCP_NODELAY => true, + * \Memcached::OPT_LIBKETAMA_COMPATIBLE => true, + * ], + * ['hostname' => '127.0.0.3', 'port' => 11211], + * ['hostname' => '127.0.0.4', 'port' => 11211], + * ], + * ], + * + */ + 'memcache_store.servers' => [ + [ + ['hostname' => 'localhost'], + ], + ], + + /* + * This value allows you to set a prefix for memcache-keys. The default + * for this value is 'simpleSAMLphp', which is fine in most cases. + * + * When running multiple instances of SSP on the same host, and more + * than one instance is using memcache, you probably want to assign + * a unique value per instance to this setting to avoid data collision. + */ + 'memcache_store.prefix' => '', + + /* + * This value is the duration data should be stored in memcache. Data + * will be dropped from the memcache servers when this time expires. + * The time will be reset every time the data is written to the + * memcache servers. + * + * This value should always be larger than the 'session.duration' + * option. Not doing this may result in the session being deleted from + * the memcache servers while it is still in use. + * + * Set this value to 0 if you don't want data to expire. + * + * Note: The oldest data will always be deleted if the memcache server + * runs out of storage space. + */ + 'memcache_store.expires' => 36 * (60 * 60), // 36 hours. + + + + /************************************* + | LANGUAGE AND INTERNATIONALIZATION | + *************************************/ + + /* + * Languages available, RTL languages, and what language is the default. + */ + 'language.available' => [ + 'en', 'no', 'nn', 'se', 'da', 'de', 'sv', 'fi', 'es', 'ca', 'fr', 'it', 'nl', 'lb', + 'cs', 'sl', 'lt', 'hr', 'hu', 'pl', 'pt', 'pt-br', 'tr', 'ja', 'zh', 'zh-tw', 'ru', + 'et', 'he', 'id', 'sr', 'lv', 'ro', 'eu', 'el', 'af', 'zu', 'xh', 'st', + ], + 'language.rtl' => ['ar', 'dv', 'fa', 'ur', 'he'], + 'language.default' => 'en', + + /* + * Options to override the default settings for the language parameter + */ + 'language.parameter.name' => 'language', + 'language.parameter.setcookie' => true, + + /* + * Options to override the default settings for the language cookie + */ + 'language.cookie.name' => 'language', + 'language.cookie.domain' => '', + 'language.cookie.path' => '/', + 'language.cookie.secure' => true, + 'language.cookie.httponly' => false, + 'language.cookie.lifetime' => (60 * 60 * 24 * 900), + 'language.cookie.samesite' => $httpUtils->canSetSameSiteNone() ? 'None' : null, + + /** + * Custom getLanguage function called from SimpleSAML\Locale\Language::getLanguage(). + * Function should return language code of one of the available languages or NULL. + * See SimpleSAML\Locale\Language::getLanguage() source code for more info. + * + * This option can be used to implement a custom function for determining + * the default language for the user. + * + * Example: + * 'language.get_language_function' => ['\SimpleSAML\Module\example\Template', 'getLanguage'], + */ + + /************** + | APPEARANCE | + **************/ + + /* + * Which theme directory should be used? + */ + 'theme.use' => 'default', + + /* + * Set this option to the text you would like to appear at the header of each page. Set to false if you don't want + * any text to appear in the header. + */ + //'theme.header' => 'SimpleSAMLphp' + + /** + * A template controller, if any. + * + * Used to intercept certain parts of the template handling, while keeping away unwanted/unexpected hooks. Set + * the 'theme.controller' configuration option to a class that implements the + * \SimpleSAML\XHTML\TemplateControllerInterface interface to use it. + */ + //'theme.controller' => '', + + /* + * Templating options + * + * By default, twig templates are not cached. To turn on template caching: + * Set 'template.cache' to an absolute path pointing to a directory that + * SimpleSAMLphp has read and write permissions to. + */ + //'template.cache' => '', + + /* + * Set the 'template.auto_reload' to true if you would like SimpleSAMLphp to + * recompile the templates (when using the template cache) if the templates + * change. If you don't want to check the source templates for every request, + * set it to false. + */ + 'template.auto_reload' => false, + + /* + * Set this option to true to indicate that your installation of SimpleSAMLphp + * is running in a production environment. This will affect the way resources + * are used, offering an optimized version when running in production, and an + * easy-to-debug one when not. Set it to false when you are testing or + * developing the software, in which case a banner will be displayed to remind + * users that they're dealing with a non-production instance. + * + * Defaults to true. + */ + 'production' => true, + + /* + * SimpleSAMLphp modules can host static resources which are served through PHP. + * The serving of the resources can be configured through these settings. + */ + 'assets' => [ + /* + * These settings adjust the caching headers that are sent + * when serving static resources. + */ + 'caching' => [ + /* + * Amount of seconds before the resource should be fetched again + */ + 'max_age' => 86400, + /* + * Calculate a checksum of every file and send it to the browser + * This allows the browser to avoid downloading assets again in situations + * where the Last-Modified header cannot be trusted, + * for example in cluster setups + * + * Defaults false + */ + 'etag' => false, + ], + ], + + /** + * Set to a full URL if you want to redirect users that land on SimpleSAMLphp's + * front page to somewhere more useful. If left unset, a basic welcome message + * is shown. + */ + //'frontpage.redirect' => 'https://example.com/', + + /********************* + | DISCOVERY SERVICE | + *********************/ + + /* + * Whether the discovery service should allow the user to save his choice of IdP. + */ + 'idpdisco.enableremember' => true, + 'idpdisco.rememberchecked' => true, + + /* + * The disco service only accepts entities it knows. + */ + 'idpdisco.validate' => true, + + 'idpdisco.extDiscoveryStorage' => null, + + /* + * IdP Discovery service look configuration. + * Wether to display a list of idp or to display a dropdown box. For many IdP' a dropdown box + * gives the best use experience. + * + * When using dropdown box a cookie is used to highlight the previously chosen IdP in the dropdown. + * This makes it easier for the user to choose the IdP + * + * Options: [links,dropdown] + */ + 'idpdisco.layout' => 'dropdown', + + + + /************************************* + | AUTHENTICATION PROCESSING FILTERS | + *************************************/ + + /* + * Authentication processing filters that will be executed for all IdPs + */ + 'authproc.idp' => [ + /* Enable the authproc filter below to add URN prefixes to all attributes + 10 => array[ + 'class' => 'core:AttributeMap', 'addurnprefix' + ], + */ + /* Enable the authproc filter below to automatically generated eduPersonTargetedID. + 20 => 'core:TargetedID', + */ + + // Adopts language from attribute to use in UI + 30 => 'core:LanguageAdaptor', + + 45 => [ + 'class' => 'core:StatisticsWithAttribute', + 'attributename' => 'realm', + 'type' => 'saml20-idp-SSO', + ], + + /* When called without parameters, it will fallback to filter attributes 'the old way' + * by checking the 'attributes' parameter in metadata on IdP hosted and SP remote. + */ + 50 => 'core:AttributeLimit', + + /* + * Search attribute "distinguishedName" for pattern and replaces if found + */ + /* + 60 => [ + 'class' => 'core:AttributeAlter', + 'pattern' => '/OU=studerende/', + 'replacement' => 'Student', + 'subject' => 'distinguishedName', + '%replace', + ], + */ + + /* + * Consent module is enabled (with no permanent storage, using cookies). + */ + /* + 90 => [ + 'class' => 'consent:Consent', + 'store' => 'consent:Cookie', + 'focus' => 'yes', + 'checked' => true + ], + */ + // If language is set in Consent module it will be added as an attribute. + 99 => 'core:LanguageAdaptor', + ], + + /* + * Authentication processing filters that will be executed for all SPs + */ + 'authproc.sp' => [ + /* + 10 => [ + 'class' => 'core:AttributeMap', 'removeurnprefix' + ], + */ + + /* + * Generate the 'group' attribute populated from other variables, including eduPersonAffiliation. + 60 => [ + 'class' => 'core:GenerateGroups', 'eduPersonAffiliation' + ], + */ + /* + * All users will be members of 'users' and 'members' + */ + /* + 61 => [ + 'class' => 'core:AttributeAdd', 'groups' => ['users', 'members'] + ], + */ + + // Adopts language from attribute to use in UI + 90 => 'core:LanguageAdaptor', + ], + + + + /************************** + | METADATA CONFIGURATION | + **************************/ + + /* + * This option allows you to specify a directory for your metadata outside of the standard metadata directory + * included in the standard distribution of the software. + */ + 'metadatadir' => 'metadata', + + /* + * This option configures the metadata sources. The metadata sources is given as an array with + * different metadata sources. When searching for metadata, SimpleSAMLphp will search through + * the array from start to end. + * + * Each element in the array is an associative array which configures the metadata source. + * The type of the metadata source is given by the 'type' element. For each type we have + * different configuration options. + * + * Flat file metadata handler: + * - 'type': This is always 'flatfile'. + * - 'directory': The directory we will load the metadata files from. The default value for + * this option is the value of the 'metadatadir' configuration option, or + * 'metadata/' if that option is unset. + * + * XML metadata handler: + * This metadata handler parses an XML file with either an EntityDescriptor element or an + * EntitiesDescriptor element. The XML file may be stored locally, or (for debugging) on a remote + * web server. + * The XML metadata handler defines the following options: + * - 'type': This is always 'xml'. + * - 'file': Path to the XML file with the metadata. + * - 'url': The URL to fetch metadata from. THIS IS ONLY FOR DEBUGGING - THERE IS NO CACHING OF THE RESPONSE. + * + * MDQ metadata handler: + * This metadata handler looks up for the metadata of an entity at the given MDQ server. + * The MDQ metadata handler defines the following options: + * - 'type': This is always 'mdq'. + * - 'server': Base URL of the MDQ server. Mandatory. + * - 'validateCertificate': The certificates file that may be used to sign the metadata. You don't need this + * option if you don't want to validate the signature on the metadata. Optional. + * - 'cachedir': Directory where metadata can be cached. Optional. + * - 'cachelength': Maximum time metadata can be cached, in seconds. Defaults to 24 + * hours (86400 seconds). Optional. + * + * PDO metadata handler: + * This metadata handler looks up metadata of an entity stored in a database. + * + * Note: If you are using the PDO metadata handler, you must configure the database + * options in this configuration file. + * + * The PDO metadata handler defines the following options: + * - 'type': This is always 'pdo'. + * + * Examples: + * + * This example defines two flatfile sources. One is the default metadata directory, the other + * is a metadata directory with auto-generated metadata files. + * + * 'metadata.sources' => [ + * ['type' => 'flatfile'], + * ['type' => 'flatfile', 'directory' => 'metadata-generated'], + * ], + * + * This example defines a flatfile source and an XML source. + * 'metadata.sources' => [ + * ['type' => 'flatfile'], + * ['type' => 'xml', 'file' => 'idp.example.org-idpMeta.xml'], + * ], + * + * This example defines an mdq source. + * 'metadata.sources' => [ + * [ + * 'type' => 'mdq', + * 'server' => 'http://mdq.server.com:8080', + * 'validateCertificate' => [ + * '/var/simplesamlphp/cert/metadata-key.new.crt', + * '/var/simplesamlphp/cert/metadata-key.old.crt' + * ], + * 'cachedir' => '/var/simplesamlphp/mdq-cache', + * 'cachelength' => 86400 + * ] + * ], + * + * This example defines an pdo source. + * 'metadata.sources' => [ + * ['type' => 'pdo'] + * ], + * + * Default: + * 'metadata.sources' => [ + * ['type' => 'flatfile'] + * ], + */ + 'metadata.sources' => [ + ['type' => 'flatfile'], + ], + + /* + * Should signing of generated metadata be enabled by default. + * + * Metadata signing can also be enabled for a individual SP or IdP by setting the + * same option in the metadata for the SP or IdP. + */ + 'metadata.sign.enable' => false, + + /* + * The default key & certificate which should be used to sign generated metadata. These + * are files stored in the cert dir. + * These values can be overridden by the options with the same names in the SP or + * IdP metadata. + * + * If these aren't specified here or in the metadata for the SP or IdP, then + * the 'certificate' and 'privatekey' option in the metadata will be used. + * if those aren't set, signing of metadata will fail. + */ + 'metadata.sign.privatekey' => null, + 'metadata.sign.privatekey_pass' => null, + 'metadata.sign.certificate' => null, + + + /**************************** + | DATA STORE CONFIGURATION | + ****************************/ + + /* + * Configure the data store for SimpleSAMLphp. + * + * - 'phpsession': Limited datastore, which uses the PHP session. + * - 'memcache': Key-value datastore, based on memcache. + * - 'sql': SQL datastore, using PDO. + * - 'redis': Key-value datastore, based on redis. + * + * The default datastore is 'phpsession'. + */ + 'store.type' => 'phpsession', + + /* + * The DSN the sql datastore should connect to. + * + * See http://www.php.net/manual/en/pdo.drivers.php for the various + * syntaxes. + */ + 'store.sql.dsn' => 'sqlite:/path/to/sqlitedatabase.sq3', + + /* + * The username and password to use when connecting to the database. + */ + 'store.sql.username' => null, + 'store.sql.password' => null, + + /* + * The prefix we should use on our tables. + */ + 'store.sql.prefix' => 'SimpleSAMLphp', + + /* + * The driver-options we should pass to the PDO-constructor. + */ + 'store.sql.options' => [], + + /* + * The hostname and port of the Redis datastore instance. + */ + 'store.redis.host' => 'localhost', + 'store.redis.port' => 6379, + + /* + * The prefix we should use on our Redis datastore. + */ + 'store.redis.prefix' => 'SimpleSAMLphp', +]; diff --git a/tests/config-templates/module_accounting.php b/tests/config-templates/module_accounting.php new file mode 100644 index 0000000000000000000000000000000000000000..e0d7108165d0f8a13e7a6cce8ce5ef21c75058c7 --- /dev/null +++ b/tests/config-templates/module_accounting.php @@ -0,0 +1,76 @@ +<?php + +declare(strict_types=1); + +use SimpleSAML\Module\accounting\ModuleConfiguration; +use SimpleSAML\Module\accounting\Stores; + +$config = [ + /** + * User ID attribute, one that is always available and that is unique to all users. + * If this attribute is not available, accounting will not be performed for that user. + * + * Examples: + * urn:oasis:names:tc:SAML:attribute:subject-id + * eduPersonUniqueId + * eduPersonPrincipalName + */ + ModuleConfiguration::OPTION_USER_ID_ATTRIBUTE => 'urn:oasis:names:tc:SAML:attribute:subject-id', + + /** + * Accounting processing type. There are two possible types: 'synchronous' and 'asynchronous'. + * - 'synchronous': accounting processing will be performed during authentication itself (slower) + * - 'asynchronous': for each authentication event a new job will be created for later processing (faster, + * but requires setting up job storage and a cron entry). + */ + ModuleConfiguration::OPTION_ACCOUNTING_PROCESSING_TYPE => + ModuleConfiguration\AccountingProcessingType::VALUE_SYNCHRONOUS, + + /** + * Jobs store. Determines which of the available stores will be used to store jobs in case the 'asynchronous' + * accounting processing type was set. + */ + ModuleConfiguration::OPTION_JOBS_STORE => Stores\Jobs\DoctrineDbal\JobsStore::class, + + /** + * Store connection for particular store. Can be used to set different connections for different stores. + */ + ModuleConfiguration::OPTION_STORE_TO_CONNECTION_KEY_MAP => [ + Stores\Jobs\DoctrineDbal\JobsStore::class => 'doctrine_dbal_pdo_mysql', + ], + + /** + * Store connections and their parameters. + * + * Any compatible Doctrine DBAL implementation can be used: + * https://www.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/configuration.html + * There are additional parameters for: table prefix. + * Examples for mysql and sqlite are provided below. + */ + ModuleConfiguration::OPTION_ALL_STORE_CONNECTIONS_AND_PARAMETERS => [ + 'doctrine_dbal_pdo_mysql' => [ + 'driver' => 'pdo_mysql', // (string): The built-in driver implementation to use + 'user' => 'user', // (string): Username to use when connecting to the database. + 'password' => 'password', // (string): Password to use when connecting to the database. + 'host' => 'host', // (string): Hostname of the database to connect to. + 'port' => 3306, // (integer): Port of the database to connect to. + 'dbname' => 'dbname', // (string): Name of the database/schema to connect to. + //'unix_socket' => 'unix_socket', // (string): Name of the socket used to connect to the database. + 'charset' => 'utf8', // (string): The charset used when connecting to the database. + //'url' => 'mysql://user:secret@localhost/mydb?charset=utf8', // ...alternative way of providing parameters. + // Additional parameters not originally available in Doctrine DBAL + 'table_prefix' => '', // (string): Prefix for each table. + ], + 'doctrine_dbal_pdo_sqlite' => [ + 'driver' => 'pdo_sqlite', // (string): The built-in driver implementation to use + 'path' => '/path/to/db.sqlite', // (string): The filesystem path to the database file. + // Mutually exclusive with memory. path takes precedence. + 'memory' => false, // (boolean): True if the SQLite database should be in-memory (non-persistent). + // Mutually exclusive with path. path takes precedence. + //'url' => 'sqlite:////path/to/db.sqlite // ...alternative way of providing path parameter. + //'url' => 'sqlite:///:memory:' // ...alternative way of providing memory parameter. + // Additional parameters not originally available in Doctrine DBAL + 'table_prefix' => '', // (string): Prefix for each table. + ], + ], +]; diff --git a/tests/config-templates/module_accounting_basic.php b/tests/config-templates/module_accounting_basic.php deleted file mode 100644 index 29497c1408b560e20d0af32af9f85340f549b679..0000000000000000000000000000000000000000 --- a/tests/config-templates/module_accounting_basic.php +++ /dev/null @@ -1,5 +0,0 @@ -<?php - -$config = [ - 'test-config' => 'test-value', -]; diff --git a/tests/src/Helpers/FilesystemHelperTest.php b/tests/src/Helpers/FilesystemHelperTest.php new file mode 100644 index 0000000000000000000000000000000000000000..01e6be75a9d128b9e97dca3811a96ad302c487ef --- /dev/null +++ b/tests/src/Helpers/FilesystemHelperTest.php @@ -0,0 +1,31 @@ +<?php + +namespace SimpleSAML\Test\Module\accounting\Helpers; + +use SimpleSAML\Module\accounting\Exceptions\InvalidValueException; +use SimpleSAML\Module\accounting\Helpers\FilesystemHelper; +use PHPUnit\Framework\TestCase; + +/** + * @covers \SimpleSAML\Module\accounting\Helpers\FilesystemHelper + */ +class FilesystemHelperTest extends TestCase +{ + public function testCanGetRealPath(): void + { + $path = __DIR__ . DIRECTORY_SEPARATOR . '..'; + + $realPath = FilesystemHelper::getRealPath($path); + + $this->assertSame(dirname(__DIR__), $realPath); + } + + public function testGetRealPathThrowsOnInvalidPaths(): void + { + $path = __DIR__ . DIRECTORY_SEPARATOR . 'invalid'; + + $this->expectException(InvalidValueException::class); + + FilesystemHelper::getRealPath($path); + } +} diff --git a/tests/src/ModuleConfigurationTest.php b/tests/src/ModuleConfigurationTest.php index b9fa74563c4230929187a19b43de57102a3f1b0b..9895cb8421003962067858c67c200f7bd152c66f 100644 --- a/tests/src/ModuleConfigurationTest.php +++ b/tests/src/ModuleConfigurationTest.php @@ -4,18 +4,88 @@ namespace SimpleSAML\Test\Module\accounting; use PHPUnit\Framework\TestCase; use SimpleSAML\Configuration; +use SimpleSAML\Module\accounting\Exceptions\InvalidConfigurationException; use SimpleSAML\Module\accounting\ModuleConfiguration; +use SimpleSAML\Module\accounting\Stores; /** * @covers \SimpleSAML\Module\accounting\ModuleConfiguration */ class ModuleConfigurationTest extends TestCase { - public function testSample(): void + protected ModuleConfiguration $moduleConfiguration; + + protected function setUp(): void { + parent::setUp(); // Configuration directory is set by phpunit using php ENV setting feature (check phpunit.xml). - $moduleConfiguration = new ModuleConfiguration('module_accounting_basic.php'); + $this->moduleConfiguration = new ModuleConfiguration('module_accounting.php'); + } + + public function testCanGetUnderlyingConfigurationInstance(): void + { + $this->assertInstanceOf(Configuration::class, $this->moduleConfiguration->getConfiguration()); + } + + public function testThrowExceptionsIfInvalidOptionIsSupplied(): void + { + $this->expectException(InvalidConfigurationException::class); + + $this->moduleConfiguration->get('invalid'); + } + + public function testCanGetValidOption(): void + { + $this->assertIsString($this->moduleConfiguration->get(ModuleConfiguration::OPTION_USER_ID_ATTRIBUTE)); + } + + public function testProperConnectionKeyIsReturned(): void + { + $this->assertSame( + 'doctrine_dbal_pdo_mysql', + $this->moduleConfiguration->getStoreConnection(Stores\Jobs\DoctrineDbal\JobsStore::class) + ); + } + + public function testInvalidConnectionKeyThrows(): void + { + $this->expectException(InvalidConfigurationException::class); + + $this->moduleConfiguration->getStoreConnection('invalid'); + } + + public function testCanGetDefinedConnections(): void + { + $this->assertArrayHasKey( + 'doctrine_dbal_pdo_mysql', + $this->moduleConfiguration->getAllStoreConnectionsAndParameters() + ); + } + + public function testCanGetSettingsForSpecificConnection(): void + { + $this->assertIsArray($this->moduleConfiguration->getStoreConnectionParameters('doctrine_dbal_pdo_mysql')); + } + + public function testGettingSettingsForInvalidConnectionThrows(): void + { + $this->expectException(InvalidConfigurationException::class); + $this->moduleConfiguration->getStoreConnectionParameters('invalid'); + } - $this->assertInstanceOf(Configuration::class, $moduleConfiguration->getConfiguration()); + public function testCanGetModuleSourceDirectory(): void + { + $this->assertSame( + dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'src', + $this->moduleConfiguration->getModuleSourceDirectory() + ); + } + + public function testCanGetModuleRootDirectory(): void + { + $this->assertSame( + dirname(__DIR__, 2), + $this->moduleConfiguration->getModuleRootDirectory() + ); } } diff --git a/tests/src/Services/LoggerServiceTest.php b/tests/src/Services/LoggerServiceTest.php new file mode 100644 index 0000000000000000000000000000000000000000..364cdbf9b1b7c9dab5104bb354ca1647ed533751 --- /dev/null +++ b/tests/src/Services/LoggerServiceTest.php @@ -0,0 +1,29 @@ +<?php + +namespace SimpleSAML\Test\Module\accounting\Services; + +use SimpleSAML\Module\accounting\Services\LoggerService; +use PHPUnit\Framework\TestCase; + +/** + * @covers \SimpleSAML\Module\accounting\Services\LoggerService + */ +class LoggerServiceTest extends TestCase +{ + public function testCanCallAllMethods(): void + { + $loggerService = new LoggerService(); + + $loggerService->stats('test'); + $loggerService->debug('test'); + $loggerService->info('test'); + $loggerService->notice('test'); + $loggerService->warning('test'); + $loggerService->error('test'); + $loggerService->alert('test'); + $loggerService->critical('test'); + $loggerService->emergency('test'); + + $this->assertTrue(true); // Nothing to evaluate + } +} diff --git a/tests/src/Stores/Connections/Bases/AbstractMigratorTest.php b/tests/src/Stores/Connections/Bases/AbstractMigratorTest.php new file mode 100644 index 0000000000000000000000000000000000000000..1cd96d8b2a24b11a76e126a4f1dcf69c374f56cc --- /dev/null +++ b/tests/src/Stores/Connections/Bases/AbstractMigratorTest.php @@ -0,0 +1,189 @@ +<?php + +namespace SimpleSAML\Test\Module\accounting\Stores\Connections\Bases; + +use Doctrine\DBAL\Schema\AbstractSchemaManager; +use SimpleSAML\Module\accounting\Exceptions\MigrationException; +use SimpleSAML\Module\accounting\ModuleConfiguration; +use SimpleSAML\Module\accounting\Services\LoggerService; +use SimpleSAML\Module\accounting\Stores\Connections\Bases\AbstractMigrator; +use PHPUnit\Framework\TestCase; +use SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal\Bases\AbstractMigration; +use SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal\Connection; +use SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal\Migrator; +use SimpleSAML\Module\accounting\Stores\Jobs\DoctrineDbal\JobsStore; + +/** + * @covers \SimpleSAML\Module\accounting\Stores\Connections\Bases\AbstractMigrator + * @uses \SimpleSAML\Module\accounting\Helpers\FilesystemHelper + * @uses \SimpleSAML\Module\accounting\ModuleConfiguration + * @uses \SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal\Connection + * @uses \SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal\Migrator + * @uses \SimpleSAML\Module\accounting\Stores\Jobs\DoctrineDbal\JobsStore\Migrations\Version20220601000000CreateJobsTable + * @uses \SimpleSAML\Module\accounting\Stores\Jobs\DoctrineDbal\JobsStore\Migrations\Version20220601000100CreateFailedJobsTable + * @uses \SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal\Bases\AbstractMigration + */ +class AbstractMigratorTest extends TestCase +{ + protected Connection $connection; + protected AbstractSchemaManager $schemaManager; + protected string $tableName; + + /** + * @var \PHPUnit\Framework\MockObject\MockObject + */ + protected $loggerServiceMock; + protected ModuleConfiguration $moduleConfiguration; + + protected function setUp(): void + { + parent::setUp(); + $this->connection = new Connection(['driver' => 'pdo_sqlite', 'memory' => true,]); + // TODO mivanci ostavi samo sqlite verziju +// $this->connection = new Connection([ +// 'dbname' => 'accounting', +// 'user' => 'apps', +// 'password' => 'apps', +// 'host' => '127.0.0.1', +// 'port' => '33306', +// 'driver' => 'pdo_mysql', +// ]); + + $this->schemaManager = $this->connection->dbal()->createSchemaManager(); + $this->tableName = $this->connection->preparePrefixedTableName(Migrator::TABLE_NAME); + + $this->loggerServiceMock = $this->createMock(LoggerService::class); + + // Configuration directory is set by phpunit using php ENV setting feature (check phpunit.xml). + $this->moduleConfiguration = new ModuleConfiguration('module_accounting.php'); + } + + public function testCanGatherMigrationClassesFromDirectory(): void + { + /** @psalm-suppress InvalidArgument Using mock instead of LoggerService instance */ + $migrator = new Migrator($this->connection, $this->loggerServiceMock); + + $directory = $this->getSampleMigrationsDirectory(); + + $namespace = $this->getSampleNameSpace(); + + $migrationClasses = $migrator->gatherMigrationClassesFromDirectory($directory, $namespace); + + $this->assertTrue(in_array($namespace . '\Version20220601000000CreateJobsTable', $migrationClasses)); + } + + public function testCanRunMigrationClasses(): void + { + /** @psalm-suppress InvalidArgument Using mock instead of LoggerService instance */ + $migrator = new Migrator($this->connection, $this->loggerServiceMock); + + $migrator->runSetup(); + + $directory = $this->getSampleMigrationsDirectory(); + + $namespace = $this->getSampleNameSpace(); + + $migrationClasses = $migrator->gatherMigrationClassesFromDirectory($directory, $namespace); + + $jobsTableName = $this->connection->preparePrefixedTableName(JobsStore::TABLE_NAME_JOBS); + + $this->assertFalse($this->schemaManager->tablesExist($jobsTableName)); + + $migrator->runMigrationClasses($migrationClasses); + + $this->assertTrue($this->schemaManager->tablesExist($jobsTableName)); + } + + public function testCanGatherOnlyMigrationClasses(): void + { + /** @psalm-suppress InvalidArgument Using mock instead of LoggerService instance */ + $migrator = new Migrator($this->connection, $this->loggerServiceMock); + + $directory = __DIR__; + $namespace = __NAMESPACE__; + + $this->assertEmpty($migrator->gatherMigrationClassesFromDirectory($directory, $namespace)); + } + + public function testMigrationExceptionHaltsExecution(): void + { + $migration = new class ($this->connection) extends AbstractMigration + { + public function run(): void + { + throw new \Exception('Something went wrong.'); + } + + public function revert(): void + { + } + }; + + /** @psalm-suppress InvalidArgument Using mock instead of LoggerService instance */ + $migrator = new Migrator($this->connection, $this->loggerServiceMock); + + $this->expectException(MigrationException::class); + + $migrator->runMigrationClasses([get_class($migration)]); + } + + public function testCanGetNonImplementedMigrationClasses(): void + { + /** @psalm-suppress InvalidArgument Using mock instead of LoggerService instance */ + $migrator = new Migrator($this->connection, $this->loggerServiceMock); + + $migrator->runSetup(); + + $nonImplementedMigrationClasses = $migrator->getNonImplementedMigrationClasses( + $this->getSampleMigrationsDirectory(), + $this->getSampleNameSpace() + ); + + $this->assertTrue(in_array( + JobsStore\Migrations\Version20220601000000CreateJobsTable::class, + $nonImplementedMigrationClasses + )); + } + + public function testCanFindOutIfNonImplementedMigrationClassesExist(): void + { + /** @psalm-suppress InvalidArgument Using mock instead of LoggerService instance */ + $migrator = new Migrator($this->connection, $this->loggerServiceMock); + + $migrator->runSetup(); + + $this->assertTrue($migrator->hasNonImplementedMigrationClasses( + $this->getSampleMigrationsDirectory(), + $this->getSampleNameSpace() + )); + } + + public function testCanRunNonImplementedMigrationClasses(): void + { +/** @psalm-suppress InvalidArgument Using mock instead of LoggerService instance */ + $migrator = new Migrator($this->connection, $this->loggerServiceMock); + + $migrator->runSetup(); + + $directory = $this->getSampleMigrationsDirectory(); + $namespace = $this->getSampleNameSpace(); + + $this->assertTrue($migrator->hasNonImplementedMigrationClasses($directory, $namespace)); + + $migrator->runNonImplementedMigrationClasses($directory, $namespace); + + $this->assertFalse($migrator->hasNonImplementedMigrationClasses($directory, $namespace)); + } + + protected function getSampleMigrationsDirectory(): string + { + return $this->moduleConfiguration->getModuleSourceDirectory() . DIRECTORY_SEPARATOR . + 'Stores' . DIRECTORY_SEPARATOR . 'Jobs' . DIRECTORY_SEPARATOR . 'DoctrineDbal' . DIRECTORY_SEPARATOR . + 'JobsStore' . DIRECTORY_SEPARATOR . AbstractMigrator::DEFAULT_MIGRATIONS_DIRECTORY_NAME; + } + + protected function getSampleNameSpace(): string + { + return JobsStore::class . '\\' . AbstractMigrator::DEFAULT_MIGRATIONS_DIRECTORY_NAME; + } +} diff --git a/tests/src/Stores/Connections/DoctrineDbal/Bases/AbstractMigrationTest.php b/tests/src/Stores/Connections/DoctrineDbal/Bases/AbstractMigrationTest.php new file mode 100644 index 0000000000000000000000000000000000000000..bdbef5430da50c68a810fef9a7413fb137d34a8d --- /dev/null +++ b/tests/src/Stores/Connections/DoctrineDbal/Bases/AbstractMigrationTest.php @@ -0,0 +1,26 @@ +<?php + +namespace SimpleSAML\Test\Module\accounting\Stores\Connections\DoctrineDbal\Bases; + +use SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal\Bases\AbstractMigration; +use PHPUnit\Framework\TestCase; +use SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal\Connection; +use SimpleSAML\Module\accounting\Stores\Jobs\DoctrineDbal\JobsStore\Migrations\Version20220601000000CreateJobsTable; + +/** + * @covers \SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal\Bases\AbstractMigration + * @uses \SimpleSAML\Module\accounting\Stores\Jobs\DoctrineDbal\JobsStore\Migrations\Version20220601000000CreateJobsTable + * @uses \SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal\Connection + */ +class AbstractMigrationTest extends TestCase +{ + public function testCanInstantiateMigrationClass(): void + { + $connection = new Connection(['driver' => 'pdo_sqlite', 'memory' => true,]); + + $this->assertInstanceOf( + AbstractMigration::class, + new Version20220601000000CreateJobsTable($connection) + ); + } +} diff --git a/tests/src/Stores/Connections/DoctrineDbal/ConnectionTest.php b/tests/src/Stores/Connections/DoctrineDbal/ConnectionTest.php new file mode 100644 index 0000000000000000000000000000000000000000..cbc1f869dfb10fdabf9299c0d265eec401388b63 --- /dev/null +++ b/tests/src/Stores/Connections/DoctrineDbal/ConnectionTest.php @@ -0,0 +1,55 @@ +<?php + +namespace SimpleSAML\Test\Module\accounting\Stores\Connections\DoctrineDbal; + +use PHPUnit\Framework\TestCase; +use SimpleSAML\Module\accounting\Exceptions\InvalidConfigurationException; +use SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal\Connection; + +/** + * @covers \SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal\Connection + */ +class ConnectionTest extends TestCase +{ + protected array $parameters = [ + 'driver' => 'pdo_sqlite', + 'memory' => true, + ]; + + public function testCanInstantiateDbalConnection(): void + { + $connection = new Connection($this->parameters); + + $this->assertInstanceOf(\Doctrine\DBAL\Connection::class, $connection->dbal()); + } + + public function testInvalidConnectionParametersThrow(): void + { + $this->expectException(InvalidConfigurationException::class); + (new Connection(['invalid' => 'parameter'])); + } + + public function testCanSetTablePrefix(): void + { + $prefix = 'test_'; + $parameters = $this->parameters; + $parameters['table_prefix'] = $prefix; + + $connection = new Connection($parameters); + + $this->assertEquals($prefix, $connection->getTablePrefix()); + + $this->assertSame('test_test', $connection->preparePrefixedTableName('test')); + } + + public function testTablePrefixParameterThrowsIfNotString(): void + { + $this->expectException(InvalidConfigurationException::class); + + $parameters = $this->parameters; + $parameters['table_prefix'] = new class () { + }; + + (new Connection($parameters)); + } +} diff --git a/tests/src/Stores/Connections/DoctrineDbal/FactoryTest.php b/tests/src/Stores/Connections/DoctrineDbal/FactoryTest.php new file mode 100644 index 0000000000000000000000000000000000000000..3790bdce74d4b819f4ecc41df718323dc4416167 --- /dev/null +++ b/tests/src/Stores/Connections/DoctrineDbal/FactoryTest.php @@ -0,0 +1,51 @@ +<?php + +namespace SimpleSAML\Test\Module\accounting\Stores\Connections\DoctrineDbal; + +use SimpleSAML\Module\accounting\ModuleConfiguration; +use SimpleSAML\Module\accounting\Services\LoggerService; +use SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal\Connection; +use SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal\Factory; +use PHPUnit\Framework\TestCase; +use SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal\Migrator; + +/** + * @covers \SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal\Factory + * @uses \SimpleSAML\Module\accounting\ModuleConfiguration + * @uses \SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal\Connection + * @uses \SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal\Migrator + */ +class FactoryTest extends TestCase +{ + protected ModuleConfiguration $moduleConfiguration; + + /** + * @var \PHPUnit\Framework\MockObject\MockObject + */ + protected $loggerServiceMock; + + protected function setUp(): void + { + // Configuration directory is set by phpunit using php ENV setting feature (check phpunit.xml). + $this->moduleConfiguration = new ModuleConfiguration('module_accounting.php'); + $this->loggerServiceMock = $this->createMock(LoggerService::class); + } + + public function testCanBuildConnection(): void + { + /** @psalm-suppress InvalidArgument */ + $factory = new Factory($this->moduleConfiguration, $this->loggerServiceMock); + + $this->assertInstanceOf(Connection::class, $factory->buildConnection('doctrine_dbal_pdo_mysql')); + } + + public function testCanBuildMigrator(): void + { + /** @psalm-suppress InvalidArgument */ + $factory = new Factory($this->moduleConfiguration, $this->loggerServiceMock); + + $connection = new Connection(['driver' => 'pdo_sqlite', 'memory' => true,]); + + $this->assertInstanceOf(Migrator::class, $factory->buildMigrator($connection)); + } +} diff --git a/tests/src/Stores/Connections/DoctrineDbal/MigratorTest.php b/tests/src/Stores/Connections/DoctrineDbal/MigratorTest.php new file mode 100644 index 0000000000000000000000000000000000000000..f02cd4b554f61a04e27c22b43651fca9c3f3f877 --- /dev/null +++ b/tests/src/Stores/Connections/DoctrineDbal/MigratorTest.php @@ -0,0 +1,158 @@ +<?php + +namespace SimpleSAML\Test\Module\accounting\Stores\Connections\DoctrineDbal; + +use PHPUnit\Framework\TestCase; +use Doctrine\DBAL\Schema\AbstractSchemaManager; +use SimpleSAML\Module\accounting\Exceptions\InvalidValueException; +use SimpleSAML\Module\accounting\ModuleConfiguration; +use SimpleSAML\Module\accounting\Services\LoggerService; +use SimpleSAML\Module\accounting\Stores\Connections\Bases\AbstractMigrator; +use SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal\Migrator; +use SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal\Connection; +use SimpleSAML\Module\accounting\Stores\Interfaces\MigrationInterface; +use SimpleSAML\Module\accounting\Stores\Jobs\DoctrineDbal\JobsStore; + +use function PHPUnit\Framework\assertFalse; + +/** + * @covers \SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal\Migrator + * @covers \SimpleSAML\Module\accounting\Stores\Connections\Bases\AbstractMigrator + * @uses \SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal\Connection + * @uses \SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal\Bases\AbstractMigration + * @uses \SimpleSAML\Module\accounting\Stores\Jobs\DoctrineDbal\JobsStore\Migrations\Version20220601000000CreateJobsTable + * @uses \SimpleSAML\Module\accounting\Stores\Jobs\DoctrineDbal\JobsStore\Migrations\Version20220601000100CreateFailedJobsTable + * @uses \SimpleSAML\Module\accounting\ModuleConfiguration + * @uses \SimpleSAML\Module\accounting\Helpers\FilesystemHelper + */ +class MigratorTest extends TestCase +{ + protected Connection $connection; + protected AbstractSchemaManager $schemaManager; + protected string $tableName; + + /** + * @var \PHPUnit\Framework\MockObject\MockObject + */ + protected $loggerServiceMock; + protected ModuleConfiguration $moduleConfiguration; + + protected function setUp(): void + { + parent::setUp(); + $this->connection = new Connection(['driver' => 'pdo_sqlite', 'memory' => true,]); + // TODO mivanci ostavi samo sqlite verziju +// $this->connection = new Connection([ +// 'dbname' => 'accounting', +// 'user' => 'apps', +// 'password' => 'apps', +// 'host' => '127.0.0.1', +// 'port' => '33306', +// 'driver' => 'pdo_mysql', +// ]); + + $this->schemaManager = $this->connection->dbal()->createSchemaManager(); + $this->tableName = $this->connection->preparePrefixedTableName(Migrator::TABLE_NAME); + + $this->loggerServiceMock = $this->createMock(LoggerService::class); + + // Configuration directory is set by phpunit using php ENV setting feature (check phpunit.xml). + $this->moduleConfiguration = new ModuleConfiguration('module_accounting.php'); + } + + public function testCanCreateMigrationsTable(): void + { + $this->assertFalse($this->schemaManager->tablesExist([$this->tableName])); + + /** @psalm-suppress InvalidArgument Using mock instead of LoggerService instance */ + $migrator = new Migrator($this->connection, $this->loggerServiceMock); + + $this->assertTrue($migrator->needsSetup()); + + $migrator->runSetup(); + + $this->assertFalse($migrator->needsSetup()); + $this->assertTrue($this->schemaManager->tablesExist([$this->tableName])); + } + + public function testRunningMigratiorSetupMultipleTimesLogsWarning(): void + { + $this->loggerServiceMock + ->expects($this->once()) + ->method('warning') + ->with($this->stringContains('setup is not needed')); + + /** @psalm-suppress InvalidArgument Using mock instead of LoggerService instance */ + $migrator = new Migrator($this->connection, $this->loggerServiceMock); + + $this->assertTrue($migrator->needsSetup()); + + $migrator->runSetup(); + $migrator->runSetup(); + } + + public function testCanRunMigrationClasses(): void + { + /** @psalm-suppress InvalidArgument */ + $migrator = new Migrator($this->connection, $this->loggerServiceMock); + + $migrator->runSetup(); + + $tableNameJobs = $this->connection->preparePrefixedTableName(JobsStore::TABLE_NAME_JOBS); + $this > assertFalse($this->schemaManager->tablesExist($tableNameJobs)); + + $migrator->runMigrationClasses([JobsStore\Migrations\Version20220601000000CreateJobsTable::class]); + + $this->assertTrue($this->schemaManager->tablesExist($tableNameJobs)); + } + + public function testCanOnlyRunDoctrineDbalMigrationClasses(): void + { + $migration = new class implements MigrationInterface { + public function run(): void + { + } + public function revert(): void + { + } + }; + + /** @psalm-suppress InvalidArgument */ + $migrator = new Migrator($this->connection, $this->loggerServiceMock); + + $migrator->runSetup(); + + $this->expectException(InvalidValueException::class); + + $migrator->runMigrationClasses([get_class($migration)]); + } + + public function testCanGetImplementedMigrationClasses(): void + { + /** @psalm-suppress InvalidArgument */ + $migrator = new Migrator($this->connection, $this->loggerServiceMock); + + $migrator->runSetup(); + + $this->assertEmpty($migrator->getImplementedMigrationClasses()); + + $migrator->runNonImplementedMigrationClasses( + $this->getSampleMigrationsDirectory(), + $this->getSampleNameSpace() + ); + + $this->assertNotEmpty($migrator->getImplementedMigrationClasses()); + } + + protected function getSampleMigrationsDirectory(): string + { + return $this->moduleConfiguration->getModuleSourceDirectory() . DIRECTORY_SEPARATOR . + 'Stores' . DIRECTORY_SEPARATOR . 'Jobs' . DIRECTORY_SEPARATOR . 'DoctrineDbal' . DIRECTORY_SEPARATOR . + 'JobsStore' . DIRECTORY_SEPARATOR . AbstractMigrator::DEFAULT_MIGRATIONS_DIRECTORY_NAME; + } + + protected function getSampleNameSpace(): string + { + return JobsStore::class . '\\' . AbstractMigrator::DEFAULT_MIGRATIONS_DIRECTORY_NAME; + } +} diff --git a/tests/src/Stores/Jobs/DoctrineDbal/JobsStore/Migrations/Version20220601000000CreateJobsTableTest.php b/tests/src/Stores/Jobs/DoctrineDbal/JobsStore/Migrations/Version20220601000000CreateJobsTableTest.php new file mode 100644 index 0000000000000000000000000000000000000000..ad2b7e99a145e3d088e2c3c5502f0e468bb7e618 --- /dev/null +++ b/tests/src/Stores/Jobs/DoctrineDbal/JobsStore/Migrations/Version20220601000000CreateJobsTableTest.php @@ -0,0 +1,37 @@ +<?php + +namespace SimpleSAML\Test\Module\accounting\Stores\Jobs\DoctrineDbal\JobsStore\Migrations; + +use SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal\Connection; +use SimpleSAML\Module\accounting\Stores\Jobs\DoctrineDbal\JobsStore; +use SimpleSAML\Module\accounting\Stores\Jobs\DoctrineDbal\JobsStore\Migrations\Version20220601000000CreateJobsTable; +use PHPUnit\Framework\TestCase; + +/** + * @covers \SimpleSAML\Module\accounting\Stores\Jobs\DoctrineDbal\JobsStore\Migrations\Version20220601000000CreateJobsTable + * @uses \SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal\Connection + * @uses \SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal\Bases\AbstractMigration + */ +class Version20220601000000CreateJobsTableTest extends TestCase +{ + protected Connection $connection; + protected \Doctrine\DBAL\Schema\AbstractSchemaManager $schemaManager; + protected string $tableName; + + protected function setUp(): void + { + $this->connection = new Connection(['driver' => 'pdo_sqlite', 'memory' => true,]); + $this->schemaManager = $this->connection->dbal()->createSchemaManager(); + $this->tableName = $this->connection->preparePrefixedTableName(JobsStore::TABLE_NAME_JOBS); + } + + public function testCanRunMigration(): void + { + $this->assertFalse($this->schemaManager->tablesExist($this->tableName)); + $migration = new Version20220601000000CreateJobsTable($this->connection); + $migration->run(); + $this->assertTrue($this->schemaManager->tablesExist($this->tableName)); + $migration->revert(); + $this->assertFalse($this->schemaManager->tablesExist($this->tableName)); + } +} diff --git a/tests/src/Stores/Jobs/DoctrineDbal/JobsStore/Migrations/Version20220601000100CreateFailedJobsTableTest.php b/tests/src/Stores/Jobs/DoctrineDbal/JobsStore/Migrations/Version20220601000100CreateFailedJobsTableTest.php new file mode 100644 index 0000000000000000000000000000000000000000..c99092eef1c563ff1ac8d685ac52256866616cea --- /dev/null +++ b/tests/src/Stores/Jobs/DoctrineDbal/JobsStore/Migrations/Version20220601000100CreateFailedJobsTableTest.php @@ -0,0 +1,38 @@ +<?php + +namespace SimpleSAML\Test\Module\accounting\Stores\Jobs\DoctrineDbal\JobsStore\Migrations; + +use SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal\Connection; +use SimpleSAML\Module\accounting\Stores\Jobs\DoctrineDbal\JobsStore; +use SimpleSAML\Module\accounting\Stores\Jobs\DoctrineDbal\JobsStore\Migrations; +use PHPUnit\Framework\TestCase; + +/** + * @covers \SimpleSAML\Module\accounting\Stores\Jobs\DoctrineDbal\JobsStore\Migrations\Version20220601000100CreateFailedJobsTable + * @uses \SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal\Connection + * @uses \SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal\Bases\AbstractMigration + * + */ +class Version20220601000100CreateFailedJobsTableTest extends TestCase +{ + protected Connection $connection; + protected \Doctrine\DBAL\Schema\AbstractSchemaManager $schemaManager; + protected string $tableName; + + protected function setUp(): void + { + $this->connection = new Connection(['driver' => 'pdo_sqlite', 'memory' => true,]); + $this->schemaManager = $this->connection->dbal()->createSchemaManager(); + $this->tableName = $this->connection->preparePrefixedTableName(JobsStore::TABLE_NAME_FAILED_JOBS); + } + + public function testCanRunMigration(): void + { + $this->assertFalse($this->schemaManager->tablesExist($this->tableName)); + $migration = new Migrations\Version20220601000100CreateFailedJobsTable($this->connection); + $migration->run(); + $this->assertTrue($this->schemaManager->tablesExist($this->tableName)); + $migration->revert(); + $this->assertFalse($this->schemaManager->tablesExist($this->tableName)); + } +} diff --git a/tests/src/Stores/Jobs/DoctrineDbal/JobsStoreTest.php b/tests/src/Stores/Jobs/DoctrineDbal/JobsStoreTest.php new file mode 100644 index 0000000000000000000000000000000000000000..cbb4013c7b590a7a8120deae3c2c9185c27191d7 --- /dev/null +++ b/tests/src/Stores/Jobs/DoctrineDbal/JobsStoreTest.php @@ -0,0 +1,45 @@ +<?php + +namespace SimpleSAML\Test\Module\accounting\Stores\Jobs\DoctrineDbal; + +use PHPUnit\Framework\MockObject\MockObject; +use SimpleSAML\Module\accounting\ModuleConfiguration; +use SimpleSAML\Module\accounting\Services\LoggerService; +use SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal\Connection; +use SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal\Factory; +use SimpleSAML\Module\accounting\Stores\Jobs\DoctrineDbal\JobsStore; +use PHPUnit\Framework\TestCase; + +/** + * @covers \SimpleSAML\Module\accounting\Stores\Jobs\DoctrineDbal\JobsStore + * @uses \SimpleSAML\Module\accounting\ModuleConfiguration + * @uses \SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal\Connection + * @uses \SimpleSAML\Module\accounting\Stores\Connections\DoctrineDbal\Factory + */ +class JobsStoreTest extends TestCase +{ + protected ModuleConfiguration $moduleConfiguration; + protected \PHPUnit\Framework\MockObject\Stub $factory; + protected Connection $connection; + + protected function setUp(): void + { + // Configuration directory is set by phpunit using php ENV setting feature (check phpunit.xml). + $this->moduleConfiguration = new ModuleConfiguration('module_accounting.php'); + $this->connection = new Connection(['driver' => 'pdo_sqlite', 'memory' => true,]); + $this->factory = $this->createStub(Factory::class); + $this->factory->method('buildConnection')->willReturn($this->connection); + } + + public function testCanGetPrefixedTableNames(): void + { + /** @psalm-suppress InvalidArgument */ + $jobsStore = new JobsStore($this->moduleConfiguration, $this->factory); + + $tableNameJobs = $this->connection->preparePrefixedTableName(JobsStore::TABLE_NAME_JOBS); + $tableNameFailedJobs = $this->connection->preparePrefixedTableName(JobsStore::TABLE_NAME_FAILED_JOBS); + + $this->assertSame($tableNameJobs, $jobsStore->getPrefixedTableNameJobs()); + $this->assertSame($tableNameFailedJobs, $jobsStore->getPrefixedTableNameFailedJobs()); + } +}