From b05f77b6a74c3e74f9790eaea422e35221e6e25d Mon Sep 17 00:00:00 2001 From: Ruben van der Linde Date: Wed, 22 Mar 2023 07:24:13 +0100 Subject: [PATCH 1/7] First test --- .github/workflows/documentation.yml | 26 +++ .github/workflows/phpcbf.yml | 26 +++ .github/workflows/phpcs.yml | 19 +++ .github/workflows/phpunit.yml | 18 ++ .phpcs.xml | 157 ++++++++++++++++++ .../Command}/CacheCleanupCommand.php | 0 .../Command}/CacheClearCommand.php | 0 {Command => src/Command}/CacheCommand.php | 0 .../Command}/CacheWarmupCommand.php | 0 .../Command}/ComposerUpdateCommand.php | 0 {Command => src/Command}/DataClearCommand.php | 0 {Command => src/Command}/EavClearCommand.php | 0 {Command => src/Command}/InstallCommand.php | 0 {Command => src/Command}/UninstallCommand.php | 0 {Command => src/Command}/UpgradeCommand.php | 0 .../Command}/ValidateObjectCommand.php | 0 .../Command}/ValidateSchemaCommand.php | 0 .../Command}/ValidateValueCommand.php | 0 .../Controller}/PluginController.php | 0 .../Controller}/SearchController.php | 0 {Entity => src/Entity}/CronjobLog.php | 0 .../Service}/AuthenticationService.php | 0 {Service => src/Service}/CacheService.php | 0 {Service => src/Service}/CallService.php | 0 {Service => src/Service}/ComposerService.php | 0 {Service => src/Service}/EavService.php | 0 {Service => src/Service}/EndpointService.php | 0 {Service => src/Service}/FileService.php | 0 .../Service}/GatewayResourceService.php | 0 .../Service}/InstallationService.php | 0 {Service => src/Service}/MappingService.php | 0 {Service => src/Service}/OasService.php | 0 {Service => src/Service}/RequestService.php | 0 {Service => src/Service}/SchemaService.php | 0 .../Subscriber}/CacheDatabaseSubscriber.php | 0 .../DoctrineToGatewayEventSubscriber.php | 0 .../Subscriber}/ObjectReferenceSubscriber.php | 0 .../Subscriber}/ObjectUriSubscriber.php | 0 38 files changed, 246 insertions(+) create mode 100644 .github/workflows/documentation.yml create mode 100644 .github/workflows/phpcbf.yml create mode 100644 .github/workflows/phpcs.yml create mode 100644 .github/workflows/phpunit.yml create mode 100644 .phpcs.xml rename {Command => src/Command}/CacheCleanupCommand.php (100%) rename {Command => src/Command}/CacheClearCommand.php (100%) rename {Command => src/Command}/CacheCommand.php (100%) rename {Command => src/Command}/CacheWarmupCommand.php (100%) rename {Command => src/Command}/ComposerUpdateCommand.php (100%) rename {Command => src/Command}/DataClearCommand.php (100%) rename {Command => src/Command}/EavClearCommand.php (100%) rename {Command => src/Command}/InstallCommand.php (100%) rename {Command => src/Command}/UninstallCommand.php (100%) rename {Command => src/Command}/UpgradeCommand.php (100%) rename {Command => src/Command}/ValidateObjectCommand.php (100%) rename {Command => src/Command}/ValidateSchemaCommand.php (100%) rename {Command => src/Command}/ValidateValueCommand.php (100%) rename {Controller => src/Controller}/PluginController.php (100%) rename {Controller => src/Controller}/SearchController.php (100%) rename {Entity => src/Entity}/CronjobLog.php (100%) rename {Service => src/Service}/AuthenticationService.php (100%) rename {Service => src/Service}/CacheService.php (100%) rename {Service => src/Service}/CallService.php (100%) rename {Service => src/Service}/ComposerService.php (100%) rename {Service => src/Service}/EavService.php (100%) rename {Service => src/Service}/EndpointService.php (100%) rename {Service => src/Service}/FileService.php (100%) rename {Service => src/Service}/GatewayResourceService.php (100%) rename {Service => src/Service}/InstallationService.php (100%) rename {Service => src/Service}/MappingService.php (100%) rename {Service => src/Service}/OasService.php (100%) rename {Service => src/Service}/RequestService.php (100%) rename {Service => src/Service}/SchemaService.php (100%) rename {Subscriber => src/Subscriber}/CacheDatabaseSubscriber.php (100%) rename {Subscriber => src/Subscriber}/DoctrineToGatewayEventSubscriber.php (100%) rename {Subscriber => src/Subscriber}/ObjectReferenceSubscriber.php (100%) rename {Subscriber => src/Subscriber}/ObjectUriSubscriber.php (100%) diff --git a/.github/workflows/documentation.yml b/.github/workflows/documentation.yml new file mode 100644 index 00000000..47af7981 --- /dev/null +++ b/.github/workflows/documentation.yml @@ -0,0 +1,26 @@ +# .github/workflows/documentation.yml +name: Docs + +on: [push] + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + - uses: php-actions/composer@v6 + with: + php_version: "7.4" + php_extensions: redis exif + version: 2.x + command: require clean/phpdoc-md + - name: Build the docs + run: vendor/bin/phpdoc-md + - name: Git commit + run: | + git config user.name "GitHub Actions" + git config user.email "" + git add docs/classes + git commit -m "Update phpdoc" || echo "No changes to commit" + git push \ No newline at end of file diff --git a/.github/workflows/phpcbf.yml b/.github/workflows/phpcbf.yml new file mode 100644 index 00000000..88ce68b7 --- /dev/null +++ b/.github/workflows/phpcbf.yml @@ -0,0 +1,26 @@ +name: php-cbf + +on: [push, pull_request] + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: '8.2' + tools: cs2pr, phpcbf + + - name: Run phpcbf + run: phpcbf . + continue-on-error: true + - name: Git commit + run: | + git config user.name "GitHub Actions" + git config user.email "" + git add src + git commit -m "Update src from PHP Codesniffer" || echo "No changes to commit" + git push \ No newline at end of file diff --git a/.github/workflows/phpcs.yml b/.github/workflows/phpcs.yml new file mode 100644 index 00000000..1c70a0c4 --- /dev/null +++ b/.github/workflows/phpcs.yml @@ -0,0 +1,19 @@ +name: php-cs + +on: [push, pull_request] + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: '8.2' + tools: cs2pr, phpcs + + - name: Run phpcs + run: phpcs -q --report=checkstyle src | cs2pr + continue-on-error: true \ No newline at end of file diff --git a/.github/workflows/phpunit.yml b/.github/workflows/phpunit.yml new file mode 100644 index 00000000..3367bfed --- /dev/null +++ b/.github/workflows/phpunit.yml @@ -0,0 +1,18 @@ +name: php-unit + +on: [push] + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + - uses: php-actions/composer@v6 + with: + php_version: "7.4" + php_extensions: redis exif + version: 2.x + command: require symfony/test-pack + - name: Run tests + run: php bin/phpunit --coverage-text \ No newline at end of file diff --git a/.phpcs.xml b/.phpcs.xml new file mode 100644 index 00000000..94c18da8 --- /dev/null +++ b/.phpcs.xml @@ -0,0 +1,157 @@ + + + The coding standard for PHP_CodeSniffer itself, for more config -> for https://github.com/squizlabs/PHP_CodeSniffer/wiki/Configuration-Options. + + README.md + LICENSE.md + CoreBundle.php + src + DependencyInjection + + + + + + + + error + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + error + + + + + error + + + + + tests/bootstrap\.php + + + + + tests/Core/Tokenizer/StableCommentWhitespaceWinTest\.php + + + diff --git a/Command/CacheCleanupCommand.php b/src/Command/CacheCleanupCommand.php similarity index 100% rename from Command/CacheCleanupCommand.php rename to src/Command/CacheCleanupCommand.php diff --git a/Command/CacheClearCommand.php b/src/Command/CacheClearCommand.php similarity index 100% rename from Command/CacheClearCommand.php rename to src/Command/CacheClearCommand.php diff --git a/Command/CacheCommand.php b/src/Command/CacheCommand.php similarity index 100% rename from Command/CacheCommand.php rename to src/Command/CacheCommand.php diff --git a/Command/CacheWarmupCommand.php b/src/Command/CacheWarmupCommand.php similarity index 100% rename from Command/CacheWarmupCommand.php rename to src/Command/CacheWarmupCommand.php diff --git a/Command/ComposerUpdateCommand.php b/src/Command/ComposerUpdateCommand.php similarity index 100% rename from Command/ComposerUpdateCommand.php rename to src/Command/ComposerUpdateCommand.php diff --git a/Command/DataClearCommand.php b/src/Command/DataClearCommand.php similarity index 100% rename from Command/DataClearCommand.php rename to src/Command/DataClearCommand.php diff --git a/Command/EavClearCommand.php b/src/Command/EavClearCommand.php similarity index 100% rename from Command/EavClearCommand.php rename to src/Command/EavClearCommand.php diff --git a/Command/InstallCommand.php b/src/Command/InstallCommand.php similarity index 100% rename from Command/InstallCommand.php rename to src/Command/InstallCommand.php diff --git a/Command/UninstallCommand.php b/src/Command/UninstallCommand.php similarity index 100% rename from Command/UninstallCommand.php rename to src/Command/UninstallCommand.php diff --git a/Command/UpgradeCommand.php b/src/Command/UpgradeCommand.php similarity index 100% rename from Command/UpgradeCommand.php rename to src/Command/UpgradeCommand.php diff --git a/Command/ValidateObjectCommand.php b/src/Command/ValidateObjectCommand.php similarity index 100% rename from Command/ValidateObjectCommand.php rename to src/Command/ValidateObjectCommand.php diff --git a/Command/ValidateSchemaCommand.php b/src/Command/ValidateSchemaCommand.php similarity index 100% rename from Command/ValidateSchemaCommand.php rename to src/Command/ValidateSchemaCommand.php diff --git a/Command/ValidateValueCommand.php b/src/Command/ValidateValueCommand.php similarity index 100% rename from Command/ValidateValueCommand.php rename to src/Command/ValidateValueCommand.php diff --git a/Controller/PluginController.php b/src/Controller/PluginController.php similarity index 100% rename from Controller/PluginController.php rename to src/Controller/PluginController.php diff --git a/Controller/SearchController.php b/src/Controller/SearchController.php similarity index 100% rename from Controller/SearchController.php rename to src/Controller/SearchController.php diff --git a/Entity/CronjobLog.php b/src/Entity/CronjobLog.php similarity index 100% rename from Entity/CronjobLog.php rename to src/Entity/CronjobLog.php diff --git a/Service/AuthenticationService.php b/src/Service/AuthenticationService.php similarity index 100% rename from Service/AuthenticationService.php rename to src/Service/AuthenticationService.php diff --git a/Service/CacheService.php b/src/Service/CacheService.php similarity index 100% rename from Service/CacheService.php rename to src/Service/CacheService.php diff --git a/Service/CallService.php b/src/Service/CallService.php similarity index 100% rename from Service/CallService.php rename to src/Service/CallService.php diff --git a/Service/ComposerService.php b/src/Service/ComposerService.php similarity index 100% rename from Service/ComposerService.php rename to src/Service/ComposerService.php diff --git a/Service/EavService.php b/src/Service/EavService.php similarity index 100% rename from Service/EavService.php rename to src/Service/EavService.php diff --git a/Service/EndpointService.php b/src/Service/EndpointService.php similarity index 100% rename from Service/EndpointService.php rename to src/Service/EndpointService.php diff --git a/Service/FileService.php b/src/Service/FileService.php similarity index 100% rename from Service/FileService.php rename to src/Service/FileService.php diff --git a/Service/GatewayResourceService.php b/src/Service/GatewayResourceService.php similarity index 100% rename from Service/GatewayResourceService.php rename to src/Service/GatewayResourceService.php diff --git a/Service/InstallationService.php b/src/Service/InstallationService.php similarity index 100% rename from Service/InstallationService.php rename to src/Service/InstallationService.php diff --git a/Service/MappingService.php b/src/Service/MappingService.php similarity index 100% rename from Service/MappingService.php rename to src/Service/MappingService.php diff --git a/Service/OasService.php b/src/Service/OasService.php similarity index 100% rename from Service/OasService.php rename to src/Service/OasService.php diff --git a/Service/RequestService.php b/src/Service/RequestService.php similarity index 100% rename from Service/RequestService.php rename to src/Service/RequestService.php diff --git a/Service/SchemaService.php b/src/Service/SchemaService.php similarity index 100% rename from Service/SchemaService.php rename to src/Service/SchemaService.php diff --git a/Subscriber/CacheDatabaseSubscriber.php b/src/Subscriber/CacheDatabaseSubscriber.php similarity index 100% rename from Subscriber/CacheDatabaseSubscriber.php rename to src/Subscriber/CacheDatabaseSubscriber.php diff --git a/Subscriber/DoctrineToGatewayEventSubscriber.php b/src/Subscriber/DoctrineToGatewayEventSubscriber.php similarity index 100% rename from Subscriber/DoctrineToGatewayEventSubscriber.php rename to src/Subscriber/DoctrineToGatewayEventSubscriber.php diff --git a/Subscriber/ObjectReferenceSubscriber.php b/src/Subscriber/ObjectReferenceSubscriber.php similarity index 100% rename from Subscriber/ObjectReferenceSubscriber.php rename to src/Subscriber/ObjectReferenceSubscriber.php diff --git a/Subscriber/ObjectUriSubscriber.php b/src/Subscriber/ObjectUriSubscriber.php similarity index 100% rename from Subscriber/ObjectUriSubscriber.php rename to src/Subscriber/ObjectUriSubscriber.php From 610f1d6d3c98770bc84cf2c0ea7a2dbd2f965eb6 Mon Sep 17 00:00:00 2001 From: Ruben van der Linde Date: Wed, 22 Mar 2023 07:36:10 +0100 Subject: [PATCH 2/7] Sniff fix --- .phpcs.xml | 1 - 1 file changed, 1 deletion(-) diff --git a/.phpcs.xml b/.phpcs.xml index 94c18da8..d1faa5c7 100644 --- a/.phpcs.xml +++ b/.phpcs.xml @@ -47,7 +47,6 @@ - From 747cf75b5a5514d51fa7765abc5e7fdc72006076 Mon Sep 17 00:00:00 2001 From: GitHub Actions <> Date: Wed, 22 Mar 2023 06:36:41 +0000 Subject: [PATCH 3/7] Update src from PHP Codesniffer --- src/Command/CacheCleanupCommand.php | 18 +- src/Command/CacheClearCommand.php | 18 +- src/Command/CacheCommand.php | 18 +- src/Command/CacheWarmupCommand.php | 18 +- src/Command/ComposerUpdateCommand.php | 26 +- src/Command/DataClearCommand.php | 46 +- src/Command/EavClearCommand.php | 17 +- src/Command/InstallCommand.php | 18 +- src/Command/UninstallCommand.php | 22 +- src/Command/UpgradeCommand.php | 22 +- src/Command/ValidateObjectCommand.php | 18 +- src/Command/ValidateSchemaCommand.php | 18 +- src/Command/ValidateValueCommand.php | 18 +- src/Controller/PluginController.php | 43 +- src/Controller/SearchController.php | 21 +- src/Entity/CronjobLog.php | 9 +- src/Service/AuthenticationService.php | 226 ++++--- src/Service/CacheService.php | 403 +++++++----- src/Service/CallService.php | 238 ++++--- src/Service/ComposerService.php | 534 +++++++++------- src/Service/EavService.php | 33 +- src/Service/EndpointService.php | 99 +-- src/Service/FileService.php | 13 +- src/Service/GatewayResourceService.php | 29 +- src/Service/InstallationService.php | 430 ++++++++----- src/Service/MappingService.php | 105 +-- src/Service/OasService.php | 50 +- src/Service/RequestService.php | 598 ++++++++++-------- src/Service/SchemaService.php | 41 +- src/Subscriber/CacheDatabaseSubscriber.php | 36 +- .../DoctrineToGatewayEventSubscriber.php | 93 ++- src/Subscriber/ObjectReferenceSubscriber.php | 37 +- src/Subscriber/ObjectUriSubscriber.php | 25 +- 33 files changed, 2055 insertions(+), 1285 deletions(-) diff --git a/src/Command/CacheCleanupCommand.php b/src/Command/CacheCleanupCommand.php index 81007072..55622ae9 100644 --- a/src/Command/CacheCleanupCommand.php +++ b/src/Command/CacheCleanupCommand.php @@ -17,26 +17,36 @@ */ class CacheCleanupCommand extends Command { + protected static $defaultName = 'commongateway:cache:cleanup'; + private $cacheService; + public function __construct(CacheService $cacheService) { $this->cacheService = $cacheService; parent::__construct(); - } + + }//end __construct() + protected function configure(): void { $this ->setDescription('This command removes outdated objects from the cache') ->setHelp('This command allows you to run further installation an configuration actions afther installing a plugin'); - } + + }//end configure() + protected function execute(InputInterface $input, OutputInterface $output): int { $this->cacheService->setStyle(new SymfonyStyle($input, $output)); return $this->cacheService->cleanup(); - } -} + + }//end execute() + + +}//end class diff --git a/src/Command/CacheClearCommand.php b/src/Command/CacheClearCommand.php index 53ba853e..fa3d379f 100644 --- a/src/Command/CacheClearCommand.php +++ b/src/Command/CacheClearCommand.php @@ -17,26 +17,36 @@ */ class CacheClearCommand extends Command { + protected static $defaultName = 'commongateway:cache:clear'; + private $cacheService; + public function __construct(CacheService $cacheService) { $this->cacheService = $cacheService; parent::__construct(); - } + + }//end __construct() + protected function configure(): void { $this ->setDescription('This command removes all objects from the cache') ->setHelp('This command allows you to run further installation an configuration actions afther installing a plugin'); - } + + }//end configure() + protected function execute(InputInterface $input, OutputInterface $output): int { $this->cacheService->setStyle(new SymfonyStyle($input, $output)); return $this->cacheService->clear(); - } -} + + }//end execute() + + +}//end class diff --git a/src/Command/CacheCommand.php b/src/Command/CacheCommand.php index 57dda3da..3b98ce88 100644 --- a/src/Command/CacheCommand.php +++ b/src/Command/CacheCommand.php @@ -17,26 +17,36 @@ */ class CacheCommand extends Command { + protected static $defaultName = 'commongateway:cache:warmup'; + private $cacheService; + public function __construct(CacheService $cacheService) { $this->cacheService = $cacheService; parent::__construct(); - } + + }//end __construct() + protected function configure(): void { $this ->setDescription('This command puts all objects into the cache') ->setHelp('This command allows you to run further installation an configuration actions afther installing a plugin'); - } + + }//end configure() + protected function execute(InputInterface $input, OutputInterface $output): int { $this->cacheService->setStyle(new SymfonyStyle($input, $output)); return $this->cacheService->warmup(); - } -} + + }//end execute() + + +}//end class diff --git a/src/Command/CacheWarmupCommand.php b/src/Command/CacheWarmupCommand.php index 5f87bdff..89d87227 100644 --- a/src/Command/CacheWarmupCommand.php +++ b/src/Command/CacheWarmupCommand.php @@ -17,26 +17,36 @@ */ class CacheWarmupCommand extends Command { + protected static $defaultName = 'commongateway:cache:warmup'; + private $cacheService; + public function __construct(CacheService $cacheService) { $this->cacheService = $cacheService; parent::__construct(); - } + + }//end __construct() + protected function configure(): void { $this ->setDescription('This command puts all objects into the cache') ->setHelp('This command allows you to run further installation an configuration actions afther installing a plugin'); - } + + }//end configure() + protected function execute(InputInterface $input, OutputInterface $output): int { $this->cacheService->setStyle(new SymfonyStyle($input, $output)); return $this->cacheService->warmup(); - } -} + + }//end execute() + + +}//end class diff --git a/src/Command/ComposerUpdateCommand.php b/src/Command/ComposerUpdateCommand.php index 7262b33c..0069d3af 100644 --- a/src/Command/ComposerUpdateCommand.php +++ b/src/Command/ComposerUpdateCommand.php @@ -18,14 +18,19 @@ */ class ComposerUpdateCommand extends Command { + protected static $defaultName = 'commongateway:composer:update'; + private $installationService; + public function __construct(InstallationService $installationService) { $this->installationService = $installationService; parent::__construct(); - } + + }//end __construct() + protected function configure(): void { @@ -37,18 +42,23 @@ protected function configure(): void ->addOption('unsafe', 'u', InputOption::VALUE_OPTIONAL, 'Update existing schema\'s and data sets', false) ->setDescription('This command runs the installation service on a commongateway bundle') ->setHelp('This command allows you to run further installation an configuration actions afther installing a plugin'); - } + + }//end configure() + protected function execute(InputInterface $input, OutputInterface $output): int { $this->installationService->setStyle(new SymfonyStyle($input, $output)); - $bundle = $input->getOption('bundle'); - $data = $input->getOption('data'); + $bundle = $input->getOption('bundle'); + $data = $input->getOption('data'); $noSchema = $input->getOption('schema'); - $script = $input->getOption('script'); - $unsafe = $input->getOption('unsafe'); + $script = $input->getOption('script'); + $unsafe = $input->getOption('unsafe'); return $this->installationService->composerupdate(); - } -} + + }//end execute() + + +}//end class diff --git a/src/Command/DataClearCommand.php b/src/Command/DataClearCommand.php index f9466040..8d10104b 100644 --- a/src/Command/DataClearCommand.php +++ b/src/Command/DataClearCommand.php @@ -20,43 +20,54 @@ */ class DataClearCommand extends Command { + protected static $defaultName = 'commongateway:data:clear'; + private $cacheService; + private EntityManagerInterface $entityManagerInterface; + private ParameterBagInterface $parameterBagInterface; + public function __construct( CacheService $cacheService, EntityManagerInterface $entityManagerInterface, ParameterBagInterface $parameterBagInterface ) { - $this->cacheService = $cacheService; - $this->entitymanager = $entityManagerInterface; + $this->cacheService = $cacheService; + $this->entitymanager = $entityManagerInterface; $this->parameterBagInterface = $parameterBagInterface; parent::__construct(); - } + + }//end __construct() + protected function configure(): void { $this ->setDescription('This command removes all objects from the datbase') ->setHelp('use with care, or better don\'t use at all'); - } + + }//end configure() + protected function execute(InputInterface $input, OutputInterface $output): int { $env = $this->parameterBagInterface->get('app_env'); - $io = new SymfonyStyle($input, $output); - - $io->writeln([ - '', - 'Common Gateway Data Remover', - '============', - '', - 'Trying to remove all data from environment: '.$env.' ', - '', - ]); + $io = new SymfonyStyle($input, $output); + + $io->writeln( + [ + '', + 'Common Gateway Data Remover', + '============', + '', + 'Trying to remove all data from environment: '.$env.' ', + '', + ] + ); if ($env != 'dev') { $io->error('Could not remove the data bescouse the environment is not in dev mode'); @@ -90,5 +101,8 @@ protected function execute(InputInterface $input, OutputInterface $output): int $io->success('All done'); return Command::SUCCESS; - } -} + + }//end execute() + + +}//end class diff --git a/src/Command/EavClearCommand.php b/src/Command/EavClearCommand.php index f6318334..a18d2588 100644 --- a/src/Command/EavClearCommand.php +++ b/src/Command/EavClearCommand.php @@ -16,6 +16,7 @@ */ class EavClearCommand extends Command { + /** * @var string */ @@ -26,6 +27,7 @@ class EavClearCommand extends Command */ private EavService $eavService; + /** * @param EavService $eavService The eav Service */ @@ -33,7 +35,9 @@ public function __construct(EavService $eavService) { $this->eavService = $eavService; parent::__construct(); - } + + }//end __construct() + /** * @return void @@ -43,7 +47,9 @@ protected function configure(): void $this ->setDescription('This command removes all objects from the database') ->setHelp('Removes ALL EAV objects from the database and should not be used on production. It will however leave common gateway objects (suchs as schemes untuched)'); - } + + }//end configure() + /** * @param InputInterface $input @@ -54,5 +60,8 @@ protected function configure(): void protected function execute(InputInterface $input, OutputInterface $output): int { return $this->eavService->deleteAllObjects(); - } -} + + }//end execute() + + +}//end class diff --git a/src/Command/InstallCommand.php b/src/Command/InstallCommand.php index 471298a0..801ddaca 100644 --- a/src/Command/InstallCommand.php +++ b/src/Command/InstallCommand.php @@ -18,14 +18,19 @@ */ class InstallCommand extends Command { + protected static $defaultName = 'commongateway:install'; + private $installationService; + public function __construct(InstallationService $installationService) { $this->installationService = $installationService; parent::__construct(); - } + + }//end __construct() + protected function configure(): void { @@ -37,7 +42,9 @@ protected function configure(): void ->addOption('unsafe', 'u', InputOption::VALUE_OPTIONAL, 'Update existing schema\'s and data sets', false) ->setDescription('This command runs the installation service on a commongateway bundle') ->setHelp('This command allows you to run further installation an configuration actions afther installing a plugin'); - } + + }//end configure() + protected function execute(InputInterface $input, OutputInterface $output): int { @@ -51,5 +58,8 @@ protected function execute(InputInterface $input, OutputInterface $output): int ]; return $this->installationService->install($bundle, $options); - } -} + + }//end execute() + + +}//end class diff --git a/src/Command/UninstallCommand.php b/src/Command/UninstallCommand.php index 06d4897d..c7688d20 100644 --- a/src/Command/UninstallCommand.php +++ b/src/Command/UninstallCommand.php @@ -19,15 +19,20 @@ */ class UninstallCommand extends Command { + protected static $defaultName = 'commongateway:uninstall'; + private InstallationService $installationService; + public function __construct(InstallationService $installationService) { $this->installationService = $installationService; parent::__construct(); - } + + }//end __construct() + protected function configure(): void { @@ -37,17 +42,22 @@ protected function configure(): void ->addOption('--data', null, InputOption::VALUE_NONE, 'Also remove orphaned data') ->setDescription('This command runs the uninstall service on a commongateway bundle') ->setHelp('This command allows you to create a OAS files for your EAV entities'); - } + + }//end configure() + protected function execute(InputInterface $input, OutputInterface $output): int { - $io = new SymfonyStyle($input, $output); + $io = new SymfonyStyle($input, $output); $bundle = $input->getArgument('bundle'); - $data = $input->getArgument('data'); + $data = $input->getArgument('data'); $schema = $input->getOption('--no-schema'); return $this->installationService->uninstall($io, $bundle, $data, $schema); return Command::SUCCESS; - } -} + + }//end execute() + + +}//end class diff --git a/src/Command/UpgradeCommand.php b/src/Command/UpgradeCommand.php index bedb3ffc..2edda333 100644 --- a/src/Command/UpgradeCommand.php +++ b/src/Command/UpgradeCommand.php @@ -19,15 +19,20 @@ */ class UpgradeCommand extends Command { + protected static $defaultName = 'commongateway:upgrade'; + private InstallationService $installationService; + public function __construct(InstallationService $installationService) { $this->installationService = $installationService; parent::__construct(); - } + + }//end __construct() + protected function configure(): void { @@ -37,15 +42,20 @@ protected function configure(): void ->addOption('--no-schema', null, InputOption::VALUE_NONE, 'Skipp the installation or update of the bundles schema\'s') ->setDescription('This command runs the upgrade service on a commongateway bundle') ->setHelp('This command allows you to create a OAS files for your EAV entities'); - } + + }//end configure() + protected function execute(InputInterface $input, OutputInterface $output): int { - $io = new SymfonyStyle($input, $output); + $io = new SymfonyStyle($input, $output); $bundle = $input->getArgument('bundle'); - $data = $input->getArgument('data'); + $data = $input->getArgument('data'); $schema = $input->getOption('--no-schema'); return $this->installationService->upgrade($io, $bundle, $data, $schema); - } -} + + }//end execute() + + +}//end class diff --git a/src/Command/ValidateObjectCommand.php b/src/Command/ValidateObjectCommand.php index 3d36324d..27c342cc 100644 --- a/src/Command/ValidateObjectCommand.php +++ b/src/Command/ValidateObjectCommand.php @@ -17,26 +17,36 @@ */ class ValidateObjectCommand extends Command { + protected static $defaultName = 'commongateway:validate:object'; + private $installationService; + public function __construct(InstallationService $installationService) { $this->installationService = $installationService; parent::__construct(); - } + + }//end __construct() + protected function configure(): void { $this ->setDescription('This command checks if there are known issues with created objects') ->setHelp('This command allows you to run further installation an configuration actions afther installing a plugin'); - } + + }//end configure() + protected function execute(InputInterface $input, OutputInterface $output): int { $this->installationService->setStyle(new SymfonyStyle($input, $output)); return $this->installationService->validateObjects(); - } -} + + }//end execute() + + +}//end class diff --git a/src/Command/ValidateSchemaCommand.php b/src/Command/ValidateSchemaCommand.php index 2128fad9..8f587f2e 100644 --- a/src/Command/ValidateSchemaCommand.php +++ b/src/Command/ValidateSchemaCommand.php @@ -17,26 +17,36 @@ */ class ValidateSchemaCommand extends Command { + protected static $defaultName = 'commongateway:validate:schema'; + private $installationService; + public function __construct(InstallationService $installationService) { $this->installationService = $installationService; parent::__construct(); - } + + }//end __construct() + protected function configure(): void { $this ->setDescription('This command checks if there are known issues with installed schemas') ->setHelp('This command allows you to run further installation an configuration actions afther installing a plugin'); - } + + }//end configure() + protected function execute(InputInterface $input, OutputInterface $output): int { $this->installationService->setStyle(new SymfonyStyle($input, $output)); return $this->installationService->validateSchemas(); - } -} + + }//end execute() + + +}//end class diff --git a/src/Command/ValidateValueCommand.php b/src/Command/ValidateValueCommand.php index d236afc5..33f5a260 100644 --- a/src/Command/ValidateValueCommand.php +++ b/src/Command/ValidateValueCommand.php @@ -17,26 +17,36 @@ */ class ValidateValueCommand extends Command { + protected static $defaultName = 'commongateway:validate:value'; + private $installationService; + public function __construct(InstallationService $installationService) { $this->installationService = $installationService; parent::__construct(); - } + + }//end __construct() + protected function configure(): void { $this ->setDescription('This command checks if there are known issues with created objects') ->setHelp('This command allows you to run further installation an configuration actions afther installing a plugin'); - } + + }//end configure() + protected function execute(InputInterface $input, OutputInterface $output): int { $this->installationService->setStyle(new SymfonyStyle($input, $output)); return $this->installationService->validateValues(); - } -} + + }//end execute() + + +}//end class diff --git a/src/Controller/PluginController.php b/src/Controller/PluginController.php index 00f1c53b..fb6923dc 100644 --- a/src/Controller/PluginController.php +++ b/src/Controller/PluginController.php @@ -1,7 +1,6 @@ composerService = $composerService; - } + + }//end __construct() + /** * @Route("/installed", methods={"GET"}) */ public function installedAction(Request $request) { - $status = 200; + $status = 200; $plugins = $this->composerService->getAll(['--installed'])['installed']; return new Response(json_encode($plugins), $status, ['Content-type' => 'application/json']); - } + + }//end installedAction() + /** * @Route("/audit", methods={"GET"}) */ public function auditAction(Request $request) { - $status = 200; + $status = 200; $plugins = $this->composerService->audit(['--format=json']); return new Response(json_encode($plugins), $status, ['Content-type' => 'application/json']); - } + + }//end auditAction() + /** * @Route("/available", methods={"GET"}) @@ -59,7 +65,9 @@ public function availableAction(Request $request) $plugins = $this->composerService->search($search, ['--type=common-gateway-plugin']); return new Response(json_encode($plugins), $status, ['Content-type' => 'application/json']); - } + + }//end availableAction() + /** * @Route("/view", methods={"GET"}) @@ -73,7 +81,9 @@ public function viewAction(Request $request) $plugins = $this->composerService->getSingle($packadge); return new Response(json_encode($plugins), $status, ['Content-type' => 'application/json']); - } + + }//end viewAction() + /** * @Route("/installl", methods={"POST"}) @@ -89,7 +99,9 @@ public function installlAction(Request $request) $plugins = $this->composerService->require($packadge); return new Response(json_encode($plugins), $status, ['Content-type' => 'application/json']); - } + + }//end installlAction() + /** * @Route("/upgrade", methods={"POST"}) @@ -105,7 +117,9 @@ public function upgradeAction(Request $request) $plugins = $this->composerService->upgrade($packadge); return new Response(json_encode($plugins), $status, ['Content-type' => 'application/json']); - } + + }//end upgradeAction() + /** * @Route("/remove", methods={"POST"}) @@ -121,5 +135,8 @@ public function removeAction(Request $request) $plugins = $this->composerService->remove($packadge); return new Response(json_encode($plugins), $status, ['Content-type' => 'application/json']); - } -} + + }//end removeAction() + + +}//end class diff --git a/src/Controller/SearchController.php b/src/Controller/SearchController.php index 99414c8f..e209395d 100644 --- a/src/Controller/SearchController.php +++ b/src/Controller/SearchController.php @@ -1,7 +1,6 @@ cacheService = $cacheService; - } + + }//end __construct() + /** * @Route("/", methods={"GET"}) */ public function installedAction(Request $request) { - $status = 200; - $results = ['bla']; //$this->cacheService->getAll(['--installed'])['installed']; - + $status = 200; + $results = ['bla']; + // $this->cacheService->getAll(['--installed'])['installed']; return new Response(json_encode($plugins), $status, ['Content-type' => 'application/json']); - } -} + + }//end installedAction() + + +}//end class diff --git a/src/Entity/CronjobLog.php b/src/Entity/CronjobLog.php index ccce3ef5..8bd901ce 100644 --- a/src/Entity/CronjobLog.php +++ b/src/Entity/CronjobLog.php @@ -12,6 +12,7 @@ */ class CronjobLog { + /** * @ORM\Id * @@ -21,8 +22,12 @@ class CronjobLog */ private $id; + public function getId(): ?int { return $this->id; - } -} + + }//end getId() + + +}//end class diff --git a/src/Service/AuthenticationService.php b/src/Service/AuthenticationService.php index 20752ad2..91ad73de 100644 --- a/src/Service/AuthenticationService.php +++ b/src/Service/AuthenticationService.php @@ -36,14 +36,19 @@ */ class AuthenticationService { + private ParameterBagInterface $parameterBag; + private FileService $fileService; + public function __construct(ParameterBagInterface $parameterBag) { $this->parameterBag = $parameterBag; - $this->fileService = new FileService(); - } + $this->fileService = new FileService(); + + }//end __construct() + /** * Converts a string RSA key to a JWK via the filesystem. @@ -55,14 +60,16 @@ public function __construct(ParameterBagInterface $parameterBag) public function convertRSAKeyToJWK(string $key): JWK { $filesystem = new Filesystem(); - $filename = '/srv/api/var/privatekey'.microtime().getmypid(); + $filename = '/srv/api/var/privatekey'.microtime().getmypid(); $filesystem->dumpFile($filename, $key); $jwk = JWKFactory::createFromKeyFile($filename, null, ['use' => 'sig']); $filesystem->remove([$filename]); return $jwk; + }//end convertRSAKeyToJWK() + /** * Converts a RSA private key to a JWK. * @@ -79,19 +86,20 @@ public function convertRSAtoJWK(Source $source): JWK } else { $rsa = base64_decode($this->parameterBag->get('jwt.privateKey')); }//end if + $filename = $this->fileService->writeFile('privateKey', $rsa); - $jwk = JWKFactory::createFromKeyFile( + $jwk = JWKFactory::createFromKeyFile( $filename, null, - [ - 'use' => 'sig', - ] + ['use' => 'sig'] ); $this->fileService->removeFile($filename); return $jwk; + }//end convertRSAtoJWK() + /** * Determines the algorithm for the JWT token to create from the source. * @@ -106,8 +114,10 @@ public function getAlgorithm(Source $source): string } else { return 'RS512'; } + }//end getAlgorithm() + /** * Gets a JWK for a source based on the algorithm of the source. * @@ -119,15 +129,19 @@ public function getAlgorithm(Source $source): string public function getJWK(string $algorithm, Source $source): JWK { if ($algorithm == 'HS256') { - return new JWK([ - 'kty' => 'oct', - 'k' => base64_encode(addslashes($source->getSecret())), - ]); + return new JWK( + [ + 'kty' => 'oct', + 'k' => base64_encode(addslashes($source->getSecret())), + ] + ); } else { return $this->convertRSAtoJWK($source); } + }//end getJWK() + /** * Gets an application id for a source. * @@ -142,8 +156,10 @@ public function getApplicationId(Source $source): string } else { return $source->getId(); } + }//end getApplicationId() + /** * Creates the JWT payload to identify at an external source. * @@ -153,18 +169,22 @@ public function getApplicationId(Source $source): string */ public function getJwtPayload(Source $source): string { - $now = new DateTime('now'); + $now = new DateTime('now'); $clientId = $this->getApplicationId($source); - return json_encode([ - 'iss' => $clientId, - 'iat' => $now->getTimestamp(), - 'client_id' => $clientId, - 'user_id' => $this->parameterBag->get('app_name'), - 'user_representation' => $this->parameterBag->get('app_name'), - ]); + return json_encode( + [ + 'iss' => $clientId, + 'iat' => $now->getTimestamp(), + 'client_id' => $clientId, + 'user_id' => $this->parameterBag->get('app_name'), + 'user_representation' => $this->parameterBag->get('app_name'), + ] + ); + }//end getJwtPayload() + /** * Creates a JWT token to identify with on the application. * @@ -178,11 +198,11 @@ public function getJwtPayload(Source $source): string public function createJwtToken(string $key, array $payload): string { $algorithmManager = new AlgorithmManager([new RS512()]); - $jwsBuilder = new JWSBuilder($algorithmManager); + $jwsBuilder = new JWSBuilder($algorithmManager); $jwk = $this->convertRSAKeytoJWK($key); - $jws = $jwsBuilder + $jws = $jwsBuilder ->create() ->withPayload(json_encode($payload)) ->addSignature($jwk, ['alg' => 'RS512']) @@ -190,8 +210,10 @@ public function createJwtToken(string $key, array $payload): string $jwsSerializer = new CompactSerializer(); return $jwsSerializer->serialize($jws, 0); + }//end createJwtToken() + /** * Create a JWT token from Component settings. * @@ -202,12 +224,12 @@ public function createJwtToken(string $key, array $payload): string public function getJwtToken(Source $source): string { $algorithmManager = new AlgorithmManager([new HS256(), new RS512()]); - $algorithm = $this->getAlgorithm($source); - $jwsBuilder = new JWSBuilder($algorithmManager); + $algorithm = $this->getAlgorithm($source); + $jwsBuilder = new JWSBuilder($algorithmManager); - $jwk = $this->getJWK($algorithm, $source); + $jwk = $this->getJWK($algorithm, $source); $clientId = $this->getApplicationId($source); - $payload = $this->getJwtPayload($source); + $payload = $this->getJwtPayload($source); $jws = $jwsBuilder ->create() @@ -218,8 +240,10 @@ public function getJwtToken(Source $source): string $jwsSerializer = new CompactSerializer(); return $jwsSerializer->serialize($jws, 0); + }//end getJwtToken() + /** * Writes the certificate and ssl keys to disk, returns the filenames. * @@ -233,16 +257,20 @@ public function getCertificate(array $config): array if (isset($config['cert'])) { $configs['cert'] = $this->fileService->writeFile('certificate', $config['cert']); } + if (isset($config['ssl_key'])) { $configs['ssl_key'] = $this->fileService->writeFile('privateKey', $config['ssl_key']); } + if (isset($config['verify']) && is_string($config['verify'])) { $configs['verify'] = $this->fileService->writeFile('verify', $config['ssl_key']); } return $configs; + }//end getCertificate() + /** * Removes certificates and private keys from disk if they are not necessary anymore. * @@ -255,97 +283,116 @@ public function removeFiles(array $config): void if (isset($config['cert'])) { $this->fileService->removeFile($config['cert']); } + if (isset($config['ssl_key'])) { $this->fileService->removeFile($config['ssl_key']); } + if (isset($config['verify']) && is_string($config['verify'])) { $this->fileService->removeFile($config['verify']); } + }//end removeFiles() + public function getTokenFromUrl(Source $source): string { - $guzzleConfig = array_merge($source->getConfiguration(), [ - 'headers' => ['Content-Type' => 'application/x-www-form-urlencoded'], - 'auth' => [$source->getUsername(), $source->getPassword()], - ]); + $guzzleConfig = array_merge( + $source->getConfiguration(), + [ + 'headers' => ['Content-Type' => 'application/x-www-form-urlencoded'], + 'auth' => [ + $source->getUsername(), + $source->getPassword(), + ], + ] + ); $guzzleConfig = array_merge($guzzleConfig, $this->getCertificate($guzzleConfig)); $client = new Client($guzzleConfig); $response = $client->post($source->getLocation().'/oauth/token', ['form_params' => ['grant_type' => 'client_credentials', 'scope' => 'api']]); - $body = json_decode($response->getBody()->getContents(), true); + $body = json_decode($response->getBody()->getContents(), true); $this->removeFiles($guzzleConfig); return $body['access_token']; - } + + }//end getTokenFromUrl() + public function getHmacToken(array $requestOptions, Source $source): string { // todo: what if we don't have a body, method or url in $requestOptions? switch ($requestOptions['method']) { - case 'POST': - $md5 = md5($requestOptions['body'], true); - $post = base64_encode($md5); - break; - case 'GET': - default: - // todo: what about a get call? - $get = 'not a UTF-8 string'; - $post = base64_encode($get); - break; + case 'POST': + $md5 = md5($requestOptions['body'], true); + $post = base64_encode($md5); + break; + case 'GET': + default: + // todo: what about a get call? + $get = 'not a UTF-8 string'; + $post = base64_encode($get); + break; } $websiteKey = $source->getApikey(); - $uri = strtolower(urlencode($requestOptions['url'])); - $nonce = 'nonce_'.rand(0000000, 9999999); - $time = time(); + $uri = strtolower(urlencode($requestOptions['url'])); + $nonce = 'nonce_'.rand(0000000, 9999999); + $time = time(); $hmac = $websiteKey.$requestOptions['method'].$uri.$time.$nonce.$post; - $s = hash_hmac('sha256', $hmac, $source->getSecret(), true); + $s = hash_hmac('sha256', $hmac, $source->getSecret(), true); $hmac = base64_encode($s); return 'hmac '.$websiteKey.':'.$hmac.':'.$nonce.':'.$time; - } + + }//end getHmacToken() + public function getAuthentication(Source $source): array { $requestOptions = []; switch ($source->getAuth()) { - case 'jwt-HS256': - case 'jwt-RS512': - case 'jwt': - $requestOptions['headers']['Authorization'] = 'Bearer '.$this->getJwtToken($source); - break; - case 'username-password': - $requestOptions['auth'] = [$source->getUsername(), $source->getPassword()]; - break; - case 'vrijbrp-jwt': - $requestOptions['headers']['Authorization'] = "Bearer {$this->getTokenFromUrl($source)}"; - break; - case 'hmac': - $requestOptions['headers']['Authorization'] = $this->getHmacToken($requestOptions, $source); - break; - case 'apikey': - if ($source->getAuthorizationHeader()) { - switch ($source->getAuthorizationPassthroughMethod()) { - case 'query': - $requestOptions['query'][$source->getAuthorizationHeader()] = $source->getApiKey(); - break; - default: - $requestOptions['headers'][$source->getAuthorizationHeader()] = $source->getApiKey(); - break; - } - } else { - $requestOptions['headers']['Authorization'] = $source->getApiKey(); + case 'jwt-HS256': + case 'jwt-RS512': + case 'jwt': + $requestOptions['headers']['Authorization'] = 'Bearer '.$this->getJwtToken($source); + break; + case 'username-password': + $requestOptions['auth'] = [ + $source->getUsername(), + $source->getPassword(), + ]; + break; + case 'vrijbrp-jwt': + $requestOptions['headers']['Authorization'] = "Bearer {$this->getTokenFromUrl($source)}"; + break; + case 'hmac': + $requestOptions['headers']['Authorization'] = $this->getHmacToken($requestOptions, $source); + break; + case 'apikey': + if ($source->getAuthorizationHeader()) { + switch ($source->getAuthorizationPassthroughMethod()) { + case 'query': + $requestOptions['query'][$source->getAuthorizationHeader()] = $source->getApiKey(); + break; + default: + $requestOptions['headers'][$source->getAuthorizationHeader()] = $source->getApiKey(); + break; } - break; - default: - break; - } + } else { + $requestOptions['headers']['Authorization'] = $source->getApiKey(); + } + break; + default: + break; + }//end switch return $requestOptions; - } + + }//end getAuthentication() + /** * Decides if the provided JWT token is signed with the RS512 Algorithm. @@ -365,8 +412,10 @@ public function checkRS512(JWT $token) } catch (InvalidHeaderException $exception) { return false; } + }//end checkRS512() + /** * Decides if the provided JWT token is signed with the HS256 Algorithm. * @@ -385,8 +434,10 @@ public function checkHS256(JWT $token) } catch (InvalidHeaderException $exception) { return false; } + }//end checkHS256() + /** * Decides if the provided JWT token is signed with the HS256 Algorithm. * @@ -405,8 +456,10 @@ public function checkRS256(JWT $token) } catch (InvalidHeaderException $exception) { return false; } + }//end checkRS256() + /** * Checks the algorithm of the JWT token and decides how to generate a JWK from the provided public key. * @@ -427,17 +480,19 @@ public function checkHeadersAndGetJWK(JWT $token, string $publicKey): JWKSet if ($this->checkRS512($token)) { $publicKeyFile = $this->fileService->writeFile('publickey', $publicKey); - $jwk = new JWKSet([JWKFactory::createFromKeyFile($publicKeyFile, null, [])]); + $jwk = new JWKSet([JWKFactory::createFromKeyFile($publicKeyFile, null, [])]); $this->fileService->removeFile($publicKeyFile); return $jwk; - } elseif ($this->checkHS256($token)) { + } else if ($this->checkHS256($token)) { return new JWKSet([JWKFactory::createFromSecret($publicKey, ['alg' => 'HS256', 'use' => 'sig'])]); - } elseif ($this->checkRS256($token)) { + } else if ($this->checkRS256($token)) { return JWKFactory::createFromJsonObject($publicKey); } + }//end checkHeadersAndGetJWK() + /** * Verifies the JWT token and returns the payload if the JWT token is valid. * @@ -450,8 +505,8 @@ public function checkHeadersAndGetJWK(JWT $token, string $publicKey): JWKSet */ public function verifyJWTToken(string $token, string $publicKey): array { - $algorithmManager = new AlgorithmManager([new HS256(), new RS512(), new RS256()]); - $jwsVerifier = new JWSVerifier($algorithmManager); + $algorithmManager = new AlgorithmManager([new HS256(), new RS512(), new RS256()]); + $jwsVerifier = new JWSVerifier($algorithmManager); $serializerManager = new JWSSerializerManager([new CompactSerializer()]); $jws = $serializerManager->unserialize($token); @@ -462,8 +517,10 @@ public function verifyJWTToken(string $token, string $publicKey): array } else { throw new AuthenticationException('Unauthorized: The provided Authorization header is invalid', 401); } + }//end verifyJWTToken() + /** * Serializes a user to be used by the token authenticator. * @@ -474,7 +531,7 @@ public function verifyJWTToken(string $token, string $publicKey): array */ public function serializeUser(User $user, SessionInterface $session): array { - $time = new \DateTime(); + $time = new \DateTime(); $expiry = new \DateTime("+{$this->parameterBag->get('app_session_duration')} seconds"); $scopes = []; foreach ($user->getSecurityGroups() as $securityGroup) { @@ -495,5 +552,8 @@ public function serializeUser(User $user, SessionInterface $session): array ]; return $payload; + }//end serializeUser() + + }//end class diff --git a/src/Service/CacheService.php b/src/Service/CacheService.php index 442c7352..47ef37c9 100644 --- a/src/Service/CacheService.php +++ b/src/Service/CacheService.php @@ -32,13 +32,20 @@ */ class CacheService { + private Client $client; + private EntityManagerInterface $entityManager; + private CacheInterface $cache; + private SymfonyStyle $io; + private ParameterBagInterface $parameters; + private SerializerInterface $serializer; + /** * @param AuthenticationService $authenticationService * @param EntityManagerInterface $entityManager @@ -51,13 +58,15 @@ public function __construct( SerializerInterface $serializer ) { $this->entityManager = $entityManager; - $this->cache = $cache; - $this->parameters = $parameters; - $this->serializer = $serializer; + $this->cache = $cache; + $this->parameters = $parameters; + $this->serializer = $serializer; if ($this->parameters->get('cache_url', false)) { $this->client = new Client($this->parameters->get('cache_url')); } - } + + }//end __construct() + /** * Set symfony style in order to output to the console. @@ -71,36 +80,44 @@ public function setStyle(SymfonyStyle $io): self $this->io = $io; return $this; - } + + }//end setStyle() + /** * Remov non-exisitng items from the cashe. */ public function cleanup() { - isset($this->io) ? $this->io->writeln([ - 'Common Gateway Cache Cleanup', - '============', - '', - ]) : ''; + isset($this->io) ? $this->io->writeln( + [ + 'Common Gateway Cache Cleanup', + '============', + '', + ] + ) : ''; isset($this->io) ? $this->io->section('Cleaning Object\'s') : ''; $collection = $this->client->objects->json; - $filter = []; - $objects = $collection->find($filter)->toArray(); + $filter = []; + $objects = $collection->find($filter)->toArray(); isset($this->io) ? $this->io->writeln('Found '.count($objects).'') : ''; - } + + }//end cleanup() + /** * Throws all available objects into the cache. */ public function warmup() { - isset($this->io) ? $this->io->writeln([ - 'Common Gateway Cache Warmup', - '============', - '', - ]) : ''; + isset($this->io) ? $this->io->writeln( + [ + 'Common Gateway Cache Warmup', + '============', + '', + ] + ) : ''; isset($this->io) ? $this->io->writeln('Connecting to'.$this->parameters->get('cache_url')) : ''; @@ -154,9 +171,9 @@ public function warmup() } // Created indexes - $collection = $this->client->objects->json->createIndex(['$**'=>'text']); - $collection = $this->client->schemas->json->createIndex(['$**'=>'text']); - $collection = $this->client->endpoints->json->createIndex(['$**'=>'text']); + $collection = $this->client->objects->json->createIndex(['$**' => 'text']); + $collection = $this->client->schemas->json->createIndex(['$**' => 'text']); + $collection = $this->client->endpoints->json->createIndex(['$**' => 'text']); isset($this->io) ? $this->io->writeln(['Removing deleted endpoints', '============']) : ''; $this->removeDataFromCache($this->client->endpoints->json, 'App:Endpoint'); @@ -165,18 +182,22 @@ public function warmup() $this->removeDataFromCache($this->client->objects->json, 'App:ObjectEntity'); return Command::SUCCESS; - } + + }//end warmup() + private function removeDataFromCache(\MongoDB\Collection $collection, string $type): void { $endpoints = $collection->find()->toArray(); foreach ($endpoints as $endpoint) { if (!$this->entityManager->find($type, $endpoint['id'])) { - isset($this->io) ?? $this->io->writeln("removing {$endpoint['id']} from cache"); + (isset($this->io) ?? $this->io->writeln("removing {$endpoint['id']} from cache")); $collection->findOneAndDelete(['id' => $endpoint['id']]); } } - } + + }//end removeDataFromCache() + /** * Writes exception data to symfony IO. @@ -187,10 +208,12 @@ private function removeDataFromCache(\MongoDB\Collection $collection, string $ty */ private function ioCatchException(Exception $exception) { - isset($this->io) ?? $this->io->warning($exception->getMessage()); - isset($this->io) ?? $this->io->block("File: {$exception->getFile()}, Line: {$exception->getLine()}"); - isset($this->io) ?? $this->io->block("Trace: {$exception->getTraceAsString()}"); - } + (isset($this->io) ?? $this->io->warning($exception->getMessage())); + (isset($this->io) ?? $this->io->block("File: {$exception->getFile()}, Line: {$exception->getLine()}")); + (isset($this->io) ?? $this->io->block("Trace: {$exception->getTraceAsString()}")); + + }//end ioCatchException() + /** * Put a single object into the cache. @@ -219,7 +242,7 @@ public function cacheObject(ObjectEntity $objectEntity): ObjectEntity $updatedObjectEntity = $this->entityManager->getRepository('App:ObjectEntity')->findOneBy(['id' => $objectEntity->getId()->toString()]); if ($updatedObjectEntity !== null) { $objectEntity = $updatedObjectEntity; - } elseif (isset($this->io)) { + } else if (isset($this->io)) { $this->io->writeln('Could not find an ObjectEntity with id: '.$objectEntity->getId()->toString()); } @@ -228,8 +251,7 @@ public function cacheObject(ObjectEntity $objectEntity): ObjectEntity // Lets not cash the entire schema $array = $objectEntity->toArray(['embedded' => true]); - //(isset($array['_schema']['$id'])?$array['_schema'] = $array['_schema']['$id']:''); - + // (isset($array['_schema']['$id'])?$array['_schema'] = $array['_schema']['$id']:''); $id = $objectEntity->getId()->toString(); // Add an id field to main object only if the object not already has an id field. @@ -247,17 +269,20 @@ public function cacheObject(ObjectEntity $objectEntity): ObjectEntity } if ($collection->findOneAndReplace( - ['_id'=>$id], + ['_id' => $id], $array, - ['upsert'=> true] - )) { + ['upsert' => true] + ) + ) { isset($this->io) ? $this->io->writeln('Updated object '.$objectEntity->getId()->toString().' of type '.$objectEntity->getEntity()->getName().' to cache') : ''; } else { isset($this->io) ? $this->io->writeln('Wrote object '.$objectEntity->getId()->toString().' of type '.$objectEntity->getEntity()->getName().' to cache') : ''; } return $objectEntity; - } + + }//end cacheObject() + /** * Removes an object from the cache. @@ -273,11 +298,13 @@ public function removeObject(ObjectEntity $object): void return; } - $id = $object->getId()->toString(); + $id = $object->getId()->toString(); $collection = $this->client->objects->json; - $collection->findOneAndDelete(['_id'=>$id]); - } + $collection->findOneAndDelete(['_id' => $id]); + + }//end removeObject() + /** * Get a single object from the cache. @@ -296,17 +323,19 @@ public function getObject(string $id): ?array $collection = $this->client->objects->json; // Check if object is in the cache ???? - if ($object = $collection->findOne(['_id'=>$id])) { + if ($object = $collection->findOne(['_id' => $id])) { return json_decode(json_encode($object), true); } // Fall back tot the entity manager - if ($object = $this->entityManager->getRepository('App:ObjectEntity')->findOneBy(['id'=>$id])) { + if ($object = $this->entityManager->getRepository('App:ObjectEntity')->findOneBy(['id' => $id])) { return $this->cacheObject($object)->toArray(['embedded' => true]); } return null; - } + + }//end getObject() + /** * Searches the object store for objects containing the search string. @@ -319,7 +348,7 @@ public function getObject(string $id): ?array * * @return array|null */ - public function searchObjects(string $search = null, array $filter = [], array $entities = []): ?array + public function searchObjects(string $search=null, array $filter=[], array $entities=[]): ?array { // Backwards compatablity if (!isset($this->client)) { @@ -333,8 +362,16 @@ public function searchObjects(string $search = null, array $filter = [], array $ // Make sure we also have all filters stored in $completeFilter before unsetting $completeFilter = $filter; - unset($filter['_start'], $filter['_offset'], $filter['_limit'], $filter['_page'], - $filter['_extend'], $filter['_search'], $filter['_order'], $filter['_fields']); + unset( + $filter['_start'], + $filter['_offset'], + $filter['_limit'], + $filter['_page'], + $filter['_extend'], + $filter['_search'], + $filter['_order'], + $filter['_fields'] + ); // 'normal' Filters (not starting with _ ) foreach ($filter as $key => &$value) { @@ -346,20 +383,19 @@ public function searchObjects(string $search = null, array $filter = [], array $ if (!empty($entities)) { foreach ($entities as $entity) { // todo: disable this for now, put back later! -// $orderError = $this->handleOrderCheck($entity, $completeFilter['_order'] ?? null); -// $filterError = $this->handleFilterCheck($entity, $filter ?? null); -// if (!empty($orderError) || !empty($filterError)) { -// !empty($orderError) && $errorData['order'] = $orderError; -// !empty($filterError) && $errorData['filter'] = $filterError; -// return [ -// 'message' => 'There are some errors in your query parameters', -// 'type' => 'error', -// 'path' => $entity->getName(), -// 'data' => $errorData, -// ]; -// } - - //$filter['_self.schema.ref']='https://larping.nl/character.schema.json'; + // $orderError = $this->handleOrderCheck($entity, $completeFilter['_order'] ?? null); + // $filterError = $this->handleFilterCheck($entity, $filter ?? null); + // if (!empty($orderError) || !empty($filterError)) { + // !empty($orderError) && $errorData['order'] = $orderError; + // !empty($filterError) && $errorData['filter'] = $filterError; + // return [ + // 'message' => 'There are some errors in your query parameters', + // 'type' => 'error', + // 'path' => $entity->getName(), + // 'data' => $errorData, + // ]; + // } + // $filter['_self.schema.ref']='https://larping.nl/character.schema.json'; $filter['_self.schema.id']['$in'][] = $entity; } } @@ -376,11 +412,13 @@ public function searchObjects(string $search = null, array $filter = [], array $ // Find / Search $results = $collection->find($filter, ['limit' => $limit, 'skip' => $start, 'sort' => $order])->toArray(); - $total = $collection->count($filter); + $total = $collection->count($filter); // Make sure to add the pagination properties in response return $this->handleResultPagination($completeFilter, $results, $total); - } + + }//end searchObjects() + /** * Make sure we still support the old query params. By translating them to the new ones with _. @@ -391,18 +429,28 @@ public function searchObjects(string $search = null, array $filter = [], array $ */ private function queryBackwardsCompatibility(array &$filter) { - !isset($filter['_limit']) && isset($filter['limit']) && $filter['_limit'] = $filter['limit']; - !isset($filter['_start']) && isset($filter['start']) && $filter['_start'] = $filter['start']; + !isset($filter['_limit']) && isset($filter['limit']) && $filter['_limit'] = $filter['limit']; + !isset($filter['_start']) && isset($filter['start']) && $filter['_start'] = $filter['start']; !isset($filter['_offset']) && isset($filter['offset']) && $filter['_offset'] = $filter['offset']; - !isset($filter['_page']) && isset($filter['page']) && $filter['_page'] = $filter['page']; + !isset($filter['_page']) && isset($filter['page']) && $filter['_page'] = $filter['page']; !isset($filter['_extend']) && isset($filter['extend']) && $filter['_extend'] = $filter['extend']; !isset($filter['_search']) && isset($filter['search']) && $filter['_search'] = $filter['search']; - !isset($filter['_order']) && isset($filter['order']) && $filter['_order'] = $filter['order']; + !isset($filter['_order']) && isset($filter['order']) && $filter['_order'] = $filter['order']; !isset($filter['_fields']) && isset($filter['fields']) && $filter['_fields'] = $filter['fields']; - unset($filter['start'], $filter['offset'], $filter['limit'], $filter['page'], - $filter['extend'], $filter['search'], $filter['order'], $filter['fields']); - } + unset( + $filter['start'], + $filter['offset'], + $filter['limit'], + $filter['page'], + $filter['extend'], + $filter['search'], + $filter['order'], + $filter['fields'] + ); + + }//end queryBackwardsCompatibility() + /** * Handles a single filter used on a get collection api call. This function makes sure special filters work correctly. @@ -433,11 +481,13 @@ private function handleFilter($key, &$value) return; } + if ($value === 'IS NOT NULL') { $value = ['$ne' => null]; return; } + if ($value === 'IS NULL' || $value === 'null') { $value = null; @@ -446,8 +496,13 @@ private function handleFilter($key, &$value) // todo: exact match is default, make case insensitive optional: $value = preg_replace('/([^A-Za-z0-9\s])/', '\\\\$1', $value); - $value = ['$regex' => "^$value$", '$options' => 'im']; - } + $value = [ + '$regex' => "^$value$", + '$options' => 'im', + ]; + + }//end handleFilter() + /** * Handles a single filter used on a get collection api call. Specifically an filter where the value is an array. @@ -466,104 +521,122 @@ private function handleFilterArray($key, &$value): bool // int_compare if (array_key_exists('int_compare', $value) && is_array($value['int_compare'])) { $value = array_map('intval', $value['int_compare']); - } elseif (array_key_exists('int_compare', $value)) { + } else if (array_key_exists('int_compare', $value)) { $value = (int) $value['int_compare']; return true; } + // bool_compare if (array_key_exists('bool_compare', $value) && is_array($value['bool_compare'])) { $value = array_map('boolval', $value['bool_compare']); - } elseif (array_key_exists('bool_compare', $value)) { + } else if (array_key_exists('bool_compare', $value)) { $value = (bool) $value['bool_compare']; return true; } + // after, before, strictly_after,strictly_before if (!empty(array_intersect_key($value, array_flip(['after', 'before', 'strictly_after', 'strictly_before'])))) { // Compare datetime if (!empty(array_intersect_key($value, array_flip(['after', 'strictly_after'])))) { - $after = array_key_exists('strictly_after', $value) ? 'strictly_after' : 'after'; + $after = array_key_exists('strictly_after', $value) ? 'strictly_after' : 'after'; $compareDate = new DateTime($value[$after]); - $compareKey = $after === 'strictly_after' ? '$gt' : '$gte'; + $compareKey = $after === 'strictly_after' ? '$gt' : '$gte'; } else { - $before = array_key_exists('strictly_before', $value) ? 'strictly_before' : 'before'; + $before = array_key_exists('strictly_before', $value) ? 'strictly_before' : 'before'; $compareDate = new DateTime($value[$before]); - $compareKey = $before === 'strictly_before' ? '$lt' : '$lte'; + $compareKey = $before === 'strictly_before' ? '$lt' : '$lte'; } + $value = ["$compareKey" => "{$compareDate->format('c')}"]; return true; } + // like if (array_key_exists('like', $value) && is_array($value['like'])) { - //$value = array_map('like', $value['like']); - } elseif (array_key_exists('like', $value)) { + // $value = array_map('like', $value['like']); + } else if (array_key_exists('like', $value)) { $value = preg_replace('/([^A-Za-z0-9\s])/', '\\\\$1', $value['like']); - $value = ['$regex' => ".*$value.*", '$options' => 'im']; + $value = [ + '$regex' => ".*$value.*", + '$options' => 'im', + ]; return true; } + // regex if (array_key_exists('regex', $value) && is_array($value['regex'])) { - //$value = array_map('like', $value['like']); @todo - } elseif (array_key_exists('regex', $value)) { - $value = ['$regex'=> $value['regex']]; + // $value = array_map('like', $value['like']); @todo + } else if (array_key_exists('regex', $value)) { + $value = ['$regex' => $value['regex']]; return true; } + // >= if (array_key_exists('>=', $value) && is_array($value['>='])) { - //$value = array_map('like', $value['like']); @todo - } elseif (array_key_exists('>=', $value)) { - $value = ['$gte'=> (int) $value['>=']]; + // $value = array_map('like', $value['like']); @todo + } else if (array_key_exists('>=', $value)) { + $value = ['$gte' => (int) $value['>=']]; return true; } + // > if (array_key_exists('>', $value) && is_array($value['>'])) { - //$value = array_map('like', $value['like']); @todo - } elseif (array_key_exists('>', $value)) { - $value = ['$gt'=> (int) $value['>']]; + // $value = array_map('like', $value['like']); @todo + } else if (array_key_exists('>', $value)) { + $value = ['$gt' => (int) $value['>']]; return true; } + // <= if (array_key_exists('<=', $value) && is_array($value['<='])) { - //$value = array_map('like', $value['like']); @todo - } elseif (array_key_exists('<=', $value)) { - $value = ['$lte'=> (int) $value['<=']]; + // $value = array_map('like', $value['like']); @todo + } else if (array_key_exists('<=', $value)) { + $value = ['$lte' => (int) $value['<=']]; return true; } + // < if (array_key_exists('<', $value) && is_array($value['<'])) { - //$value = array_map('like', $value['like']); @todo - } elseif (array_key_exists('<', $value)) { - $value = ['$lt'=> (int) $value['<']]; + // $value = array_map('like', $value['like']); @todo + } else if (array_key_exists('<', $value)) { + $value = ['$lt' => (int) $value['<']]; return true; } + // exact if (array_key_exists('exact', $value) && is_array($value['exact'])) { - //$value = array_map('like', $value['like']); @todo - } elseif (array_key_exists('exact', $value)) { + // $value = array_map('like', $value['like']); @todo + } else if (array_key_exists('exact', $value)) { $value = $value; return true; } + // case_insensitive if (array_key_exists('case_insensitive', $value) && is_array($value['case_insensitive'])) { - //$value = array_map('like', $value['like']); @todo - } elseif (array_key_exists('case_insensitive', $value)) { - $value = ['$regex' => $value['case_insensitive'], '$options' => 'i']; + // $value = array_map('like', $value['like']); @todo + } else if (array_key_exists('case_insensitive', $value)) { + $value = [ + '$regex' => $value['case_insensitive'], + '$options' => 'i', + ]; return true; } + // case_sensitive if (array_key_exists('case_sensitive', $value) && is_array($value['case_sensitive'])) { - //$value = array_map('like', $value['like']); @todo - } elseif (array_key_exists('case_sensitive', $value)) { + // $value = array_map('like', $value['like']); @todo + } else if (array_key_exists('case_sensitive', $value)) { $value = ['$regex' => $value['case_sensitive']]; return true; @@ -573,10 +646,12 @@ private function handleFilterArray($key, &$value): bool $value = ['$in' => $value]; return true; - } + }//end if return false; - } + + }//end handleFilterArray() + /** * Will check if we are allowed to order with the given $order query param. @@ -597,24 +672,30 @@ private function handleOrderCheck(Entity $entity, $order): ?string if (!is_array($order)) { $orderCheckStr = implode(', ', $orderCheck); - $message = 'Please give an attribute to order on. Like this: ?_order[attributeName]=desc/asc. Supported order query parameters: '.$orderCheckStr; + $message = 'Please give an attribute to order on. Like this: ?_order[attributeName]=desc/asc. Supported order query parameters: '.$orderCheckStr; } + if (is_array($order) && count($order) > 1) { $message = 'Only one order query param at the time is allowed.'; } + if (is_array($order) && !in_array(strtoupper(array_values($order)[0]), ['DESC', 'ASC'])) { $message = 'Please use desc or asc as value for your order query param, not: '.array_values($order)[0]; } + if (is_array($order) && !in_array(array_keys($order)[0], $orderCheck)) { $orderCheckStr = implode(', ', $orderCheck); - $message = 'Unsupported order query parameter ('.array_keys($order)[0].'). Supported order query parameters: '.$orderCheckStr; + $message = 'Unsupported order query parameter ('.array_keys($order)[0].'). Supported order query parameters: '.$orderCheckStr; } + if (isset($message)) { return $message; } return null; - } + + }//end handleOrderCheck() + /** * Will check if we are allowed to filter on the given $filters in the query params. @@ -638,6 +719,7 @@ private function handleFilterCheck(Entity $entity, ?array $filters): ?string $unsupportedParams = !isset($unsupportedParams) ? $param : "$unsupportedParams, $param"; } } + if (isset($unsupportedParams)) { $filterCheckStr = implode(', ', $filterCheck); @@ -645,7 +727,9 @@ private function handleFilterCheck(Entity $entity, ?array $filters): ?string } return null; - } + + }//end handleFilterCheck() + /** * Adds search filter to the query on MongoDB. Will use given $search string to search on entire object, unless @@ -663,6 +747,7 @@ private function handleSearch(array &$filter, array $completeFilter, ?string $se if (isset($completeFilter['_search']) && !empty($completeFilter['_search'])) { $search = $completeFilter['_search']; } + if (empty($search)) { return; } @@ -671,24 +756,30 @@ private function handleSearch(array &$filter, array $completeFilter, ?string $se if (is_string($search)) { $filter['$text'] = [ - '$search' => $search, - '$caseSensitive'=> false, + '$search' => $search, + '$caseSensitive' => false, ]; } // _search query with specific properties in the [method] like this: ?_search[property1,property2]=value - elseif (is_array($search)) { + else if (is_array($search)) { $searchRegex = preg_replace('/([^A-Za-z0-9\s])/', '\\\\$1', $search[array_key_first($search)]); if (empty($searchRegex)) { return; } - $searchRegex = ['$regex' => $searchRegex, '$options' => 'i']; - $properties = explode(',', array_key_first($search)); + + $searchRegex = [ + '$regex' => $searchRegex, + '$options' => 'i', + ]; + $properties = explode(',', array_key_first($search)); foreach ($properties as $property) { // todo: we might want to check if we are allowed to filter on this property? with $this->handleFilterCheck; $filter['$or'][][$property] = $searchRegex; } } - } + + }//end handleSearch() + /** * Decides the pagination values. @@ -706,16 +797,19 @@ public function setPagination(&$limit, &$start, array $filters): array } else { $limit = 30; } + if (isset($filters['_start']) || isset($filters['_offset'])) { $start = isset($filters['_start']) ? intval($filters['_start']) : intval($filters['_offset']); - } elseif (isset($filters['_page'])) { - $start = (intval($filters['_page']) - 1) * $limit; + } else if (isset($filters['_page'])) { + $start = ((intval($filters['_page']) - 1) * $limit); } else { $start = 0; } return $filters; - } + + }//end setPagination() + /** * Adds pagination variables to an array with the results we found with searchObjects(). @@ -726,18 +820,19 @@ public function setPagination(&$limit, &$start, array $filters): array * * @return array the result with pagination. */ - private function handleResultPagination(array $filter, array $results, int $total = 0): array + private function handleResultPagination(array $filter, array $results, int $total=0): array { $start = isset($filter['_start']) && is_numeric($filter['_start']) ? (int) $filter['_start'] : 0; $limit = isset($filter['_limit']) && is_numeric($filter['_limit']) ? (int) $filter['_limit'] : 30; - $page = isset($filter['_page']) && is_numeric($filter['_page']) ? (int) $filter['_page'] : 1; + $page = isset($filter['_page']) && is_numeric($filter['_page']) ? (int) $filter['_page'] : 1; // Lets build the page & pagination if ($start > 1) { - $offset = $start - 1; + $offset = ($start - 1); } else { - $offset = ($page - 1) * $limit; + $offset = (($page - 1) * $limit); } + $pages = ceil($total / $limit); return [ @@ -746,10 +841,12 @@ private function handleResultPagination(array $filter, array $results, int $tota 'limit' => $limit, 'total' => $total, 'offset' => $offset, - 'page' => floor($offset / $limit) + 1, + 'page' => (floor($offset / $limit) + 1), 'pages' => $pages == 0 ? 1 : $pages, ]; - } + + }//end handleResultPagination() + /** * Put a single endpoint into the cache. @@ -768,10 +865,11 @@ public function cacheEndpoint(Endpoint $endpoint): Endpoint if (isset($this->io)) { $this->io->writeln('Start caching endpoint '.$endpoint->getId()->toString().' with name: '.$endpoint->getName()); } + $updatedEndpoint = $this->entityManager->getRepository('App:Endpoint')->find($endpoint->getId()); if ($updatedEndpoint !== null) { $endpoint = $updatedEndpoint; - } elseif (isset($this->io)) { + } else if (isset($this->io)) { $this->io->writeln('Could not find an Endpoint with id: '.$endpoint->getId()->toString()); } @@ -782,15 +880,18 @@ public function cacheEndpoint(Endpoint $endpoint): Endpoint if ($collection->findOneAndReplace( ['id' => $endpoint->getId()->toString()], $endpointArray, - ['upsert'=> true] - )) { + ['upsert' => true] + ) + ) { isset($this->io) ? $this->io->writeln('Updated endpoint '.$endpoint->getId()->toString().' to cache') : ''; } else { isset($this->io) ? $this->io->writeln('Wrote object '.$endpoint->getId()->toString().' to cache') : ''; } return $endpoint; - } + + }//end cacheEndpoint() + /** * Removes an endpoint from the cache. @@ -809,7 +910,9 @@ public function removeEndpoint(Endpoint $endpoint): void $collection = $this->client->endpoints->json; $collection->findOneAndDelete(['id' => $endpoint->getId()->toString()]); - } + + }//end removeEndpoint() + /** * Get a single endpoint from the cache. @@ -836,7 +939,9 @@ public function getEndpoint(string $id): ?array } return null; - } + + }//end getEndpoint() + public function getEndpoints(array $filter): ?Endpoint { @@ -852,9 +957,13 @@ public function getEndpoints(array $filter): ?Endpoint $filter['$where'] = "\"$path\".match(this.pathRegex)"; unset($filter['path']); } + if (isset($filter['method'])) { - $method = $filter['method']; - $filter['$or'] = [['methods' => ['$in' => [$method]]], ['method' => $method]]; + $method = $filter['method']; + $filter['$or'] = [ + ['methods' => ['$in' => [$method]]], + ['method' => $method], + ]; unset($filter['method']); } @@ -862,13 +971,15 @@ public function getEndpoints(array $filter): ?Endpoint if (count($endpoints) > 1) { throw new NonUniqueResultException(); - } elseif (count($endpoints) == 1) { - //@TODO: We actually want to use the denormalizer, but that breaks on not setting ids + } else if (count($endpoints) == 1) { + // @TODO: We actually want to use the denormalizer, but that breaks on not setting ids return $this->entityManager->find('App\Entity\Endpoint', $endpoints[0]['id']); } else { return null; } - } + + }//end getEndpoints() + /** * Put a single schema into the cache. @@ -883,32 +994,35 @@ public function cacheShema(Entity $entity): Entity if (!isset($this->client)) { return $entity; } + $collection = $this->client->schemas->json; // Remap the array $array = $entity->toSchema(null); $array['reference'] = $array['$id']; - $array['schema'] = $array['$schema']; + $array['schema'] = $array['$schema']; unset($array['$id']); unset($array['$schema']); /* - var_dump($array); + var_dump($array); - if ($collection->findOneAndReplace( + if ($collection->findOneAndReplace( ['_id'=>$entity->getID()], $entity->toSchema(null), ['upsert'=>true] - )) { + )) { $this->io->writeln('Updated object '.$entity->getId().' to cache'); - } else { + } else { $this->io->writeln('Wrote object '.$entity->getId().' to cache'); - } + } */ return $entity; - } + + }//end cacheShema() + /** * Removes an Schema from the cache. @@ -925,7 +1039,9 @@ public function removeSchema(Entity $entity): void } $collection = $this->client->schemas->json; - } + + }//end removeSchema() + /** * Get a single schema from the cache. @@ -942,5 +1058,8 @@ public function getSchema(Uuid $id): ?array } $collection = $this->client->schemas->json; - } -} + + }//end getSchema() + + +}//end class diff --git a/src/Service/CallService.php b/src/Service/CallService.php index e782f236..e24c76d1 100644 --- a/src/Service/CallService.php +++ b/src/Service/CallService.php @@ -2,7 +2,7 @@ namespace CommonGateway\CoreBundle\Service; -//use App\Entity\CallLog; +// use App\Entity\CallLog; use App\Entity\Gateway as Source; use Doctrine\ORM\EntityManagerInterface; use GuzzleHttp\Client; @@ -32,14 +32,22 @@ */ class CallService { + private AuthenticationService $authenticationService; + private Client $client; + private EntityManagerInterface $entityManager; + private FileService $fileService; + private MappingService $mappingService; + private SessionInterface $session; + private LoggerInterface $logger; + /** * @param AuthenticationService $authenticationService * @param EntityManagerInterface $entityManager @@ -55,13 +63,15 @@ public function __construct( LoggerInterface $callLogger ) { $this->authenticationService = $authenticationService; - $this->client = new Client([]); - $this->entityManager = $entityManager; - $this->fileService = $fileService; + $this->client = new Client([]); + $this->entityManager = $entityManager; + $this->fileService = $fileService; $this->mappingService = $mappingService; - $this->session = $session; - $this->logger = $callLogger; - } + $this->session = $session; + $this->logger = $callLogger; + + }//end __construct() + /** * Writes the certificate and ssl keys to disk, returns the filenames. @@ -75,21 +85,25 @@ public function getCertificate(array &$config) if (isset($config['cert']) === true) { if (is_array($config['cert'])) { $config['cert'][0] = $this->fileService->writeFile('certificate', $config['cert'][0]); - } elseif (is_string($config['cert'])) { + } else if (is_string($config['cert'])) { $config['cert'] = $this->fileService->writeFile('certificate', $config['cert']); } } + if (isset($config['ssl_key']) === true) { if (is_array($config['ssl_key'])) { $config['ssl_key'][0] = $this->fileService->writeFile('privateKey', $config['ssl_key'][0]); - } elseif (is_string($config['ssl_key'])) { + } else if (is_string($config['ssl_key'])) { $config['ssl_key'] = $this->fileService->writeFile('privateKey', $config['ssl_key']); } } + if (isset($config['verify']) === true && is_string($config['verify']) === true) { $config['verify'] = $this->fileService->writeFile('verify', $config['verify']); } - } + + }//end getCertificate() + /** * Removes certificates and private keys from disk if they are not necessary anymore. @@ -104,14 +118,18 @@ public function removeFiles(array $config): void $filename = is_array($config['cert']) ? $config['cert'][0] : $config['cert']; $this->fileService->removeFile($filename); } + if (isset($config['ssl_key']) === true) { $filename = is_array($config['ssl_key']) ? $config['ssl_key'][0] : $config['ssl_key']; $this->fileService->removeFile($filename); } + if (isset($config['verify']) === true && is_string($config['verify']) === true) { $this->fileService->removeFile($config['verify']); } - } + + }//end removeFiles() + /** * Removes empty headers and sets array to string values. @@ -133,7 +151,9 @@ private function removeEmptyHeaders(array $headers): ?array } return $headers; - } + + }//end removeEmptyHeaders() + /** * Calls a source according to given configuration. @@ -149,11 +169,11 @@ private function removeEmptyHeaders(array $headers): ?array */ public function call( Source $source, - string $endpoint = '', - string $method = 'GET', - array $config = [], - bool $asynchronous = false, - bool $createCertificates = true + string $endpoint='', + string $method='GET', + array $config=[], + bool $asynchronous=false, + bool $createCertificates=true ): Response { $this->session->set('source', $source->getId()->toString()); $this->logger->info('Calling source '.$source->getName()); @@ -161,20 +181,21 @@ public function call( if (!$source->getIsEnabled()) { throw new HttpException('409', "This source is not enabled: {$source->getName()}"); } + if ($source->getConfiguration()) { $config = array_merge_recursive($config, $source->getConfiguration()); } -// $log = new CallLog(); -// $log->setSource($source); -// $log->setEndpoint($source->getLocation().$endpoint); -// $log->setMethod($method); -// $log->setConfig($config); -// $log->setRequestBody($config['body'] ?? null); - + // $log = new CallLog(); + // $log->setSource($source); + // $log->setEndpoint($source->getLocation().$endpoint); + // $log->setMethod($method); + // $log->setConfig($config); + // $log->setRequestBody($config['body'] ?? null); if (empty($source->getLocation())) { throw new HttpException('409', "This source has no location: {$source->getName()}"); } + if (isset($config['headers']) === false) { $config['headers'] = []; } @@ -184,11 +205,11 @@ public function call( // Set authentication if needed $config = array_merge_recursive($this->getAuthentication($source), $config); $createCertificates && $this->getCertificate($config); - $config['headers'] = array_merge($source->getHeaders() ?? [], $config['headers']); // Backwards compatible, $source->getHeaders = deprecated + $config['headers'] = array_merge(($source->getHeaders() ?? []), $config['headers']); + // Backwards compatible, $source->getHeaders = deprecated $config['headers']['host'] = $parsedUrl['host']; - $config['headers'] = $this->removeEmptyHeaders($config['headers']); -// $log->setRequestHeaders($config['headers'] ?? null); - + $config['headers'] = $this->removeEmptyHeaders($config['headers']); + // $log->setRequestHeaders($config['headers'] ?? null); $url = $source->getLocation().$endpoint; $this->logger->info('Calling url '.$url); @@ -204,22 +225,22 @@ public function call( } else { $response = $this->client->requestAsync($method, $url, $config); } - $this->logger->info("Request to $url succesful"); - } catch (ServerException|ClientException|RequestException|Exception $exception) { -// $stopTimer = microtime(true); -// $log->setResponseStatus(''); -// if ($e->getResponse()) { -// $log->setResponseStatusCode($e->getResponse()->getStatusCode()); -// $log->setResponseBody($e->getResponse()->getBody()->getContents()); -// $log->setResponseHeaders($e->getResponse()->getHeaders()); -// } else { -// $log->setResponseStatusCode(0); -// $log->setResponseBody($e->getMessage()); -// } -// $log->setResponseTime($stopTimer - $startTimer); -// $this->entityManager->persist($log); -// $this->entityManager->flush(); + $this->logger->info("Request to $url succesful"); + } catch (ServerException | ClientException | RequestException | Exception $exception) { + // $stopTimer = microtime(true); + // $log->setResponseStatus(''); + // if ($e->getResponse()) { + // $log->setResponseStatusCode($e->getResponse()->getStatusCode()); + // $log->setResponseBody($e->getResponse()->getBody()->getContents()); + // $log->setResponseHeaders($e->getResponse()->getHeaders()); + // } else { + // $log->setResponseStatusCode(0); + // $log->setResponseBody($e->getMessage()); + // } + // $log->setResponseTime($stopTimer - $startTimer); + // $this->entityManager->persist($log); + // $this->entityManager->flush(); $this->logger->error('Request failed with error '.$exception->getMessage().' and body '.$exception->getResponse()->getBody()->getContents()); throw $exception; @@ -227,25 +248,26 @@ public function call( $this->logger->error('Request failed with error '.$exception); throw $exception; - } -// $stopTimer = microtime(true); -// -// $responseClone = clone $response; -// -// $log->setResponseHeaders($responseClone->getHeaders()); -// $log->setResponseStatus(''); -// $log->setResponseStatusCode($responseClone->getStatusCode()); -// // Disabled because you cannot getBody after passing it here -// // $log->setResponseBody($responseClone->getBody()->getContents()); -// $log->setResponseBody(''); -// $log->setResponseTime($stopTimer - $startTimer); -// $this->entityManager->persist($log); -// $this->entityManager->flush(); - + }//end try + // $stopTimer = microtime(true); + // + // $responseClone = clone $response; + // + // $log->setResponseHeaders($responseClone->getHeaders()); + // $log->setResponseStatus(''); + // $log->setResponseStatusCode($responseClone->getStatusCode()); + // Disabled because you cannot getBody after passing it here + // $log->setResponseBody($responseClone->getBody()->getContents()); + // $log->setResponseBody(''); + // $log->setResponseTime($stopTimer - $startTimer); + // $this->entityManager->persist($log); + // $this->entityManager->flush(); $createCertificates && $this->removeFiles($config); return $this->handleEndpointsConfigIn($source, $endpoint, $response); - } + + }//end call() + /** * Handles the endpointsConfig of a Source before we do an api-call. @@ -267,7 +289,7 @@ private function handleEndpointsConfigOut(Source $source, string $endpoint, arra // Let's check if the endpoint used on this source has "out" configuration in the EndpointsConfig of the source. if (array_key_exists($endpoint, $endpointsConfig) === true && array_key_exists('out', $endpointsConfig[$endpoint])) { $endpointConfigOut = $endpointsConfig[$endpoint]['out']; - } elseif (array_key_exists('global', $endpointsConfig) === true && array_key_exists('out', $endpointsConfig['global'])) { + } else if (array_key_exists('global', $endpointsConfig) === true && array_key_exists('out', $endpointsConfig['global'])) { $endpointConfigOut = $endpointsConfig['global']['out']; } @@ -278,8 +300,10 @@ private function handleEndpointsConfigOut(Source $source, string $endpoint, arra } return $config; + }//end handleEndpointsConfigOut() + /** * Handles endpointConfig for a specific endpoint on a source and a specific configuration key like: 'query' or 'headers'. * Before we do an api-call. @@ -300,15 +324,18 @@ private function handleEndpointConfigOut(array $config, array $endpointConfigOut if (array_key_exists('mapping', $endpointConfigOut[$configKey])) { $mapping = $this->entityManager->getRepository('App:Mapping')->findOneBy(['reference' => $endpointConfigOut[$configKey]['mapping']]); if ($mapping === null) { - //todo: log error + // todo: log error return $config; } + $config[$configKey] = $this->mappingService->mapping($mapping, $config[$configKey]); } return $config; + }//end handleEndpointConfigOut() + /** * Handles the endpointsConfig of a Source after we did an api-call. * @@ -329,13 +356,13 @@ private function handleEndpointsConfigIn(Source $source, string $endpoint, Respo // Let's check if the endpoint used on this source has "in" configuration in the EndpointsConfig of the source. if (array_key_exists($endpoint, $endpointsConfig) === true && array_key_exists('in', $endpointsConfig[$endpoint])) { $endpointConfigIn = $endpointsConfig[$endpoint]['in']; - } elseif (array_key_exists('global', $endpointsConfig) === true && array_key_exists('in', $endpointsConfig['global'])) { + } else if (array_key_exists('global', $endpointsConfig) === true && array_key_exists('in', $endpointsConfig['global'])) { $endpointConfigIn = $endpointsConfig['global']['in']; } if (isset($endpointConfigIn) === true) { $headers = $this->handleEndpointConfigIn($response->getHeaders(), $endpointConfigIn, 'headers'); - $body = $this->handleEndpointConfigIn($response->getBody(), $endpointConfigIn, 'body'); + $body = $this->handleEndpointConfigIn($response->getBody(), $endpointConfigIn, 'body'); is_array($body) && $body = json_encode($body); @@ -343,8 +370,10 @@ private function handleEndpointsConfigIn(Source $source, string $endpoint, Respo } return $response; + }//end handleEndpointsConfigIn() + /** * Handles endpointConfig for a specific endpoint on a source and a specific response property like: 'headers' or 'body'. * After we did an api-call. @@ -365,16 +394,19 @@ private function handleEndpointConfigIn($responseData, array $endpointConfigIn, if (array_key_exists('mapping', $endpointConfigIn[$responseProperty])) { $mapping = $this->entityManager->getRepository('App:Mapping')->findOneBy(['reference' => $endpointConfigIn[$responseProperty]['mapping']]); if ($mapping === null) { - //todo: log error + // todo: log error return $responseData; } + $responseData = json_decode($responseData->getContents(), true); $responseData = $this->mappingService->mapping($mapping, $responseData); } return $responseData; + }//end handleEndpointConfigIn() + /** * Determine the content type of a response. * @@ -395,7 +427,9 @@ private function getContentType(Response $response, Source $source): string } return $contentType; - } + + }//end getContentType() + /** * Decodes a response based on the source it belongs to. @@ -410,32 +444,32 @@ private function getContentType(Response $response, Source $source): string public function decodeResponse( Source $source, Response $response, - ?string $contentType = 'application/json' + ?string $contentType='application/json' ): array { $this->logger->info('Decoding response content'); // resultaat omzetten - // als geen content-type header dan content-type header is accept header $responseBody = $response->getBody()->getContents(); if (!$responseBody) { return []; } + $this->logger->debug('Response content: '.$responseBody); - $xmlEncoder = new XmlEncoder(['xml_root_node_name' => $this->configuration['apiSource']['location']['xmlRootNodeName'] ?? 'response']); + $xmlEncoder = new XmlEncoder(['xml_root_node_name' => ($this->configuration['apiSource']['location']['xmlRootNodeName'] ?? 'response')]); $yamlEncoder = new YamlEncoder(); - $contentType = $this->getContentType($response, $source) ?? $contentType; + $contentType = ($this->getContentType($response, $source) ?? $contentType); switch ($contentType) { - case 'text/yaml': - case 'text/x-yaml': - return $yamlEncoder->decode($responseBody, 'yaml'); - case 'text/xml': - case 'text/xml; charset=utf-8': - case 'application/xml': - return $xmlEncoder->decode($responseBody, 'xml'); - case 'application/json': - default: - $result = json_decode($responseBody, true); + case 'text/yaml': + case 'text/x-yaml': + return $yamlEncoder->decode($responseBody, 'yaml'); + case 'text/xml': + case 'text/xml; charset=utf-8': + case 'application/xml': + return $xmlEncoder->decode($responseBody, 'xml'); + case 'application/json': + default: + $result = json_decode($responseBody, true); } if (isset($result)) { @@ -452,7 +486,9 @@ public function decodeResponse( throw new \Exception('Could not decode body, content type could not be determined'); } - } + + }//end decodeResponse() + /** * Determines the authentication procedure based upon a source. @@ -464,7 +500,9 @@ public function decodeResponse( private function getAuthentication(Source $source): array { return $this->authenticationService->getAuthentication($source); - } + + }//end getAuthentication() + /** * Fetches all pages for a source and merges the result arrays to one array. @@ -477,43 +515,47 @@ private function getAuthentication(Source $source): array * * @return array The array of results */ - public function getAllResults(Source $source, string $endpoint = '', array $config = []): array + public function getAllResults(Source $source, string $endpoint='', array $config=[]): array { $this->logger->info('Fetch all data from source and combine the results into one array'); - $errorCount = 0; - $pageCount = 1; - $results = []; + $errorCount = 0; + $pageCount = 1; + $results = []; $previousResult = []; while ($errorCount < 5) { try { $config['query']['page'] = $pageCount; $pageCount++; - $response = $this->call($source, $endpoint, 'GET', $config); + $response = $this->call($source, $endpoint, 'GET', $config); $decodedResponse = $this->decodeResponse($source, $response); - if ( - $decodedResponse === [] || - isset($decodedResponse['results']) && $decodedResponse['results'] === [] || - isset($decodedResponse['items']) && $decodedResponse['items'] == [] || - isset($decodedResponse['page']) && $decodedResponse['page'] !== $pageCount - 1 || - $decodedResponse == $previousResult + if ($decodedResponse === [] + || isset($decodedResponse['results']) && $decodedResponse['results'] === [] + || isset($decodedResponse['items']) && $decodedResponse['items'] == [] + || isset($decodedResponse['page']) && $decodedResponse['page'] !== ($pageCount - 1) + || $decodedResponse == $previousResult ) { break; } + $decodedResponses[] = $decodedResponse; - $previousResult = $decodedResponse; + $previousResult = $decodedResponse; } catch (\Exception $exception) { $errorCount++; $this->logger->error($exception->getMessage()); } + if (isset($decodedResponse['results'])) { $results = array_merge($decodedResponse['results'], $results); - } elseif (isset($decodedResponse['items'])) { + } else if (isset($decodedResponse['items'])) { $results = array_merge($decodedResponse['items'], $results); - } elseif (isset($decodedResponse[0])) { + } else if (isset($decodedResponse[0])) { $results = array_merge($decodedResponse, $results); } - } + }//end while return $results; - } -} + + }//end getAllResults() + + +}//end class diff --git a/src/Service/ComposerService.php b/src/Service/ComposerService.php index 1359f9e2..f614e3b3 100644 --- a/src/Service/ComposerService.php +++ b/src/Service/ComposerService.php @@ -17,6 +17,8 @@ */ class ComposerService { + + private function arrayEnum(array $array, array $enum): bool { // Lets see if the values in the array arry pressent in the enum @@ -27,7 +29,9 @@ private function arrayEnum(array $array, array $enum): bool } return true; - } + + }//end arrayEnum() + /** * Make a call to composer. @@ -38,223 +42,249 @@ private function arrayEnum(array $array, array $enum): bool * * @return array|string */ - private function composerCall(string $call, array $options = [], string $packadge = '') + private function composerCall(string $call, array $options=[], string $packadge='') { $optionsList = []; // Lets check for valid calls switch ($call) { - case 'init': - $optionsList = []; - // name: Name of the package. - //--description: Description of the package. - //--author: Author name of the package. - //--type: Type of package. - //--homepage: Homepage of the package. - //--require: Package to require with a version constraint. Should be in format foo/bar:1.0.0. - //--require-dev: Development requirements, see --require. - //--stability (-s): Value for the minimum-stability field. - //--license (-l): License of package. - //--repository: Provide one (or more) custom repositories. They will be stored in the generated composer.json, and used for auto-completion when prompting for the list of requires. Every repository can be either an HTTP URL pointing to a composer repository or a JSON string which similar to what the repositories key accepts. - //--autoload (-a): Add a PSR-4 autoload mapping to - break; - case 'install': - $optionsList = []; - // --prefer-install: There are two ways of downloading a package: source and dist. Composer uses dist by default. If you pass --prefer-install=source (or --prefer-source) Composer will install from source if there is one. This is useful if you want to make a bugfix to a project and get a local git clone of the dependency directly. To get the legacy behavior where Composer use source automatically for dev versions of packages, use --prefer-install=auto. See also config.preferred-install. Passing this flag will override the config value. - //--dry-run: If you want to run through an installation without actually installing a package, you can use --dry-run. This will simulate the installation and show you what would happen. - //--download-only: Download only, do not install packages. - //--dev: Install packages listed in require-dev (this is the default behavior). - //--no-dev: Skip installing packages listed in require-dev. The autoloader generation skips the autoload-dev rules. Also see COMPOSER_NO_DEV. - //--no-autoloader: Skips autoloader generation. - //--no-progress: Removes the progress display that can mess with some terminals or scripts which don't handle backspace characters. - //--audit: Run an audit after installation is complete. - //--audit-format: Audit output format. Must be "table", "plain", "json", or "summary" (default). - //--optimize-autoloader (-o): Convert PSR-0/4 autoloading to classmap to get a faster autoloader. This is recommended especially for production, but can take a bit of time to run so it is currently not done by default. - //--classmap-authoritative (-a): Autoload classes from the classmap only. Implicitly enables --optimize-autoloader. - //--apcu-autoloader: Use APCu to cache found/not-found classes. - //--apcu-autoloader-prefix: Use a custom prefix for the APCu autoloader cache. Implicitly enables --apcu-autoloader. - //--ignore-platform-reqs: ignore all platform requirements (php, hhvm, lib-* and ext-*) and force the installation even if the local machine does not fulfill these. See also the platform config option. - //--ignore-platform-req: ignore a specific platform requirement(php, hhvm, lib-* and ext-*) and force the installation even if the local machine does not fulfill it. Multiple requirements can be ignored via wildcard. Appending a + makes it only ignore the upper-bound of the requirements. For example, if a package requires php: ^7, then the option --ignore-platform-req=php+ would allow installing on PHP 8, but installation on PHP 5.6 would still fail. - break; - case 'update': - $optionsList = []; - // --prefer-install: There are two ways of downloading a package: source and dist. Composer uses dist by default. If you pass --prefer-install=source (or --prefer-source) Composer will install from source if there is one. This is useful if you want to make a bugfix to a project and get a local git clone of the dependency directly. To get the legacy behavior where Composer use source automatically for dev versions of packages, use --prefer-install=auto. See also config.preferred-install. Passing this flag will override the config value. - //--dry-run: Simulate the command without actually doing anything. - //--dev: Install packages listed in require-dev (this is the default behavior). - //--no-dev: Skip installing packages listed in require-dev. The autoloader generation skips the autoload-dev rules. Also see COMPOSER_NO_DEV. - //--no-install: Does not run the install step after updating the composer.lock file. - //--no-audit: Does not run the audit steps after updating the composer.lock file. Also see COMPOSER_NO_AUDIT. - //--audit-format: Audit output format. Must be "table", "plain", "json", or "summary" (default). - //--lock: Only updates the lock file hash to suppress warning about the lock file being out of date. - //--with: Temporary version constraint to add, e.g. foo/bar:1.0.0 or foo/bar=1.0.0 - //--no-autoloader: Skips autoloader generation. - //--no-progress: Removes the progress display that can mess with some terminals or scripts which don't handle backspace characters. - //--with-dependencies (-w): Update also dependencies of packages in the argument list, except those which are root requirements. - //--with-all-dependencies (-W): Update also dependencies of packages in the argument list, including those which are root requirements. - //--optimize-autoloader (-o): Convert PSR-0/4 autoloading to classmap to get a faster autoloader. This is recommended especially for production, but can take a bit of time to run, so it is currently not done by default. - //--classmap-authoritative (-a): Autoload classes from the classmap only. Implicitly enables --optimize-autoloader. - //--apcu-autoloader: Use APCu to cache found/not-found classes. - //--apcu-autoloader-prefix: Use a custom prefix for the APCu autoloader cache. Implicitly enables --apcu-autoloader. - //--ignore-platform-reqs: ignore all platform requirements (php, hhvm, lib-* and ext-*) and force the installation even if the local machine does not fulfill these. See also the platform config option. - //--ignore-platform-req: ignore a specific platform requirement(php, hhvm, lib-* and ext-*) and force the installation even if the local machine does not fulfill it. Multiple requirements can be ignored via wildcard. Appending a + makes it only ignore the upper-bound of the requirements. For example, if a package requires php: ^7, then the option --ignore-platform-req=php+ would allow installing on PHP 8, but installation on PHP 5.6 would still fail. - //--prefer-stable: Prefer stable versions of dependencies. Can also be set via the COMPOSER_PREFER_STABLE=1 env var. - //--prefer-lowest: Prefer lowest versions of dependencies. Useful for testing minimal versions of requirements, generally used with --prefer-stable. Can also be set via the COMPOSER_PREFER_LOWEST=1 env var. - //--interactive: Interactive interface with autocompletion to select the packages to update. - //--root-reqs: Restricts the update to your first degree dependencies.+ makes it only ignore the upper-bound of the requirements. For example, if a package requires php: ^7, then the option --ignore-platform-req=php+ would allow installing on PHP 8, but installation on PHP 5.6 would still fail. - break; - case 'require': - $optionsList = []; - // --dev: Add packages to require-dev. - //--dry-run: Simulate the command without actually doing anything. - //--prefer-install: There are two ways of downloading a package: source and dist. Composer uses dist by default. If you pass --prefer-install=source (or --prefer-source) Composer will install from source if there is one. This is useful if you want to make a bugfix to a project and get a local git clone of the dependency directly. To get the legacy behavior where Composer use source automatically for dev versions of packages, use --prefer-install=auto. See also config.preferred-install. Passing this flag will override the config value. - //--no-progress: Removes the progress display that can mess with some terminals or scripts which don't handle backspace characters. - //--no-update: Disables the automatic update of the dependencies (implies --no-install). - //--no-install: Does not run the install step after updating the composer.lock file. - //--no-audit: Does not run the audit steps after updating the composer.lock file. Also see COMPOSER_NO_AUDIT. - //--audit-format: Audit output format. Must be "table", "plain", "json", or "summary" (default). - //--update-no-dev: Run the dependency update with the --no-dev option. Also see COMPOSER_NO_DEV. - //--update-with-dependencies (-w): Also update dependencies of the newly required packages, except those that are root requirements. - //--update-with-all-dependencies (-W): Also update dependencies of the newly required packages, including those that are root requirements. - //--ignore-platform-reqs: ignore all platform requirements (php, hhvm, lib-* and ext-*) and force the installation even if the local machine does not fulfill these. See also the platform config option. - //--ignore-platform-req: ignore a specific platform requirement(php, hhvm, lib-* and ext-*) and force the installation even if the local machine does not fulfill it. Multiple requirements can be ignored via wildcard. - //--prefer-stable: Prefer stable versions of dependencies. Can also be set via the COMPOSER_PREFER_STABLE=1 env var. - //--prefer-lowest: Prefer lowest versions of dependencies. Useful for testing minimal versions of requirements, generally used with --prefer-stable. Can also be set via the COMPOSER_PREFER_LOWEST=1 env var. - //--sort-packages: Keep packages sorted in composer.json. - //--optimize-autoloader (-o): Convert PSR-0/4 autoloading to classmap to get a faster autoloader. This is recommended especially for production, but can take a bit of time to run, so it is currently not done by default. - //--classmap-authoritative (-a): Autoload classes from the classmap only. Implicitly enables --optimize-autoloader. - //--apcu-autoloader: Use APCu to cache found/not-found classes. - //--apcu-autoloader-prefix: Use a custom prefix for the APCu autoloader cache. Implicitly enables --apcu-autoloader.ard. Appending a + makes it only ignore the upper-bound of the requirements. For example, if a package requires php: ^7, then the option --ignore-platform-req=php+ would allow installing on PHP 8, but installation on PHP 5.6 would still fail. - break; - case 'remove': - $optionsList = []; - // --dev: Remove packages from require-dev. - //--dry-run: Simulate the command without actually doing anything. - //--no-progress: Removes the progress display that can mess with some terminals or scripts which don't handle backspace characters. - //--no-update: Disables the automatic update of the dependencies (implies --no-install). - //--no-install: Does not run the install step after updating the composer.lock file. - //--no-audit: Does not run the audit steps after installation is complete. Also see COMPOSER_NO_AUDIT. - //--audit-format: Audit output format. Must be "table", "plain", "json", or "summary" (default). - //--update-no-dev: Run the dependency update with the --no-dev option. Also see COMPOSER_NO_DEV. - //--update-with-dependencies (-w): Also update dependencies of the removed packages. (Deprecated, is now default behavior) - //--update-with-all-dependencies (-W): Allows all inherited dependencies to be updated, including those that are root requirements. - //--ignore-platform-reqs: ignore all platform requirements (php, hhvm, lib-* and ext-*) and force the installation even if the local machine does not fulfill these. See also the platform config option. - //--ignore-platform-req: ignore a specific platform requirement(php, hhvm, lib-* and ext-*) and force the installation even if the local machine does not fulfill it. Multiple requirements can be ignored via wildcard. - //--optimize-autoloader (-o): Convert PSR-0/4 autoloading to classmap to get a faster autoloader. This is recommended especially for production, but can take a bit of time to run so it is currently not done by default. - //--classmap-authoritative (-a): Autoload classes from the classmap only. Implicitly enables --optimize-autoloader. - //--apcu-autoloader: Use APCu to cache found/not-found classes. - //--apcu-autoloader-prefix: Use a custom prefix for the APCu autoloader cache. Implicitly enables --apcu-autoloader.x: Use a custom prefix for the APCu autoloader cache. Implicitly enables --apcu-autoloader.ard. Appending a + makes it only ignore the upper-bound of the requirements. For example, if a package requires php: ^7, then the option --ignore-platform-req=php+ would allow installing on PHP 8, but installation on PHP 5.6 would still fail. - break; - case 'bump': - $optionsList = []; - // - //--dev-only: Only bump requirements in "require-dev". - //--no-dev-only: Only bump requirements in "require". - //--dry-run: Outputs the packages to bump, but will not execute anything. - break; - case 'check-platform-reqs': - $optionsList = []; - //--lock: Checks requirements only from the lock file, not from installed packages. - //--no-dev: Disables checking of require-dev packages requirements. - //--format (-f): Format of the output: text (default) or json - break; - case 'remove': - $optionsList = []; - // --dev: Remove packages from require-dev. - //--dry-run: Simulate the command without actually doing anything. - //--no-progress: Removes the progress display that can mess with some terminals or scripts which don't handle backspace characters. - //--no-update: Disables the automatic update of the dependencies (implies --no-install). - //--no-install: Does not run the install step after updating the composer.lock file. - //--no-audit: Does not run the audit steps after installation is complete. Also see COMPOSER_NO_AUDIT. - //--audit-format: Audit output format. Must be "table", "plain", "json", or "summary" (default). - //--update-no-dev: Run the dependency update with the --no-dev option. Also see COMPOSER_NO_DEV. - //--update-with-dependencies (-w): Also update dependencies of the removed packages. (Deprecated, is now default behavior) - //--update-with-all-dependencies (-W): Allows all inherited dependencies to be updated, including those that are root requirements. - //--ignore-platform-reqs: ignore all platform requirements (php, hhvm, lib-* and ext-*) and force the installation even if the local machine does not fulfill these. See also the platform config option. - //--ignore-platform-req: ignore a specific platform requirement(php, hhvm, lib-* and ext-*) and force the installation even if the local machine does not fulfill it. Multiple requirements can be ignored via wildcard. - //--optimize-autoloader (-o): Convert PSR-0/4 autoloading to classmap to get a faster autoloader. This is recommended especially for production, but can take a bit of time to run so it is currently not done by default. - //--classmap-authoritative (-a): Autoload classes from the classmap only. Implicitly enables --optimize-autoloader. - //--apcu-autoloader: Use APCu to cache found/not-found classes. - //--apcu-autoloader-prefix: Use a custom prefix for the APCu autoloader cache. Implicitly enables --apcu-autoloader.x: Use a custom prefix for the APCu autoloader cache. Implicitly enables --apcu-autoloader.ard. Appending a + makes it only ignore the upper-bound of the requirements. For example, if a package requires php: ^7, then the option --ignore-platform-req=php+ would allow installing on PHP 8, but installation on PHP 5.6 would still fail. - break; - case 'search': - $optionsList = ['--format']; - // --only-name (-N): Search only in package names. - //--only-vendor (-O): Search only for vendor / organization names, returns only "vendor" as a result. - //--type (-t): Search for a specific package type. - //--format (-f): Lets you pick between text (default) or json output format. Note that in the json, only the name and description keys are guaranteed to be present. The rest (url, repository, downloads and favers) are available for Packagist.org search results and other repositories may return more or less data. - break; - case 'show': - $optionsList = ['--all', '--installed', '--locked', '--platform ', '--available', '--self', '--name-only', '--path', '--tree', '--latest', '--outdated', '--latest', '--ignore', '--no-dev', '--major-only', '--minor-only', '--patch-only', '--direct', '--strict', '--ignore-platform-reqs', '--ignore-platform-req', '--format']; - break; - case 'home': - $optionsList = []; - // --homepage (-H): Open the homepage instead of the repository URL. - //--show (-s): Only show the homepage or repository URL. - break; - case 'suggests': - $optionsList = []; - // --by-package: Groups output by suggesting package (default). - //--by-suggestion: Groups output by suggested package. - //--all: Show suggestions from all dependencies, including transitive ones (by default only direct dependencies' suggestions are shown). - //--list: Show only list of suggested package names. - //--no-dev: Excludes suggestions from require-dev packages. - break; - case 'fund': - $optionsList = []; - //--format (-f): Lets you pick between text (default) or json output format. - break; - case 'depends ': - $optionsList = []; - //--recursive (-r): Recursively resolves up to the root package. - //--tree (-t): Prints the results as a nested tree, implies -r. - break; - case 'prohibits ': - $optionsList = []; - //--recursive (-r): Recursively resolves up to the root package. - //--tree (-t): Prints the results as a nested tree, implies -r. - break; - case 'validate ': - $optionsList = []; - //--no-check-all: Do not emit a warning if requirements in composer.json use unbound or overly strict version constraints. - //--no-check-lock: Do not emit an error if composer.lock exists and is not up to date. - //--no-check-publish: Do not emit an error if composer.json is unsuitable for publishing as a package on Packagist but is otherwise valid. - //--with-dependencies: Also validate the composer.json of all installed dependencies. - //--strict: Return a non-zero exit code for warnings as well as errors. - break; - case 'status ': - $optionsList = []; - //--recursive (-r): Recursively resolves up to the root package. - //--tree (-t): Prints the results as a nested tree, implies -r. - break; - case 'config ': - $optionsList = []; - //--global (-g): Operate on the global config file located at $COMPOSER_HOME/config.json by default. Without this option, this command affects the local composer.json file or a file specified by --file. - //--editor (-e): Open the local composer.json file using in a text editor as defined by the EDITOR env variable. With the --global option, this opens the global config file. - //--auth (-a): Affect auth config file (only used for --editor). - //--unset: Remove the configuration element named by setting-key. - //--list (-l): Show the list of current config variables. With the --global option this lists the global configuration only. - //--file="..." (-f): Operate on a specific file instead of composer.json. Note that this cannot be used in conjunction with the --global option. - //--absolute: Returns absolute paths when fetching *-dir config values instead of relative. - //--json: JSON decode the setting value, to be used with extra.* keys. - //--merge: Merge the setting value with the current value, to be used with extra.* keys in combination with --json. - //--append: When adding a repository, append it (lowest priority) to the existing ones instead of prepending it (highest priority). - //--source: Display where the config value is loaded from. - break; - case 'diagnose ': - $optionsList = []; - break; - case 'archive ': - $optionsList = []; - //--no-dev: Disables auditing of require-dev packages. - //--format (-f): Audit output format. Must be "table" (default), "plain", "json", or "summary". - //--locked: Audit packages from the lock file, regardless of what is currently in vendor dir. - break; - case 'audit ': - $optionsList = ['--format']; - break; - } + case 'init': + $optionsList = []; + // name: Name of the package. + // --description: Description of the package. + // --author: Author name of the package. + // --type: Type of package. + // --homepage: Homepage of the package. + // --require: Package to require with a version constraint. Should be in format foo/bar:1.0.0. + // --require-dev: Development requirements, see --require. + // --stability (-s): Value for the minimum-stability field. + // --license (-l): License of package. + // --repository: Provide one (or more) custom repositories. They will be stored in the generated composer.json, and used for auto-completion when prompting for the list of requires. Every repository can be either an HTTP URL pointing to a composer repository or a JSON string which similar to what the repositories key accepts. + // --autoload (-a): Add a PSR-4 autoload mapping to + break; + case 'install': + $optionsList = []; + // --prefer-install: There are two ways of downloading a package: source and dist. Composer uses dist by default. If you pass --prefer-install=source (or --prefer-source) Composer will install from source if there is one. This is useful if you want to make a bugfix to a project and get a local git clone of the dependency directly. To get the legacy behavior where Composer use source automatically for dev versions of packages, use --prefer-install=auto. See also config.preferred-install. Passing this flag will override the config value. + // --dry-run: If you want to run through an installation without actually installing a package, you can use --dry-run. This will simulate the installation and show you what would happen. + // --download-only: Download only, do not install packages. + // --dev: Install packages listed in require-dev (this is the default behavior). + // --no-dev: Skip installing packages listed in require-dev. The autoloader generation skips the autoload-dev rules. Also see COMPOSER_NO_DEV. + // --no-autoloader: Skips autoloader generation. + // --no-progress: Removes the progress display that can mess with some terminals or scripts which don't handle backspace characters. + // --audit: Run an audit after installation is complete. + // --audit-format: Audit output format. Must be "table", "plain", "json", or "summary" (default). + // --optimize-autoloader (-o): Convert PSR-0/4 autoloading to classmap to get a faster autoloader. This is recommended especially for production, but can take a bit of time to run so it is currently not done by default. + // --classmap-authoritative (-a): Autoload classes from the classmap only. Implicitly enables --optimize-autoloader. + // --apcu-autoloader: Use APCu to cache found/not-found classes. + // --apcu-autoloader-prefix: Use a custom prefix for the APCu autoloader cache. Implicitly enables --apcu-autoloader. + // --ignore-platform-reqs: ignore all platform requirements (php, hhvm, lib-* and ext-*) and force the installation even if the local machine does not fulfill these. See also the platform config option. + // --ignore-platform-req: ignore a specific platform requirement(php, hhvm, lib-* and ext-*) and force the installation even if the local machine does not fulfill it. Multiple requirements can be ignored via wildcard. Appending a + makes it only ignore the upper-bound of the requirements. For example, if a package requires php: ^7, then the option --ignore-platform-req=php+ would allow installing on PHP 8, but installation on PHP 5.6 would still fail. + break; + case 'update': + $optionsList = []; + // --prefer-install: There are two ways of downloading a package: source and dist. Composer uses dist by default. If you pass --prefer-install=source (or --prefer-source) Composer will install from source if there is one. This is useful if you want to make a bugfix to a project and get a local git clone of the dependency directly. To get the legacy behavior where Composer use source automatically for dev versions of packages, use --prefer-install=auto. See also config.preferred-install. Passing this flag will override the config value. + // --dry-run: Simulate the command without actually doing anything. + // --dev: Install packages listed in require-dev (this is the default behavior). + // --no-dev: Skip installing packages listed in require-dev. The autoloader generation skips the autoload-dev rules. Also see COMPOSER_NO_DEV. + // --no-install: Does not run the install step after updating the composer.lock file. + // --no-audit: Does not run the audit steps after updating the composer.lock file. Also see COMPOSER_NO_AUDIT. + // --audit-format: Audit output format. Must be "table", "plain", "json", or "summary" (default). + // --lock: Only updates the lock file hash to suppress warning about the lock file being out of date. + // --with: Temporary version constraint to add, e.g. foo/bar:1.0.0 or foo/bar=1.0.0 + // --no-autoloader: Skips autoloader generation. + // --no-progress: Removes the progress display that can mess with some terminals or scripts which don't handle backspace characters. + // --with-dependencies (-w): Update also dependencies of packages in the argument list, except those which are root requirements. + // --with-all-dependencies (-W): Update also dependencies of packages in the argument list, including those which are root requirements. + // --optimize-autoloader (-o): Convert PSR-0/4 autoloading to classmap to get a faster autoloader. This is recommended especially for production, but can take a bit of time to run, so it is currently not done by default. + // --classmap-authoritative (-a): Autoload classes from the classmap only. Implicitly enables --optimize-autoloader. + // --apcu-autoloader: Use APCu to cache found/not-found classes. + // --apcu-autoloader-prefix: Use a custom prefix for the APCu autoloader cache. Implicitly enables --apcu-autoloader. + // --ignore-platform-reqs: ignore all platform requirements (php, hhvm, lib-* and ext-*) and force the installation even if the local machine does not fulfill these. See also the platform config option. + // --ignore-platform-req: ignore a specific platform requirement(php, hhvm, lib-* and ext-*) and force the installation even if the local machine does not fulfill it. Multiple requirements can be ignored via wildcard. Appending a + makes it only ignore the upper-bound of the requirements. For example, if a package requires php: ^7, then the option --ignore-platform-req=php+ would allow installing on PHP 8, but installation on PHP 5.6 would still fail. + // --prefer-stable: Prefer stable versions of dependencies. Can also be set via the COMPOSER_PREFER_STABLE=1 env var. + // --prefer-lowest: Prefer lowest versions of dependencies. Useful for testing minimal versions of requirements, generally used with --prefer-stable. Can also be set via the COMPOSER_PREFER_LOWEST=1 env var. + // --interactive: Interactive interface with autocompletion to select the packages to update. + // --root-reqs: Restricts the update to your first degree dependencies.+ makes it only ignore the upper-bound of the requirements. For example, if a package requires php: ^7, then the option --ignore-platform-req=php+ would allow installing on PHP 8, but installation on PHP 5.6 would still fail. + break; + case 'require': + $optionsList = []; + // --dev: Add packages to require-dev. + // --dry-run: Simulate the command without actually doing anything. + // --prefer-install: There are two ways of downloading a package: source and dist. Composer uses dist by default. If you pass --prefer-install=source (or --prefer-source) Composer will install from source if there is one. This is useful if you want to make a bugfix to a project and get a local git clone of the dependency directly. To get the legacy behavior where Composer use source automatically for dev versions of packages, use --prefer-install=auto. See also config.preferred-install. Passing this flag will override the config value. + // --no-progress: Removes the progress display that can mess with some terminals or scripts which don't handle backspace characters. + // --no-update: Disables the automatic update of the dependencies (implies --no-install). + // --no-install: Does not run the install step after updating the composer.lock file. + // --no-audit: Does not run the audit steps after updating the composer.lock file. Also see COMPOSER_NO_AUDIT. + // --audit-format: Audit output format. Must be "table", "plain", "json", or "summary" (default). + // --update-no-dev: Run the dependency update with the --no-dev option. Also see COMPOSER_NO_DEV. + // --update-with-dependencies (-w): Also update dependencies of the newly required packages, except those that are root requirements. + // --update-with-all-dependencies (-W): Also update dependencies of the newly required packages, including those that are root requirements. + // --ignore-platform-reqs: ignore all platform requirements (php, hhvm, lib-* and ext-*) and force the installation even if the local machine does not fulfill these. See also the platform config option. + // --ignore-platform-req: ignore a specific platform requirement(php, hhvm, lib-* and ext-*) and force the installation even if the local machine does not fulfill it. Multiple requirements can be ignored via wildcard. + // --prefer-stable: Prefer stable versions of dependencies. Can also be set via the COMPOSER_PREFER_STABLE=1 env var. + // --prefer-lowest: Prefer lowest versions of dependencies. Useful for testing minimal versions of requirements, generally used with --prefer-stable. Can also be set via the COMPOSER_PREFER_LOWEST=1 env var. + // --sort-packages: Keep packages sorted in composer.json. + // --optimize-autoloader (-o): Convert PSR-0/4 autoloading to classmap to get a faster autoloader. This is recommended especially for production, but can take a bit of time to run, so it is currently not done by default. + // --classmap-authoritative (-a): Autoload classes from the classmap only. Implicitly enables --optimize-autoloader. + // --apcu-autoloader: Use APCu to cache found/not-found classes. + // --apcu-autoloader-prefix: Use a custom prefix for the APCu autoloader cache. Implicitly enables --apcu-autoloader.ard. Appending a + makes it only ignore the upper-bound of the requirements. For example, if a package requires php: ^7, then the option --ignore-platform-req=php+ would allow installing on PHP 8, but installation on PHP 5.6 would still fail. + break; + case 'remove': + $optionsList = []; + // --dev: Remove packages from require-dev. + // --dry-run: Simulate the command without actually doing anything. + // --no-progress: Removes the progress display that can mess with some terminals or scripts which don't handle backspace characters. + // --no-update: Disables the automatic update of the dependencies (implies --no-install). + // --no-install: Does not run the install step after updating the composer.lock file. + // --no-audit: Does not run the audit steps after installation is complete. Also see COMPOSER_NO_AUDIT. + // --audit-format: Audit output format. Must be "table", "plain", "json", or "summary" (default). + // --update-no-dev: Run the dependency update with the --no-dev option. Also see COMPOSER_NO_DEV. + // --update-with-dependencies (-w): Also update dependencies of the removed packages. (Deprecated, is now default behavior) + // --update-with-all-dependencies (-W): Allows all inherited dependencies to be updated, including those that are root requirements. + // --ignore-platform-reqs: ignore all platform requirements (php, hhvm, lib-* and ext-*) and force the installation even if the local machine does not fulfill these. See also the platform config option. + // --ignore-platform-req: ignore a specific platform requirement(php, hhvm, lib-* and ext-*) and force the installation even if the local machine does not fulfill it. Multiple requirements can be ignored via wildcard. + // --optimize-autoloader (-o): Convert PSR-0/4 autoloading to classmap to get a faster autoloader. This is recommended especially for production, but can take a bit of time to run so it is currently not done by default. + // --classmap-authoritative (-a): Autoload classes from the classmap only. Implicitly enables --optimize-autoloader. + // --apcu-autoloader: Use APCu to cache found/not-found classes. + // --apcu-autoloader-prefix: Use a custom prefix for the APCu autoloader cache. Implicitly enables --apcu-autoloader.x: Use a custom prefix for the APCu autoloader cache. Implicitly enables --apcu-autoloader.ard. Appending a + makes it only ignore the upper-bound of the requirements. For example, if a package requires php: ^7, then the option --ignore-platform-req=php+ would allow installing on PHP 8, but installation on PHP 5.6 would still fail. + break; + case 'bump': + $optionsList = []; + // + // --dev-only: Only bump requirements in "require-dev". + // --no-dev-only: Only bump requirements in "require". + // --dry-run: Outputs the packages to bump, but will not execute anything. + break; + case 'check-platform-reqs': + $optionsList = []; + // --lock: Checks requirements only from the lock file, not from installed packages. + // --no-dev: Disables checking of require-dev packages requirements. + // --format (-f): Format of the output: text (default) or json + break; + case 'remove': + $optionsList = []; + // --dev: Remove packages from require-dev. + // --dry-run: Simulate the command without actually doing anything. + // --no-progress: Removes the progress display that can mess with some terminals or scripts which don't handle backspace characters. + // --no-update: Disables the automatic update of the dependencies (implies --no-install). + // --no-install: Does not run the install step after updating the composer.lock file. + // --no-audit: Does not run the audit steps after installation is complete. Also see COMPOSER_NO_AUDIT. + // --audit-format: Audit output format. Must be "table", "plain", "json", or "summary" (default). + // --update-no-dev: Run the dependency update with the --no-dev option. Also see COMPOSER_NO_DEV. + // --update-with-dependencies (-w): Also update dependencies of the removed packages. (Deprecated, is now default behavior) + // --update-with-all-dependencies (-W): Allows all inherited dependencies to be updated, including those that are root requirements. + // --ignore-platform-reqs: ignore all platform requirements (php, hhvm, lib-* and ext-*) and force the installation even if the local machine does not fulfill these. See also the platform config option. + // --ignore-platform-req: ignore a specific platform requirement(php, hhvm, lib-* and ext-*) and force the installation even if the local machine does not fulfill it. Multiple requirements can be ignored via wildcard. + // --optimize-autoloader (-o): Convert PSR-0/4 autoloading to classmap to get a faster autoloader. This is recommended especially for production, but can take a bit of time to run so it is currently not done by default. + // --classmap-authoritative (-a): Autoload classes from the classmap only. Implicitly enables --optimize-autoloader. + // --apcu-autoloader: Use APCu to cache found/not-found classes. + // --apcu-autoloader-prefix: Use a custom prefix for the APCu autoloader cache. Implicitly enables --apcu-autoloader.x: Use a custom prefix for the APCu autoloader cache. Implicitly enables --apcu-autoloader.ard. Appending a + makes it only ignore the upper-bound of the requirements. For example, if a package requires php: ^7, then the option --ignore-platform-req=php+ would allow installing on PHP 8, but installation on PHP 5.6 would still fail. + break; + case 'search': + $optionsList = ['--format']; + // --only-name (-N): Search only in package names. + // --only-vendor (-O): Search only for vendor / organization names, returns only "vendor" as a result. + // --type (-t): Search for a specific package type. + // --format (-f): Lets you pick between text (default) or json output format. Note that in the json, only the name and description keys are guaranteed to be present. The rest (url, repository, downloads and favers) are available for Packagist.org search results and other repositories may return more or less data. + break; + case 'show': + $optionsList = [ + '--all', + '--installed', + '--locked', + '--platform ', + '--available', + '--self', + '--name-only', + '--path', + '--tree', + '--latest', + '--outdated', + '--latest', + '--ignore', + '--no-dev', + '--major-only', + '--minor-only', + '--patch-only', + '--direct', + '--strict', + '--ignore-platform-reqs', + '--ignore-platform-req', + '--format', + ]; + break; + case 'home': + $optionsList = []; + // --homepage (-H): Open the homepage instead of the repository URL. + // --show (-s): Only show the homepage or repository URL. + break; + case 'suggests': + $optionsList = []; + // --by-package: Groups output by suggesting package (default). + // --by-suggestion: Groups output by suggested package. + // --all: Show suggestions from all dependencies, including transitive ones (by default only direct dependencies' suggestions are shown). + // --list: Show only list of suggested package names. + // --no-dev: Excludes suggestions from require-dev packages. + break; + case 'fund': + $optionsList = []; + // --format (-f): Lets you pick between text (default) or json output format. + break; + case 'depends ': + $optionsList = []; + // --recursive (-r): Recursively resolves up to the root package. + // --tree (-t): Prints the results as a nested tree, implies -r. + break; + case 'prohibits ': + $optionsList = []; + // --recursive (-r): Recursively resolves up to the root package. + // --tree (-t): Prints the results as a nested tree, implies -r. + break; + case 'validate ': + $optionsList = []; + // --no-check-all: Do not emit a warning if requirements in composer.json use unbound or overly strict version constraints. + // --no-check-lock: Do not emit an error if composer.lock exists and is not up to date. + // --no-check-publish: Do not emit an error if composer.json is unsuitable for publishing as a package on Packagist but is otherwise valid. + // --with-dependencies: Also validate the composer.json of all installed dependencies. + // --strict: Return a non-zero exit code for warnings as well as errors. + break; + case 'status ': + $optionsList = []; + // --recursive (-r): Recursively resolves up to the root package. + // --tree (-t): Prints the results as a nested tree, implies -r. + break; + case 'config ': + $optionsList = []; + // --global (-g): Operate on the global config file located at $COMPOSER_HOME/config.json by default. Without this option, this command affects the local composer.json file or a file specified by --file. + // --editor (-e): Open the local composer.json file using in a text editor as defined by the EDITOR env variable. With the --global option, this opens the global config file. + // --auth (-a): Affect auth config file (only used for --editor). + // --unset: Remove the configuration element named by setting-key. + // --list (-l): Show the list of current config variables. With the --global option this lists the global configuration only. + // --file="..." (-f): Operate on a specific file instead of composer.json. Note that this cannot be used in conjunction with the --global option. + // --absolute: Returns absolute paths when fetching *-dir config values instead of relative. + // --json: JSON decode the setting value, to be used with extra.* keys. + // --merge: Merge the setting value with the current value, to be used with extra.* keys in combination with --json. + // --append: When adding a repository, append it (lowest priority) to the existing ones instead of prepending it (highest priority). + // --source: Display where the config value is loaded from. + break; + case 'diagnose ': + $optionsList = []; + break; + case 'archive ': + $optionsList = []; + // --no-dev: Disables auditing of require-dev packages. + // --format (-f): Audit output format. Must be "table" (default), "plain", "json", or "summary". + // --locked: Audit packages from the lock file, regardless of what is currently in vendor dir. + break; + case 'audit ': + $optionsList = ['--format']; + break; + }//end switch // Prepare the comand - $cmd = ['composer', $call]; + $cmd = [ + 'composer', + $call, + ]; if ($packadge != '') { $cmd[] = strtolower($packadge); @@ -281,8 +311,8 @@ private function composerCall(string $call, array $options = [], string $packadg // executes after the command finishes if (!$process->isSuccessful()) { - //throw new ProcessFailedException($process); - //var_dump('error'); + // throw new ProcessFailedException($process); + // var_dump('error'); $content = $process->getErrorOutput(); } else { $content = $process->getOutput(); @@ -296,7 +326,9 @@ private function composerCall(string $call, array $options = [], string $packadg } return $content; - } + + }//end composerCall() + /** * Gets all installed plugins from the lock file. @@ -315,7 +347,9 @@ public function getLockFile(): array $results = $plugins['packages']; return $results; - } + + }//end getLockFile() + /** * Show al packadges installed trough composer. @@ -326,7 +360,7 @@ public function getLockFile(): array * * @return array */ - public function getAll(array $options = []): array + public function getAll(array $options=[]): array { $results = $this->getLockFile(); $plugins = []; @@ -340,7 +374,9 @@ public function getAll(array $options = []): array } return $plugins; - } + + }//end getAll() + /** * Show a single packadge installed trough composer. @@ -351,10 +387,12 @@ public function getAll(array $options = []): array * * @return array */ - public function require(string $packadge, array $options = []): array + public function require(string $packadge, array $options=[]): array { return $this->composerCall('require', $options, $packadge); - } + + }//end require() + /** * Show a single packadge installed trough composer. @@ -365,10 +403,12 @@ public function require(string $packadge, array $options = []): array * * @return array */ - public function upgrade(string $packadge, array $options = []): array + public function upgrade(string $packadge, array $options=[]): array { return $this->composerCall('upgrade', $options, $packadge); - } + + }//end upgrade() + /** * Show a single packadge installed trough composer. @@ -379,10 +419,12 @@ public function upgrade(string $packadge, array $options = []): array * * @return array */ - public function remove(string $packadge, array $options = []): array + public function remove(string $packadge, array $options=[]): array { return $this->composerCall('remove', $options, $packadge); - } + + }//end remove() + /** * Show a single packadge installed trough composer. @@ -393,19 +435,19 @@ public function remove(string $packadge, array $options = []): array * * @return array */ - public function getSingle(string $packadge, array $options = []): array + public function getSingle(string $packadge, array $options=[]): array { $url = 'https://packagist.org/packages/'.$packadge.'.json'; - $client = new \GuzzleHttp\Client(); + $client = new \GuzzleHttp\Client(); $response = $client->request('GET', $url); - $plugin = json_decode($response->getBody()->getContents(), true)['package']; + $plugin = json_decode($response->getBody()->getContents(), true)['package']; $installedPlugins = $this->getLockFile(); foreach ($installedPlugins as $installedPlugin) { if ($installedPlugin['name'] == $plugin['name']) { - $plugin = array_merge($installedPlugin, $plugin); + $plugin = array_merge($installedPlugin, $plugin); $plugin['update'] = false; // Lets see if we have newer versions than currently installer @@ -413,17 +455,20 @@ public function getSingle(string $packadge, array $options = []): array if (version_compare($plugin['version'], $version) < 0) { if (!$plugin['update']) { $plugin['update'] = $version; - } elseif (version_compare($plugin['update'], $version) < 0) { + } else if (version_compare($plugin['update'], $version) < 0) { $plugin['update'] = $version; } } } + break; } } return $plugin; - } + + }//end getSingle() + /** * Search for a given term. @@ -434,18 +479,20 @@ public function getSingle(string $packadge, array $options = []): array * * @return array */ - public function search(string $search = null, array $options = []): array + public function search(string $search=null, array $options=[]): array { - $url = 'https://packagist.org/search.json'; - $query = ['tags'=>'common-gateway-plugin']; + $url = 'https://packagist.org/search.json'; + $query = ['tags' => 'common-gateway-plugin']; if ($search) { $query['q'] = $search; } - $client = new \GuzzleHttp\Client(); - $response = $client->request('GET', 'https://packagist.org/search.json', [ - 'query' => $query, - ]); + $client = new \GuzzleHttp\Client(); + $response = $client->request( + 'GET', + 'https://packagist.org/search.json', + ['query' => $query] + ); $plugins = json_decode($response->getBody()->getContents(), true)['results']; @@ -455,7 +502,9 @@ public function search(string $search = null, array $options = []): array } return $plugins; - } + + }//end search() + /** * Search for a given term. @@ -466,8 +515,11 @@ public function search(string $search = null, array $options = []): array * * @return array */ - public function audit(array $options = []): array + public function audit(array $options=[]): array { return $this->composerCall('audit', $options); - } -} + + }//end audit() + + +}//end class diff --git a/src/Service/EavService.php b/src/Service/EavService.php index b84ae4cd..5f4a2fa9 100644 --- a/src/Service/EavService.php +++ b/src/Service/EavService.php @@ -15,13 +15,20 @@ */ class EavService { + private EntityManagerInterface $entityManager; + private CacheService $cacheService; + private array $configuration; + private array $data; + private ObjectEntity $object; + private string $id; + /** * @param EntityManagerInterface $entityManager */ @@ -30,8 +37,10 @@ public function __construct( CacheService $cacheService ) { $this->entityManager = $entityManager; - $this->cacheService = $cacheService; - } + $this->cacheService = $cacheService; + + }//end __construct() + /** * Checks an entity to see if there are anny atributtes waiting for it. @@ -46,8 +55,9 @@ public function checkEntityforAttribute(Entity $entity): Entity if (!$entity->getReference()) { return $entity; } + // Find the atribbutes - $attributes = $this->entityManager->getRepository('App:Attribute')->findBy(['reference'=>$entity->getReference(), 'object'=>null]); + $attributes = $this->entityManager->getRepository('App:Attribute')->findBy(['reference' => $entity->getReference(), 'object' => null]); // Add them to the entity foreach ($attributes as $attribute) { @@ -55,7 +65,9 @@ public function checkEntityforAttribute(Entity $entity): Entity } return $entity; - } + + }//end checkEntityforAttribute() + /** * Checks an atribute to see if a schema for its reference has becomme available. @@ -71,13 +83,15 @@ public function checkAttributeforEntity(Attribute $attribute): Attribute return $attribute; } - $entity = $this->entityManager->getRepository('App:Entity')->findOneBy(['reference'=>$attribute->getReference()]); + $entity = $this->entityManager->getRepository('App:Entity')->findOneBy(['reference' => $attribute->getReference()]); if ($entity !== null) { $attribute->setObject($entity); } return $attribute; - } + + }//end checkAttributeforEntity() + /** * Removes all object entities from the database (should obviusly not be used in production). @@ -105,5 +119,8 @@ public function deleteAllObjects(Entity $entity): bool } return true; - } -} + + }//end deleteAllObjects() + + +}//end class diff --git a/src/Service/EndpointService.php b/src/Service/EndpointService.php index 0cfc6b39..f27905e8 100644 --- a/src/Service/EndpointService.php +++ b/src/Service/EndpointService.php @@ -26,6 +26,7 @@ */ class EndpointService { + /** * @var EntityManagerInterface */ @@ -63,6 +64,7 @@ class EndpointService */ private ?Endpoint $endpoint = null; + /** * @param EntityManagerInterface $entityManager The enitymanger * @param SerializerInterface $serializer The serializer @@ -77,14 +79,16 @@ public function __construct( SessionInterface $session, LoggerInterface $endpointLogger ) { - $this->entityManager = $entityManager; - $this->serializer = $serializer; - $this->requestService = $requestService; + $this->entityManager = $entityManager; + $this->serializer = $serializer; + $this->requestService = $requestService; $this->eventDispatcher = $eventDispatcher; - $this->session = $session; - $this->logger = $endpointLogger; + $this->session = $session; + $this->logger = $endpointLogger; + }//end __construct() + /** * Handle the request afther it commes in through the ZZ controller. * @@ -110,8 +114,8 @@ public function handleRequest(Request $request): Response $this->logger->debug('Determine parameters for request'); $parameters = $this->getParametersFromRequest(); $parameters['endpoint'] = $endpoint; - $parameters['accept'] = $accept; - $parameters['body'] = $this->decodeBody(); + $parameters['accept'] = $accept; + $parameters['body'] = $this->decodeBody(); if (json_decode($request->get('payload'), true)) { $parameters['payload'] = json_decode($request->get('payload'), true); @@ -146,8 +150,10 @@ public function handleRequest(Request $request): Response $this->logger->error('No proxy, schema or events could be established for this endpoint'); throw new Exception('No proxy, schema or events could be established for this endpoint'); + }//end handleRequest() + /** * Gets the accept type based on the request. * @@ -169,37 +175,37 @@ public function getAcceptType(): string // Determine the accept type. $this->logger->debug('Determine accept type from accept header'); switch ($acceptHeader) { - case 'application/json': - return 'json'; - case 'application/json+hal': - case 'application/hal+json': - return 'jsonhal'; - case 'application/json+ld': - case 'application/ld+json': - return 'jsonld'; - case 'application/json+fromio': - case 'application/formio+json': - return 'formio'; - case 'application/json+schema': - case 'application/schema+json': - return 'schema'; - case 'application/json+graphql': - case 'application/graphql+json': - return 'graphql'; - case 'text/xml': - case 'application/xml': - return 'xml'; + case 'application/json': + return 'json'; + case 'application/json+hal': + case 'application/hal+json': + return 'jsonhal'; + case 'application/json+ld': + case 'application/ld+json': + return 'jsonld'; + case 'application/json+fromio': + case 'application/formio+json': + return 'formio'; + case 'application/json+schema': + case 'application/schema+json': + return 'schema'; + case 'application/json+graphql': + case 'application/graphql+json': + return 'graphql'; + case 'text/xml': + case 'application/xml': + return 'xml'; }//end switch // As a backup we look at any file extenstion. $this->logger->debug('Determine accept type from path extension'); - $path = $this->request->getPathInfo(); + $path = $this->request->getPathInfo(); $pathparts = explode('.', $path); if (count($pathparts) >= 2) { $extension = end($pathparts); switch ($extension) { - case 'pdf': - return 'pdf'; + case 'pdf': + return 'pdf'; }//end switch } @@ -207,8 +213,10 @@ public function getAcceptType(): string $this->logger->error('No proper accept could be determined'); throw new BadRequestException('No proper accept could be determined'); + }//end getAcceptType() + /** * Decodes the body of the request based upon the content-type header, accept header or endpoint default. * @@ -225,17 +233,19 @@ public function decodeBody(): ?array // Decode the body. switch ($contentType) { - case 'text/xml': - case 'application/xml': - case 'xml': - $xmlEncoder = new XmlEncoder(); - - return $xmlEncoder->decode($this->request->getContent(), 'xml'); - default: - return json_decode($this->request->getContent(), true); + case 'text/xml': + case 'application/xml': + case 'xml': + $xmlEncoder = new XmlEncoder(); + + return $xmlEncoder->decode($this->request->getContent(), 'xml'); + default: + return json_decode($this->request->getContent(), true); }//end switch + }//end decodeBody() + /** * Gets the endpoint based on the request. * @@ -245,8 +255,8 @@ public function decodeBody(): ?array */ public function getEndpoint(): Endpoint { - $path = $this->request->getPathInfo(); - $path = substr($path, 5); + $path = $this->request->getPathInfo(); + $path = substr($path, 5); $endpoint = $this->entityManager->getRepository('App:Endpoint')->findByMethodRegex($this->request->getMethod(), $path); if ($endpoint !== null) { @@ -254,8 +264,10 @@ public function getEndpoint(): Endpoint }//end if throw new Exception('No proper endpoint could be detirmend'); + }//end getEndpoint() + /** * Builds a parameter array from the request. * @@ -263,7 +275,7 @@ public function getEndpoint(): Endpoint * * @return array The parameter arrau */ - private function getParametersFromRequest(?array $parameters = []): array + private function getParametersFromRequest(?array $parameters=[]): array { // Lets make sure that we always have a path. $this->logger->debug('Get the raw path'); @@ -293,7 +305,7 @@ private function getParametersFromRequest(?array $parameters = []): array $this->logger->debug('Get general request information'); $parameters['method'] = $this->request->getMethod(); - $parameters['query'] = $this->request->query->all(); + $parameters['query'] = $this->request->query->all(); // Lets get all the headers. $parameters['headers'] = $this->request->headers->all(); @@ -302,5 +314,8 @@ private function getParametersFromRequest(?array $parameters = []): array $parameters['post'] = $this->request->request->all(); return $parameters; + }//end getParametersFromRequest() + + }//end class diff --git a/src/Service/FileService.php b/src/Service/FileService.php index 5d16f1da..fc7255ee 100644 --- a/src/Service/FileService.php +++ b/src/Service/FileService.php @@ -11,16 +11,23 @@ */ class FileService { + + public function writeFile(string $baseFileName, string $contents): string { $stamp = microtime().getmypid(); file_put_contents("/srv/api/var/$baseFileName-$stamp", $contents); return "/srv/api/var/$baseFileName-$stamp"; - } + + }//end writeFile() + public function removeFile($filename): void { unlink($filename); - } -} + + }//end removeFile() + + +}//end class diff --git a/src/Service/GatewayResourceService.php b/src/Service/GatewayResourceService.php index 8fe61dda..0918ff25 100644 --- a/src/Service/GatewayResourceService.php +++ b/src/Service/GatewayResourceService.php @@ -18,11 +18,12 @@ * * @license EUPL * - * @package commongateway/corebundle + * @package commongateway/corebundle * @category Service */ class GatewayResourceService { + /** * @var EntityManagerInterface */ @@ -33,6 +34,7 @@ class GatewayResourceService */ private LoggerInterface $pluginLogger; + /** * @param EntityManagerInterface $entityManager * @param LoggerInterface $pluginLogger @@ -40,8 +42,10 @@ class GatewayResourceService public function __construct(EntityManagerInterface $entityManager, LoggerInterface $pluginLogger) { $this->entityManager = $entityManager; - $this->pluginLogger = $pluginLogger; - } + $this->pluginLogger = $pluginLogger; + + }//end __construct() + /** * Get a schema by reference. @@ -55,12 +59,14 @@ public function getSchema(string $reference, string $pluginName): ?Entity { $entity = $this->entityManager->getRepository('App:Entity')->findOneBy(['reference' => $reference]); if ($entity === null) { - $this->pluginLogger->error("No entity found for $reference.", ['plugin'=>$pluginName]); + $this->pluginLogger->error("No entity found for $reference.", ['plugin' => $pluginName]); }//end if return $entity; + }//end getSchema() + /** * Get a mapping by reference. * @@ -73,12 +79,14 @@ public function getMapping(string $reference, string $pluginName): ?Mapping { $mapping = $this->entityManager->getRepository('App:Mapping')->findOneBy(['reference' => $reference]); if ($mapping === null) { - $this->pluginLogger->error("No mapping found for $reference.", ['plugin'=>$pluginName]); + $this->pluginLogger->error("No mapping found for $reference.", ['plugin' => $pluginName]); }//end if return $mapping; + }//end getMapping() + /** * Get a source by reference. * @@ -91,12 +99,14 @@ public function getSource(string $reference, string $pluginName): ?Source { $source = $this->entityManager->getRepository('App:Gateway')->findOneBy(['reference' => $reference]); if ($source === null) { - $this->pluginLogger->error("No source found for $reference.", ['plugin'=>$pluginName]); + $this->pluginLogger->error("No source found for $reference.", ['plugin' => $pluginName]); }//end if return $source; + }//end getSource() + /** * Get a source by reference. * @@ -109,9 +119,12 @@ public function getEndpoint(string $reference, string $pluginName): ?Endpoint { $source = $this->entityManager->getRepository('App:Endpoint')->findOneBy(['reference' => $reference]); if ($source === null) { - $this->pluginLogger->error("No endpoint found for $reference.", ['plugin'=>$pluginName]); + $this->pluginLogger->error("No endpoint found for $reference.", ['plugin' => $pluginName]); }//end if return $source; + }//end getEndpoint() -} + + +}//end class diff --git a/src/Service/InstallationService.php b/src/Service/InstallationService.php index dd72cd29..b1f9d6bf 100644 --- a/src/Service/InstallationService.php +++ b/src/Service/InstallationService.php @@ -14,7 +14,7 @@ use App\Entity\ObjectEntity; use App\Entity\Organization; use App\Entity\SecurityGroup; -//use App\Entity\User; +// use App\Entity\User; use App\Kernel; use Doctrine\ORM\EntityManagerInterface; use Exception; @@ -39,6 +39,7 @@ */ class InstallationService { + /** * @var ComposerService */ @@ -91,9 +92,10 @@ class InstallationService 'https://docs.commongateway.nl/schemas/Mapping.schema.json', 'https://docs.commongateway.nl/schemas/Organization.schema.json', 'https://docs.commongateway.nl/schemas/SecurityGroup.schema.json', - // 'https://docs.commongateway.nl/schemas/User.schema.json', + // 'https://docs.commongateway.nl/schemas/User.schema.json', ]; + /** * @codeCoverageIgnore We do not need to test constructors * @@ -110,13 +112,15 @@ public function __construct( LoggerInterface $installationLogger ) { $this->composerService = $composerService; - $this->entityManager = $entityManager; - $this->container = $kernel->getContainer(); - $this->logger = $installationLogger; - $this->schemaService = $schemaService; - $this->filesystem = new Filesystem(); + $this->entityManager = $entityManager; + $this->container = $kernel->getContainer(); + $this->logger = $installationLogger; + $this->schemaService = $schemaService; + $this->filesystem = new Filesystem(); + }//end __construct() + /** * Updates all commonground bundles on the common gateway installation. * @@ -128,7 +132,7 @@ public function __construct( * * @return int */ - public function update(array $config = []): int + public function update(array $config=[]): int { // Let's see if we are trying to update a single plugin. if (isset($config['plugin']) === true) { @@ -148,8 +152,10 @@ public function update(array $config = []): int } return Command::SUCCESS; + }//end update() + /** * Installs the files from a bundle. * @@ -162,7 +168,7 @@ public function update(array $config = []): int * * @return bool The result of the installation. */ - public function install(string $bundle, array $config = []): bool + public function install(string $bundle, array $config=[]): bool { $this->logger->debug('Installing plugin '.$bundle, ['plugin' => $bundle]); @@ -171,8 +177,10 @@ public function install(string $bundle, array $config = []): bool // Let's check the basic folders for legacy purposes. todo: remove these at some point $this->readDirectory($this->vendorFolder.'/'.$bundle.'/Action'); - $this->readDirectory($this->vendorFolder.'/'.$bundle.'/Schema'); // Entity - $this->readDirectory($this->vendorFolder.'/'.$bundle.'/Source'); // Gateway + $this->readDirectory($this->vendorFolder.'/'.$bundle.'/Schema'); + // Entity + $this->readDirectory($this->vendorFolder.'/'.$bundle.'/Source'); + // Gateway $this->readDirectory($this->vendorFolder.'/'.$bundle.'/Mapping'); $this->readDirectory($this->vendorFolder.'/'.$bundle.'/Data'); // A function that translates old core schema references to the new ones. Only here for backwards compatibility. @@ -187,8 +195,10 @@ public function install(string $bundle, array $config = []): bool $this->logger->debug('All Done installing plugin '.$bundle, ['bundle' => $bundle]); return true; + }//end install() + /** * Will handle all files found in the plugin, creating new objects using the $this->objects array. * @@ -222,6 +232,7 @@ private function handlePluginFiles(string $bundle, array $config) $this->logger->debug('Found '.count($schemas).' objects types for schema '.$ref, ['bundle' => $bundle, 'reference' => $ref]); $this->handleObjectType($ref, $schemas); } + unset($this->objects[$ref]); } @@ -233,8 +244,10 @@ private function handlePluginFiles(string $bundle, array $config) // Find and handle the installation.json file, if it exists. $this->handleInstallationJson($bundle); + }//end handlePluginFiles() + /** * Handles default / required test data from the data.json file if we are not loading in ALL testdata. * @@ -248,18 +261,21 @@ private function handleDataJson(string $bundle, array $config) // Handle default / required testdata in data.json file if we are not loading in ALL testdata. if (isset($config['data']) === false || $config['data'] === false) { $finder = new Finder(); - $files = $finder->in($this->vendorFolder.'/'.$bundle.'/Installation')->files()->name('data.json'); + $files = $finder->in($this->vendorFolder.'/'.$bundle.'/Installation')->files()->name('data.json'); $this->logger->debug('Found '.count($files).' data.json file(s)', ['bundle' => $bundle]); foreach ($files as $file) { $this->readfile($file); } + foreach ($this->objects as $ref => $schemas) { $this->handleObjectType($ref, $schemas); unset($this->objects[$ref]); } } + }//end handleDataJson() + /** * @param string $bundle The bundle. * @@ -272,7 +288,7 @@ private function handleInstallationJson(string $bundle) if ($this->filesystem->exists($this->vendorFolder.'/'.$bundle.'/Installation/installation.json') !== false) { $finder = new Finder(); // todo: maybe only allow installation.json file in root of Installation folder? -// $finder->depth('== 0'); + // $finder->depth('== 0'); $files = $finder->in($this->vendorFolder.'/'.$bundle.'/Installation')->files()->name('installation.json'); if (count($files) === 1) { $this->logger->debug('Found an installation.json file', ['bundle' => $bundle]); @@ -286,8 +302,10 @@ private function handleInstallationJson(string $bundle) // Save the objects created during handling installation.json to the database. $this->entityManager->flush(); } + }//end handleInstallationJson() + /** * For backwards compatibility, support old core schema reference and translate them to the new ones. * Todo: remove this function when we no longer need it. @@ -298,29 +316,33 @@ private function translateCoreReferences() { foreach ($this->objects as $translateFrom => $value) { switch ($translateFrom) { - case 'https://json-schema.org/draft/2020-12/action': - $translateTo = 'https://docs.commongateway.nl/schemas/Action.schema.json'; - break; - case 'https://json-schema.org/draft/2020-12/schema': - $translateTo = 'https://docs.commongateway.nl/schemas/Entity.schema.json'; - break; - case 'https://json-schema.org/draft/2020-12/source': - $translateTo = 'https://docs.commongateway.nl/schemas/Gateway.schema.json'; - break; - case 'https://json-schema.org/draft/2020-12/mapping': - $translateTo = 'https://docs.commongateway.nl/schemas/Mapping.schema.json'; - break; - default: - continue 2; + case 'https://json-schema.org/draft/2020-12/action': + $translateTo = 'https://docs.commongateway.nl/schemas/Action.schema.json'; + break; + case 'https://json-schema.org/draft/2020-12/schema': + $translateTo = 'https://docs.commongateway.nl/schemas/Entity.schema.json'; + break; + case 'https://json-schema.org/draft/2020-12/source': + $translateTo = 'https://docs.commongateway.nl/schemas/Gateway.schema.json'; + break; + case 'https://json-schema.org/draft/2020-12/mapping': + $translateTo = 'https://docs.commongateway.nl/schemas/Mapping.schema.json'; + break; + default: + continue 2; } + if (isset($this->objects[$translateTo]) === false) { $this->objects[$translateTo] = []; } + $this->objects[$translateTo] = array_merge($this->objects[$translateTo], $this->objects[$translateFrom]); unset($this->objects[$translateFrom]); - } + }//end foreach + }//end translateCoreReferences() + /** * This function reads a folder to find other folders or json objects. * @@ -360,9 +382,9 @@ private function readDirectory(string $location): bool // Make sure to warn users if they have to many files in a folder. (36 is maximum) if (count($hits->files()) > 34) { $this->logger->critical('Found more than 34 files in directory, try limiting your files to 32 per directory. Or you won\'t be able to load in these schema\'s locally on a windows machine.', ['location' => $location, 'files' => count($hits->files())]); - } elseif (count($hits->files()) > 32) { + } else if (count($hits->files()) > 32) { $this->logger->error('Found more than 32 files in directory, try limiting your files to 32 per directory. Or you won\'t be able to load in these schema\'s locally on a windows machine.', ['location' => $location, 'files' => count($hits->files())]); - } elseif (count($hits->files()) > 25) { + } else if (count($hits->files()) > 25) { $this->logger->warning('Found more than 25 files in directory, try limiting your files to 32 per directory. Or you won\'t be able to load in these schema\'s locally on a windows machine.', ['location' => $location, 'files' => count($hits->files())]); } @@ -371,12 +393,15 @@ private function readDirectory(string $location): bool if ($file->getFilename() === 'installation.json') { continue; } + $this->readfile($file); } return true; + }//end readDirectory() + /** * This function read a folder to find other folders or json objects. * @@ -395,19 +420,20 @@ private function readfile(SplFileInfo $file) } // Todo: validateJsonMapping does not exist -// // Check if it is a valid schema. -// $mappingSchema = $this->validateJsonMapping($mappingSchema); -// -// if ($this->validateJsonMapping($mappingSchema) === true) { -// $this->logger->error($file->getFilename().' is not a valid json-mapping object'); -// -// return false; -// } - + // Check if it is a valid schema. + // $mappingSchema = $this->validateJsonMapping($mappingSchema); + // + // if ($this->validateJsonMapping($mappingSchema) === true) { + // $this->logger->error($file->getFilename().' is not a valid json-mapping object'); + // + // return false; + // } // Add the file to the object. return $this->addToObjects($mappingSchema); + }//end readfile() + /** * Adds an object to the objects stack if it is valid. * @@ -430,6 +456,7 @@ private function addToObjects(array $schema) foreach ($value as $object) { $this->objects[$key][] = $object; } + continue; } @@ -438,8 +465,10 @@ private function addToObjects(array $schema) } return true; + }//end addToObjects() + /** * Handles schemas of a certain type. * @@ -459,7 +488,9 @@ private function handleObjectType(string $type, array $schemas): void // Save it to the database. $this->entityManager->persist($object); } - }//end handleObjectType(); + + }//end handleObjectType() + /** * Create an object bases on a type and a schema (the object as an array). @@ -505,8 +536,10 @@ private function handleObject(string $type, array $schema): ?object } return $object; + }//end handleObject() + /** * This function loads a core schema. * @@ -524,7 +557,8 @@ private function loadCoreSchema(array $schema, string $type): ?object return null; } - $type = $matches[1]; + + $type = $matches[1]; $query = explode(',', ltrim($matches[2], '?')); // Load it if we have it. @@ -552,17 +586,19 @@ private function loadCoreSchema(array $schema, string $type): ?object // Load the data. Todo: these version compare checks don't look right... if (array_key_exists('version', $schema) === true && version_compare($schema['version'], $object->getVersion()) <= 0) { $this->logger->debug('The schema has a version number equal or lower then the already present version, the object is NOT updated', ['schemaVersion' => $schema['version'], 'objectVersion' => $object->getVersion()]); - } elseif (array_key_exists('version', $schema) === true && version_compare($schema['version'], $object->getVersion()) > 0) { + } else if (array_key_exists('version', $schema) === true && version_compare($schema['version'], $object->getVersion()) > 0) { $this->logger->debug('The schema has a version number higher then the already present version, the object data is updated', ['schemaVersion' => $schema['version'], 'objectVersion' => $object->getVersion()]); $object->fromSchema($schema); - } elseif (array_key_exists('version', $schema) === false || $object->getVersion() === null) { + } else if (array_key_exists('version', $schema) === false || $object->getVersion() === null) { $this->logger->debug('The new schema doesn\'t have a version number, the object data is created', ['schemaVersion' => $schema['version'] ?? null, 'objectVersion' => $object->getVersion()]); $object->fromSchema($schema); } return $object; + }//end loadCoreSchema() + /** * Creates a new object of the given type. * @@ -573,35 +609,37 @@ private function loadCoreSchema(array $schema, string $type): ?object private function createNewObjectType(string $type): ?object { switch ($type) { - case 'Action': - return new Action(); - case 'Application': - return new Application(); - case 'CollectionEntity': - return new CollectionEntity(); - case 'Cronjob': - return new Cronjob(); - case 'DashboardCard': - return new DashboardCard(); - case 'Endpoint': - return new Endpoint(); - case 'Entity': - return new Entity(); - case 'Gateway': - return new Source(); - case 'Mapping': - return new Mapping(); - case 'Organization': - return new Organization(); - case 'SecurityGroup': - return new SecurityGroup(); -// case 'User': -// return new User(); - default: - return null; - } + case 'Action': + return new Action(); + case 'Application': + return new Application(); + case 'CollectionEntity': + return new CollectionEntity(); + case 'Cronjob': + return new Cronjob(); + case 'DashboardCard': + return new DashboardCard(); + case 'Endpoint': + return new Endpoint(); + case 'Entity': + return new Entity(); + case 'Gateway': + return new Source(); + case 'Mapping': + return new Mapping(); + case 'Organization': + return new Organization(); + case 'SecurityGroup': + return new SecurityGroup(); + // case 'User': + // return new User(); + default: + return null; + }//end switch + }//end createNewObjectType() + /** * This function loads an non-core schema. * @@ -639,8 +677,10 @@ private function loadSchema(array $schema, string $type): ?ObjectEntity $object->hydrate($schema); return $object; + }//end loadSchema() + /** * Specifically handles the installation file. * @@ -676,6 +716,7 @@ private function handleInstaller(SplFileInfo $file): bool if (isset($data['actions']['handlers']) === true) { $this->createActions($data['actions']['handlers']); } + // Fix references in configuration of these actions. if (isset($data['actions']['fixConfigRef']) === true) { $this->fixConfigRef($data['actions']['fixConfigRef']); @@ -704,8 +745,9 @@ private function handleInstaller(SplFileInfo $file): bool } catch (Exception $exception) { $error = "{$file->getFilename()} Could not be loaded from container: {$exception->getMessage()}"; } + if (empty($installationService) === true || isset($error) === true) { - $this->logger->error($error ?? "{$file->getFilename()} Could not be loaded from container"); + $this->logger->error(($error ?? "{$file->getFilename()} Could not be loaded from container")); return false; } @@ -719,8 +761,10 @@ private function handleInstaller(SplFileInfo $file): bool return false; } + }//end handleInstaller() + /** * This functions connects schema's with a reference containing the collection schemaPrefix to the given collection. * This way endpoints will be created with the correct prefix. @@ -729,7 +773,7 @@ private function handleInstaller(SplFileInfo $file): bool * * @return void */ - private function updateSchemasCollection(array $collectionsData = []) + private function updateSchemasCollection(array $collectionsData=[]) { $collections = 0; @@ -744,6 +788,7 @@ private function updateSchemasCollection(array $collectionsData = []) $this->logger->error('No valid schemaPrefix given while trying to add collection to schema\'s', ['reference' => $collectionData['reference']]); continue; } + $this->addSchemasToCollection($collection, $collectionData['schemaPrefix']); $collections++; @@ -752,8 +797,10 @@ private function updateSchemasCollection(array $collectionsData = []) } $this->logger->info("Updated schemas for $collections Collections"); + }//end updateSchemasCollection() + /** * Adds a collection to all schemas that have a reference starting with $schemaPrefix. * @@ -768,8 +815,10 @@ private function addSchemasToCollection(CollectionEntity $collection, string $sc foreach ($entities as $entity) { $entity->addCollection($collection); } + }//end addSchemasToCollection() + /** * This function creates endpoints for an array of schema references or source references. * @@ -777,7 +826,7 @@ private function addSchemasToCollection(CollectionEntity $collection, string $sc * * @return array An array of endpoints */ - private function createEndpoints(array $endpointsData = []): array + private function createEndpoints(array $endpointsData=[]): array { $endpoints = []; @@ -792,9 +841,9 @@ private function createEndpoints(array $endpointsData = []): array // Then we can handle some data. foreach ($endpointTypeData as $endpointData) { // Just in case unset these. - $subEndpoints = $endpointData['subEndpoints'] ?? []; + $subEndpoints = ($endpointData['subEndpoints'] ?? []); unset($endpointData['subEndpoints']); - $subSchemaEndpoints = $endpointData['subSchemaEndpoints'] ?? []; + $subSchemaEndpoints = ($endpointData['subSchemaEndpoints'] ?? []); unset($endpointData['subSchemaEndpoints']); // Create the base Endpoint. @@ -802,20 +851,23 @@ private function createEndpoints(array $endpointsData = []): array if ($endpoint === null) { continue; } + $endpoints[] = $endpoint; // Handle sub and subSchema Endpoints. (will always create an endpoint for type 'schemas') $endpointData['$id'] = $endpoint->getReference(); - $endpoints = array_merge($endpoints, $this->handleSubEndpoints($endpointData, $subEndpoints)); - $endpoints = array_merge($endpoints, $this->handleSubSchemaEndpoints($endpointData, $subSchemaEndpoints)); + $endpoints = array_merge($endpoints, $this->handleSubEndpoints($endpointData, $subEndpoints)); + $endpoints = array_merge($endpoints, $this->handleSubSchemaEndpoints($endpointData, $subSchemaEndpoints)); } }//end foreach $this->logger->info(count($endpoints).' Endpoints Created'); return $endpoints; + }//end createEndpoints() + /** * Creates a single endpoint for an Entity or a Source using the data from installation.json. * @@ -840,6 +892,7 @@ private function createEndpoint(string $type, array $endpointData): ?Endpoint $endpointData['entities'][] = $object; } } + unset($endpointData['schemas']); } else { $object = $this->checkIfObjectExists($repository, $endpointData['reference'], $type); @@ -865,8 +918,10 @@ private function createEndpoint(string $type, array $endpointData): ?Endpoint $this->logger->debug('Endpoint created for '.(isset($object) === true ? $object->getReference() : 'multipleSchemas').' with reference: '.$endpointData['$id']); return $endpoint; + }//end createEndpoint() + /** * Constructs an Endpoint using the Endpoint constructor, but how the constructor is called depends on the $type. * @@ -880,19 +935,21 @@ private function constructEndpoint(string $type, $object, array $endpointData): { // todo ? maybe create a second constructor? So we can do Endpoint($object, $endpointData); switch ($type) { - case 'sources': - return new Endpoint(null, $object, $endpointData); - case 'schemas': - return new Endpoint($object, null, $endpointData); - case 'multipleSchemas': - return new Endpoint(null, null, $endpointData); + case 'sources': + return new Endpoint(null, $object, $endpointData); + case 'schemas': + return new Endpoint($object, null, $endpointData); + case 'multipleSchemas': + return new Endpoint(null, null, $endpointData); } $this->logger->error('Unknown type used for endpoint construction: '.$type); return null; + }//end constructEndpoint() + /** * Checks if an object exists, using the given repository and reference. * @@ -912,8 +969,10 @@ private function checkIfObjectExists($repository, string $reference, string $typ } return $object; + }//end checkIfObjectExists() + /** * Creates a reference for a new Endpoint using the name of the object we are creating it for and the domain of its reference. * @@ -938,10 +997,12 @@ private function createEndpointReference($object, string $type): ?string } $endpointType = $type === 'sources' ? 'Proxy' : 'Entity'; - $name = str_replace(' ', '-', $object->getName()); + $name = str_replace(' ', '-', $object->getName()); return "https://{$parsedUrl['host']}/{$endpointType}Endpoint/$name.endpoint.json"; - } + + }//end createEndpointReference() + /** * Creates the basics for a new subEndpoint or subSchemaEndpoint. @@ -963,8 +1024,10 @@ private function createBaseEndpoint(array $baseEndpointData, array $newEndpointD } return $this->createEndpoint('schemas', $endpointData); + }//end createBaseEndpoint() + /** * Updates some basic fields like name, description and throws for a new subEndpoint or subSchemaEndpoint. * @@ -983,14 +1046,17 @@ private function setEndpointBasics(Endpoint $newEndpoint, array $newEndpointData $newEndpoint->setThrows($newEndpointData['throws']); // Throws only trigger when an Endpoint has no entities. - $newEndpoint->setEntity(null); // Old way of setting Entity for Endpoints + $newEndpoint->setEntity(null); + // Old way of setting Entity for Endpoints foreach ($newEndpoint->getEntities() as $removeEntity) { $newEndpoint->removeEntity($removeEntity); } return $newEndpoint; + }//end setEndpointBasics() + /** * Creates subEndpoints for an Entity Endpoint. Example: domain.com/api/entities/subEndpoint['path']. * @@ -1017,7 +1083,7 @@ private function handleSubEndpoints(array $baseEndpointData, array $subEndpoints continue; } - $path = $subEndpoint->getPath(); + $path = $subEndpoint->getPath(); $path[] = $subEndpointData['path']; $subEndpoint->setPath($path); @@ -1028,10 +1094,12 @@ private function handleSubEndpoints(array $baseEndpointData, array $subEndpoints $subEndpoint = $this->setEndpointBasics($subEndpoint, $subEndpointData); $this->entityManager->persist($subEndpoint); - } + }//end foreach return $endpoints; - }//end handleSubSchemaEndpoints() + + }//end handleSubEndpoints() + /** * Creates subSchemaEndpoints for an Entity Endpoint. Example: domain.com/api/entities/{uuid}/subSchemaEndpoint['path']/{uuid}. @@ -1078,11 +1146,13 @@ private function handleSubSchemaEndpoints(array $baseEndpointData, array $subSch $subSchemaEndpoint = $this->setEndpointBasics($subSchemaEndpoint, $subSchemaEndpointData); $this->entityManager->persist($subSchemaEndpoint); - } + }//end foreach return $endpoints; + }//end handleSubSchemaEndpoints() + /** * This functions creates actions for an array of handlers. * @@ -1090,7 +1160,7 @@ private function handleSubSchemaEndpoints(array $baseEndpointData, array $subSch * * @return array An array of Action objects */ - private function createActions(array $handlersData = []): array + private function createActions(array $handlersData=[]): array { $actions = []; @@ -1112,23 +1182,26 @@ private function createActions(array $handlersData = []): array $action = new Action($actionHandler); array_key_exists('name', $handlerData) ? $action->setName($handlerData['name']) : ''; array_key_exists('reference', $handlerData) ? $action->setReference($handlerData['reference']) : ''; - $action->setListens($handlerData['listens'] ?? []); - $action->setConditions($handlerData['conditions'] ?? ['==' => [1, 1]]); + $action->setListens(($handlerData['listens'] ?? [])); + $action->setConditions(($handlerData['conditions'] ?? ['==' => [1, 1]])); - $defaultConfig = $this->addActionConfiguration($actionHandler); // todo: maybe use: Action->getDefaultConfigFromSchema() instead? - isset($handlerData['configuration']) && $defaultConfig = $this->overrideConfig($defaultConfig, $handlerData['configuration'] ?? []); + $defaultConfig = $this->addActionConfiguration($actionHandler); + // todo: maybe use: Action->getDefaultConfigFromSchema() instead? + isset($handlerData['configuration']) && $defaultConfig = $this->overrideConfig($defaultConfig, ($handlerData['configuration'] ?? [])); $action->setConfiguration($defaultConfig); $this->entityManager->persist($action); $actions[] = $action; $this->logger->debug('Action created for '.$handlerData['actionHandler'].' with class '.get_class($actionHandler)); - } + }//end foreach $this->logger->info(count($actions).' Actions Created'); return $actions; + }//end createActions() + /** * This functions replaces references in the action->configuration array with corresponding ids of the entity/source. * @@ -1136,7 +1209,7 @@ private function createActions(array $handlersData = []): array * * @return void An array of Action objects */ - private function fixConfigRef(array $actionRefs = []): void + private function fixConfigRef(array $actionRefs=[]): void { $actions = 0; @@ -1153,24 +1226,27 @@ private function fixConfigRef(array $actionRefs = []): void } $actionHandler = $this->container->get($action->getClass()); - $schema = $actionHandler->getConfiguration(); + $schema = $actionHandler->getConfiguration(); if (empty($schema) === true) { $this->logger->error('Handler '.$action->getClass().' has no configuration'); continue; } - $defaultConfig = $this->addActionConfiguration($actionHandler); // todo: maybe use: Action->getDefaultConfigFromSchema() instead? - empty($action->getConfiguration()) === false && $defaultConfig = $this->overrideConfig($defaultConfig, $action->getConfiguration() ?? []); + $defaultConfig = $this->addActionConfiguration($actionHandler); + // todo: maybe use: Action->getDefaultConfigFromSchema() instead? + empty($action->getConfiguration()) === false && $defaultConfig = $this->overrideConfig($defaultConfig, ($action->getConfiguration() ?? [])); $action->setConfiguration($defaultConfig); $this->entityManager->persist($action); $actions++; - } + }//end foreach $this->logger->info($actions.' Actions configuration updated.'); + }//end fixConfigRef() + /** * This function creates default configuration for the action. * @@ -1183,32 +1259,35 @@ public function addActionConfiguration($actionHandler): array $defaultConfig = []; foreach ($actionHandler->getConfiguration()['properties'] as $key => $value) { switch ($value['type']) { - case 'string': - case 'array': - if (isset($value['example'])) { - $defaultConfig[$key] = $value['example']; - } - break; - case 'object': - break; - case 'uuid': - if (isset($value['$ref'])) { - try { - $entity = $this->entityManager->getRepository('App:Entity')->findOneBy(['reference' => $value['$ref']]); - } catch (Exception $exception) { - $this->logger->error("No entity found with reference {$value['$ref']} (addActionConfiguration() for installation.json)"); - } - $defaultConfig[$key] = $entity->getId()->toString(); + case 'string': + case 'array': + if (isset($value['example'])) { + $defaultConfig[$key] = $value['example']; + } + break; + case 'object': + break; + case 'uuid': + if (isset($value['$ref'])) { + try { + $entity = $this->entityManager->getRepository('App:Entity')->findOneBy(['reference' => $value['$ref']]); + } catch (Exception $exception) { + $this->logger->error("No entity found with reference {$value['$ref']} (addActionConfiguration() for installation.json)"); } - break; - default: - // throw error - } - } + + $defaultConfig[$key] = $entity->getId()->toString(); + } + break; + default: + // throw error + }//end switch + }//end foreach return $defaultConfig; + }//end addActionConfiguration() + /** * Overrides the default configuration of an Action. Will also set entity and source to id if a reference is given. * @@ -1222,28 +1301,32 @@ public function overrideConfig(array $defaultConfig, array $overrides): array foreach ($overrides as $key => $override) { if (is_array($override) && $this->isAssociative($override)) { $defaultConfig[$key] = $this->overrideConfig(isset($defaultConfig[$key]) ? $defaultConfig[$key] : [], $override); - } elseif ($key == 'entity' && is_string($override) && Uuid::isValid($override) === false) { + } else if ($key == 'entity' && is_string($override) && Uuid::isValid($override) === false) { $entity = $this->entityManager->getRepository('App:Entity')->findOneBy(['reference' => $override]); if (!$entity) { $this->logger->error("No entity found with reference {$override} (overrideConfig() for installation.json)"); continue; } + $defaultConfig[$key] = $entity->getId()->toString(); - } elseif ($key == 'source' && is_string($override) && Uuid::isValid($override) === false) { + } else if ($key == 'source' && is_string($override) && Uuid::isValid($override) === false) { $source = $this->entityManager->getRepository('App:Gateway')->findOneBy(['reference' => $override]); if (!$source) { $this->logger->error("No source found with reference {$override} (overrideConfig() for installation.json)"); continue; } + $defaultConfig[$key] = $source->getId()->toString(); } else { $defaultConfig[$key] = $override; - } - } + }//end if + }//end foreach return $defaultConfig; + }//end overrideConfig() + /** * Decides if an array is associative. * @@ -1257,9 +1340,11 @@ private function isAssociative(array $array): bool return false; } - return array_keys($array) !== range(0, count($array) - 1); + return array_keys($array) !== range(0, (count($array) - 1)); + }//end isAssociative() + /** * This function creates cronjobs for an array of action references. * @@ -1267,7 +1352,7 @@ private function isAssociative(array $array): bool * * @return array An array of cronjobs */ - private function createCronjobs(array $actions = []): array + private function createCronjobs(array $actions=[]): array { $cronjobs = []; @@ -1288,8 +1373,10 @@ private function createCronjobs(array $actions = []): array $this->logger->info(count($cronjobs).' Cronjobs Created'); return $cronjobs; + }//end createCronjobs() + /** * This functions creates dashboard cars for an array of endpoints, sources, schema's or objects. * @@ -1299,7 +1386,7 @@ private function createCronjobs(array $actions = []): array * * @return array An array of dashboardCard objects */ - private function createCards(array $cardsData = []): array + private function createCards(array $cardsData=[]): array { $cards = []; @@ -1307,46 +1394,46 @@ private function createCards(array $cardsData = []): array foreach ($cardsData as $type => $references) { // Let's determine the proper repo to use. switch ($type) { - case 'actions': - $repository = $this->entityManager->getRepository('App:Action'); - break; - case 'applications': - $repository = $this->entityManager->getRepository('App:Application'); - break; - case 'collections': - $repository = $this->entityManager->getRepository('App:CollectionEntity'); - break; - case 'cronjobs': - $repository = $this->entityManager->getRepository('App:Cronjob'); - break; - case 'endpoints': - $repository = $this->entityManager->getRepository('App:Endpoint'); - break; - case 'schemas': - $repository = $this->entityManager->getRepository('App:Entity'); - break; - case 'sources': - $repository = $this->entityManager->getRepository('App:Gateway'); - break; - case 'mappings': - $repository = $this->entityManager->getRepository('App:Mapping'); - break; - case 'objects': - $repository = $this->entityManager->getRepository('App:ObjectEntity'); - break; - case 'organizations': - $repository = $this->entityManager->getRepository('App:Organization'); - break; -// case 'securityGroups': -// $repository = $this->entityManager->getRepository('App:SecurityGroup'); -// break; -// case 'users': -// $repository = $this->entityManager->getRepository('App:User'); -// break; - default: - // We can't do anything so... - $this->logger->error('Unknown type used for the creation of a dashboard card: '.$type); - continue 2; + case 'actions': + $repository = $this->entityManager->getRepository('App:Action'); + break; + case 'applications': + $repository = $this->entityManager->getRepository('App:Application'); + break; + case 'collections': + $repository = $this->entityManager->getRepository('App:CollectionEntity'); + break; + case 'cronjobs': + $repository = $this->entityManager->getRepository('App:Cronjob'); + break; + case 'endpoints': + $repository = $this->entityManager->getRepository('App:Endpoint'); + break; + case 'schemas': + $repository = $this->entityManager->getRepository('App:Entity'); + break; + case 'sources': + $repository = $this->entityManager->getRepository('App:Gateway'); + break; + case 'mappings': + $repository = $this->entityManager->getRepository('App:Mapping'); + break; + case 'objects': + $repository = $this->entityManager->getRepository('App:ObjectEntity'); + break; + case 'organizations': + $repository = $this->entityManager->getRepository('App:Organization'); + break; + // case 'securityGroups': + // $repository = $this->entityManager->getRepository('App:SecurityGroup'); + // break; + // case 'users': + // $repository = $this->entityManager->getRepository('App:User'); + // break; + default: + // We can't do anything so... + $this->logger->error('Unknown type used for the creation of a dashboard card: '.$type); + continue 2; }//end switch // Then we can handle some data. @@ -1366,7 +1453,7 @@ private function createCards(array $cardsData = []): array } $dashboardCard = new DashboardCard($object); - $cards[] = $dashboardCard; + $cards[] = $dashboardCard; $this->entityManager->persist($dashboardCard); $this->logger->debug('Dashboard Card created for '.$reference); } @@ -1375,5 +1462,8 @@ private function createCards(array $cardsData = []): array $this->logger->info(count($cards).' Cards Created'); return $cards; + }//end createCards() + + }//end class diff --git a/src/Service/MappingService.php b/src/Service/MappingService.php index 51b4e6d4..932e59f0 100644 --- a/src/Service/MappingService.php +++ b/src/Service/MappingService.php @@ -20,12 +20,14 @@ */ class MappingService { + // Add symfony style bundle in order to output to the console. private SymfonyStyle $io; // Create a private variable to store the twig environment private Environment $twig; + /** * Setting up the base class with required services. * @@ -35,7 +37,9 @@ public function __construct( Environment $twig ) { $this->twig = $twig; - } + + }//end __construct() + /** * Set symfony style in order to output to the console. @@ -49,7 +53,9 @@ public function setStyle(SymfonyStyle $io): self $this->io = $io; return $this; - } + + }//end setStyle() + /** * Replaces strings in array keys, helpful for characters like . in array keys. @@ -75,8 +81,10 @@ private function encodeArrayKeys(array $array, string $toReplace, string $replac } return $result; + }//end encodeArrayKeys() + /** * Maps (transforms) an array (input) to a different array (output). * @@ -89,16 +97,16 @@ public function mapping(Mapping $mappingObject, array $input): array { $input = $this->encodeArrayKeys($input, '.', '.'); - isset($this->io) ?? $this->io->debug('Mapping array based on mapping object '.$mappingObject->getName().' (id:'.$mappingObject->getId()->toString().' / ref:'.$mappingObject->getReference().') v:'.$mappingObject->getversion()); + (isset($this->io) ?? $this->io->debug('Mapping array based on mapping object '.$mappingObject->getName().' (id:'.$mappingObject->getId()->toString().' / ref:'.$mappingObject->getReference().') v:'.$mappingObject->getversion())); // Determine pass trough // Let's get the dot array based on https://github.com/adbario/php-dot-notation if ($mappingObject->getPassTrough()) { $dotArray = new Dot($input); - isset($this->io) ?? $this->io->debug('Mapping *with* pass trough'); + (isset($this->io) ?? $this->io->debug('Mapping *with* pass trough')); } else { $dotArray = new Dot(); - isset($this->io) ?? $this->io->debug('Mapping *without* pass trough'); + (isset($this->io) ?? $this->io->debug('Mapping *without* pass trough')); } $dotInput = new Dot($input); @@ -118,16 +126,17 @@ public function mapping(Mapping $mappingObject, array $input): array // Unset unwanted key's foreach ($mappingObject->getUnset() as $unset) { if (!$dotArray->has($unset)) { - isset($this->io) ?? $this->io->debug("Trying to unset an property that doesn't exist during mapping"); + (isset($this->io) ?? $this->io->debug("Trying to unset an property that doesn't exist during mapping")); continue; } + $dotArray->delete($unset); } // Cast values to a specific type foreach ($mappingObject->getCast() as $key => $cast) { if (!$dotArray->has($key)) { - isset($this->io) ?? $this->io->debug("Trying to cast an property that doesn't exist during mapping"); + (isset($this->io) ?? $this->io->debug("Trying to cast an property that doesn't exist during mapping")); continue; } @@ -136,45 +145,45 @@ public function mapping(Mapping $mappingObject, array $input): array // todo: this works, we should go to php 8.0 later if (str_starts_with($cast, 'unsetIfValue==')) { $unsetIfValue = substr($cast, 14); - $cast = 'unsetIfValue'; + $cast = 'unsetIfValue'; } switch ($cast) { - case 'int': - case 'integer': - $value = intval($value); - break; - case 'bool': - case 'boolean': - echo 'i equals 1'; - break; - case 'string': - echo 'i equals 2'; - break; - case 'keyCantBeValue': - if ($key == $value) { - $dotArray->delete($key); - } - break; - case 'unsetIfValue': - if (isset($unsetIfValue) === true && $value == $unsetIfValue) { - $dotArray->delete($key); - } - break; + case 'int': + case 'integer': + $value = intval($value); + break; + case 'bool': + case 'boolean': + echo 'i equals 1'; + break; + case 'string': + echo 'i equals 2'; + break; + case 'keyCantBeValue': + if ($key == $value) { + $dotArray->delete($key); + } + break; + case 'unsetIfValue': + if (isset($unsetIfValue) === true && $value == $unsetIfValue) { + $dotArray->delete($key); + } + break; // Todo: Add more casts - case 'jsonToArray': - $value = str_replace(['"', '&quot;'], '"', $value); - $value = json_decode($value, true); - default: - isset($this->io) ?? $this->io->debug('Trying to cast to an unsupported cast type: '.$cast); - break; - } + case 'jsonToArray': + $value = str_replace(['"', '&quot;'], '"', $value); + $value = json_decode($value, true); + default: + (isset($this->io) ?? $this->io->debug('Trying to cast to an unsupported cast type: '.$cast)); + break; + }//end switch // dont reset key that was deleted on purpose if ($dotArray->has($key)) { $dotArray->set($key, $value); } - } + }//end foreach // Back to array $output = $dotArray->all(); @@ -186,13 +195,19 @@ public function mapping(Mapping $mappingObject, array $input): array } // Log the result - isset($this->io) ?? $this->io->debug('Mapped object', [ - 'input' => $input, - 'output' => $output, - 'passTrough' => $mappingObject->getPassTrough(), - 'mapping' => $mappingObject->getMapping(), - ]); + (isset($this->io) ?? $this->io->debug( + 'Mapped object', + [ + 'input' => $input, + 'output' => $output, + 'passTrough' => $mappingObject->getPassTrough(), + 'mapping' => $mappingObject->getMapping(), + ] + )); return $output; - } -} + + }//end mapping() + + +}//end class diff --git a/src/Service/OasService.php b/src/Service/OasService.php index 975a07eb..29181b7f 100644 --- a/src/Service/OasService.php +++ b/src/Service/OasService.php @@ -17,6 +17,7 @@ */ class OasService { + /** * @var EntityManagerInterface */ @@ -27,6 +28,7 @@ class OasService */ private ParameterBagInterface $parameters; + /** * @param EntityManagerInterface $entityManager The Entity Manager */ @@ -35,9 +37,11 @@ public function __construct( ParameterBagInterface $parameters ) { $this->entityManager = $entityManager; - $this->parameters = $parameters; + $this->parameters = $parameters; + }//end __construct() + /** * Create an OAS documentation for a specific application. * @@ -47,13 +51,13 @@ public function createOas(): array { // Setup the basic oas array. $oas = [ - 'openapi' => '3.0.0', - 'info' => [ + 'openapi' => '3.0.0', + 'info' => [ 'title' => 'Common Gateway', 'description' => 'The Common Gateway is a further Dutch development of the European API Platform. API Platform is a project of Les Tilleus and, in itself, an extension of the Symfony framework. API Platform is a tool for delivering APIs based on standardized documentation and is used for various French and German government projects. Including Digital state, a precursor to Xroute, GOV.UK and Common Ground. The project is now part of joinup.eu (the European equivalent of Common Ground).', 'version' => '1.0.3', ], - 'servers' => [ + 'servers' => [ [ 'url' => $this->parameters->get('app_url', 'https://localhost'), 'description' => 'The kubernetes server', @@ -72,7 +76,9 @@ public function createOas(): array $oas = $this->addSecurity($oas); return $oas; - }//end createOas(); + + }//end createOas() + /** * Adds the endpoints to an OAS Array. @@ -101,17 +107,21 @@ private function addEndpoints(array $oas): array $pathArray[] = '{'.$path.'}'; continue; } + $pathArray[] = $path; } + $oas['paths']['/'.implode('/', $pathArray)] = $this->getEndpointOperations($endpoint); // Add the schemas. $oas['components']['schemas'] = array_merge($oas['components']['schemas'], $this->getEndpointSchemas($endpoint)); - } + }//end foreach return $oas; + }//end addEndpoints() + /** * Gets the operations for a given endpoint. * @@ -142,7 +152,7 @@ private function getEndpointOperations(Endpoint $endpoint): array 'example' => 'Object is successfully deleted', ], ], - 'application/xml' => [ + 'application/xml' => [ 'schema' => [ 'type' => 'string', 'example' => 'Object is successfully deleted', @@ -153,7 +163,7 @@ private function getEndpointOperations(Endpoint $endpoint): array ], ]; continue; - } + }//end if // In all other cases we want include a schema. $operations[strtolower($method)] = [ @@ -162,32 +172,31 @@ private function getEndpointOperations(Endpoint $endpoint): array 'tags' => [strtolower($endpoint->getName())], 'description' => $endpoint->getDescription(), 'parameters' => [ - ['name' => 'id', + [ + 'name' => 'id', 'in' => 'path', 'description' => '', 'required' => true, - 'schema' => [ - 'type' => 'string', - ], + 'schema' => ['type' => 'string'], ], ], 'requestBody' => [ 'description' => $endpoint->getDescription(), - //'required' =>// Todo: figure out what we want to do here - 'content' => [ + // 'required' =>// Todo: figure out what we want to do here + 'content' => [ 'application/json' => [ 'schema' => [ '$ref' => '#/components/schemas/'.$endpoint->getEntities()->first()->getName(), ], ], - 'application/xml' => [ + 'application/xml' => [ 'schema' => [ '$ref' => '#/components/schemas/'.$endpoint->getEntities()->first()->getName(), ], ], ], ], - 'responses' => [ + 'responses' => [ '200' => [ 'description' => $endpoint->getDescription(), 'content' => [ @@ -196,7 +205,7 @@ private function getEndpointOperations(Endpoint $endpoint): array '$ref' => '#/components/schemas/'.$endpoint->getEntities()->first()->getName(), ], ], - 'application/xml' => [ + 'application/xml' => [ 'schema' => [ '$ref' => '#/components/schemas/'.$endpoint->getEntities()->first()->getName(), ], @@ -215,8 +224,10 @@ private function getEndpointOperations(Endpoint $endpoint): array }//end foreach return $operations; + }//end getEndpointOperations() + /** * Get the schema's for a given endpoint. * @@ -233,8 +244,10 @@ private function getEndpointSchemas(Endpoint $endpoint): array } return $schemas; + }//end getEndpointSchemas() + /** * Add the security to an OAS array. * @@ -245,5 +258,8 @@ private function getEndpointSchemas(Endpoint $endpoint): array private function addSecurity(array $oas): array { return $oas; + }//end addSecurity() + + }//end class diff --git a/src/Service/RequestService.php b/src/Service/RequestService.php index 35086e0d..36089f24 100644 --- a/src/Service/RequestService.php +++ b/src/Service/RequestService.php @@ -35,24 +35,42 @@ */ class RequestService { + private EntityManagerInterface $entityManager; + private CacheService $cacheService; + private array $configuration; + private array $data; + private ObjectEntity $object; + private string $id; - private $schema; // todo: cast to Entity|Boolean in php 8 + + private $schema; + + // todo: cast to Entity|Boolean in php 8 // todo: we might want to move or rewrite code instead of using these services here: private ResponseService $responseService; + private ObjectEntityService $objectEntityService; + private LogService $logService; + private CallService $callService; + private Security $security; + private EventDispatcherInterface $eventDispatcher; + private SerializerInterface $serializer; + private SessionInterface $session; + private LoggerInterface $logger; + /** * @param EntityManagerInterface $entityManager * @param CacheService $cacheService @@ -79,18 +97,20 @@ public function __construct( SessionInterface $session, LoggerInterface $requestLogger ) { - $this->entityManager = $entityManager; - $this->cacheService = $cacheService; - $this->responseService = $responseService; + $this->entityManager = $entityManager; + $this->cacheService = $cacheService; + $this->responseService = $responseService; $this->objectEntityService = $objectEntityService; - $this->logService = $logService; - $this->callService = $callService; - $this->security = $security; - $this->eventDispatcher = $eventDispatcher; - $this->serializer = $serializer; + $this->logService = $logService; + $this->callService = $callService; + $this->security = $security; + $this->eventDispatcher = $eventDispatcher; + $this->serializer = $serializer; $this->session = $session; - $this->logger = $requestLogger; - } + $this->logger = $requestLogger; + + }//end __construct() + /** * A function to replace Request->query->all() because Request->query->all() will replace some characters with an underscore. @@ -101,7 +121,7 @@ public function __construct( * * @return array An array with all query parameters. */ - public function realRequestQueryAll(string $method = 'get', ?string $queryString = ''): array + public function realRequestQueryAll(string $method='get', ?string $queryString=''): array { $vars = []; if (strtolower($method) === 'get' && empty($this->data['querystring']) && empty($queryString)) { @@ -110,8 +130,8 @@ public function realRequestQueryAll(string $method = 'get', ?string $queryString $pairs = explode('&', empty($queryString) === false ? $queryString : $_SERVER['QUERY_STRING']); foreach ($pairs as $pair) { - $nv = explode('=', $pair); - $name = urldecode($nv[0]); + $nv = explode('=', $pair); + $name = urldecode($nv[0]); $value = ''; if (count($nv) == 2) { $value = urldecode($nv[1]); @@ -121,7 +141,9 @@ public function realRequestQueryAll(string $method = 'get', ?string $queryString } return $vars; - } + + }//end realRequestQueryAll() + /** * Get the ID from given parameters. @@ -135,24 +157,27 @@ public function getId(array $object) // Try to grap an id if (isset($this->data['path']['{id}'])) { return $this->data['path']['{id}']; - } elseif (isset($this->data['path']['[id]'])) { + } else if (isset($this->data['path']['[id]'])) { return $this->data['path']['[id]']; - } elseif (isset($this->data['query']['id'])) { + } else if (isset($this->data['query']['id'])) { return $this->data['query']['id']; - } elseif (isset($this->data['path']['id'])) { + } else if (isset($this->data['path']['id'])) { return$this->data['path']['id']; - } elseif (isset($this->data['path']['{uuid}'])) { + } else if (isset($this->data['path']['{uuid}'])) { return $this->data['path']['{uuid}']; - } elseif (isset($this->data['query']['uuid'])) { + } else if (isset($this->data['query']['uuid'])) { return$this->data['query']['uuid']; - } elseif (isset($this->content['id'])) { // the id might also be passed trough the object itself + } else if (isset($this->content['id'])) { + // the id might also be passed trough the object itself return $this->content['id']; - } elseif (isset($this->content['uuid'])) { + } else if (isset($this->content['uuid'])) { return $this->content['uuid']; } return false; - } + + }//end getId() + /** * Get the schema from given parameters returns false if no schema could be established. @@ -172,9 +197,11 @@ public function getSchema(array $parameters) if (isset($this->content['_self']['schema']['id'])) { $id = $this->content['_self']['schema']['id']; } + if (isset($this->content['_self']['schema']['ref'])) { $reference = $this->content['_self']['schema']['ref']; } + if (isset($this->content['_self']['schema']['reference'])) { $reference = $this->content['_self']['schema']['reference']; } @@ -185,6 +212,7 @@ public function getSchema(array $parameters) if (count($this->data['endpoint']->getEntities()) == 1) { return $this->data['endpoint']->getEntities()->first(); } + // The endpoint contains multiple schema's if (count($this->data['endpoint']->getEntities()) >= 1) { // todo: so right now if we dont have an id or ref and multpile options we "guese" the first, it that smart? @@ -192,19 +220,22 @@ public function getSchema(array $parameters) if (isset($id)) { $criteria->where(['id' => $id]); } + if (isset($reference)) { $criteria->where(['reference' => $reference]); } return $this->data['endpoint']->getEntities()->matching($criteria)->first(); } + // The endpoint contains no schema's so there is no limit we dont need to do anything - } + }//end if // We only end up here if there is no endpoint or an unlimited endpoint if (isset($id)) { return $this->entityManager->getRepository('App:Entity')->findOneBy(['id' => $id]); } + if (isset($reference)) { return $this->entityManager->getRepository('App:Entity')->findOneBy(['reference' => $reference]); } @@ -212,7 +243,9 @@ public function getSchema(array $parameters) else { return false; } - } + + }//end getSchema() + /** * This function adds a single query param to the given $vars array. ?$name=$value @@ -233,11 +266,11 @@ private function recursiveRequestQueryKey(array &$vars, string $name, string $na { $matchesCount = preg_match('/(\[[^[\]]*])/', $name, $matches); if ($matchesCount > 0) { - $key = $matches[0]; + $key = $matches[0]; $name = str_replace($key, '', $name); - $key = trim($key, '[]'); + $key = trim($key, '[]'); if (!empty($key)) { - $vars[$nameKey] = $vars[$nameKey] ?? []; + $vars[$nameKey] = ($vars[$nameKey] ?? []); $this->recursiveRequestQueryKey($vars[$nameKey], $name, $key, $value); } else { $vars[$nameKey][] = $value; @@ -245,7 +278,9 @@ private function recursiveRequestQueryKey(array &$vars, string $name, string $na } else { $vars[$nameKey] = $value; } - } + + }//end recursiveRequestQueryKey() + /** * @param array $data The data from the call @@ -253,18 +288,16 @@ private function recursiveRequestQueryKey(array &$vars, string $name, string $na * * @return Response The data as returned bij the origanal source */ - public function proxyHandler(array $data, array $configuration, ?Source $proxy = null): Response + public function proxyHandler(array $data, array $configuration, ?Source $proxy=null): Response { - $this->data = $data; + $this->data = $data; $this->configuration = $configuration; // If we already have a proxy, we can skip these checks. if ($proxy instanceof Source === false) { // We only do proxying if the endpoint forces it, and we do not have a proxy. if (!$data['endpoint'] instanceof Endpoint || !$proxy = $data['endpoint']->getProxy()) { - $message = !$data['endpoint'] instanceof Endpoint ? - "No Endpoint in data['endpoint']" : - "This Endpoint has no Proxy: {$data['endpoint']->getName()}"; + $message = !$data['endpoint'] instanceof Endpoint ? "No Endpoint in data['endpoint']" : "This Endpoint has no Proxy: {$data['endpoint']->getName()}"; return new Response( json_encode(['Message' => $message]), @@ -276,7 +309,8 @@ public function proxyHandler(array $data, array $configuration, ?Source $proxy = if ($proxy instanceof Source && !$proxy->getIsEnabled()) { return new Response( json_encode(['Message' => "This Source is not enabled: {$proxy->getName()}"]), - Response::HTTP_OK, // This should be ok, so we can disable Sources without creating error responses? + Response::HTTP_OK, + // This should be ok, so we can disable Sources without creating error responses? ['content-type' => 'application/json'] ); } @@ -311,23 +345,29 @@ public function proxyHandler(array $data, array $configuration, ?Source $proxy = $result->getHeaders() ); } catch (Exception $exception) { - $statusCode = $exception->getCode() ?? 500; + $statusCode = ($exception->getCode() ?? 500); if (method_exists(get_class($exception), 'getResponse') === true && $exception->getResponse() !== null) { - $body = $exception->getResponse()->getBody()->getContents(); + $body = $exception->getResponse()->getBody()->getContents(); $statusCode = $exception->getResponse()->getStatusCode(); - $headers = $exception->getResponse()->getHeaders(); + $headers = $exception->getResponse()->getHeaders(); } - $content = $this->serializer->serialize([ - 'Message' => $exception->getMessage(), - 'Body' => $body ?? "Can\'t get a response & body for this type of Exception: ".get_class($exception), - ], 'json'); - $response = new Response($content, $statusCode, $headers ?? []); - } + + $content = $this->serializer->serialize( + [ + 'Message' => $exception->getMessage(), + 'Body' => ($body ?? "Can\'t get a response & body for this type of Exception: ").get_class($exception), + ], + 'json' + ); + $response = new Response($content, $statusCode, ($headers ?? [])); + }//end try // And don so lets return what we have. return $response; + }//end proxyHandler() + /** * Get a scopes array for the current user (or of the anonymus if no user s logged in). * @@ -338,7 +378,7 @@ public function getScopes(): ?array if ($user = $this->security->getUser()) { return $user->getScopes(); } else { - $anonymousSecurityGroup = $this->entityManager->getRepository('App:SecurityGroup')->findOneBy(['anonymous'=>true]); + $anonymousSecurityGroup = $this->entityManager->getRepository('App:SecurityGroup')->findOneBy(['anonymous' => true]); if ($anonymousSecurityGroup) { return $anonymousSecurityGroup->getScopes(); } @@ -346,7 +386,9 @@ public function getScopes(): ?array // Lets play it save return []; - } + + }//end getScopes() + /** * Handles incomming requests and is responsible for generating a response. @@ -358,20 +400,20 @@ public function getScopes(): ?array */ public function requestHandler(array $data, array $configuration): Response { - $this->data = $data; + $this->data = $data; $this->configuration = $configuration; $filters = []; // haat aan de de _ if (isset($this->data['querystring'])) { - // $query = explode('&',$this->data['querystring']); - // foreach ($query as $row) { - // $row = explode('=', $row); - // $key = $row[0]; - // $value = $row[1]; - // $filters[$key] = $value; - // } + // $query = explode('&',$this->data['querystring']); + // foreach ($query as $row) { + // $row = explode('=', $row); + // $key = $row[0]; + // $value = $row[1]; + // $filters[$key] = $value; + // } $filters = $this->realRequestQueryAll($this->data['method']); } @@ -388,8 +430,8 @@ public function requestHandler(array $data, array $configuration): Response foreach ($this->data['path'] as $key => $value) { if (strpos($key, '{') !== false) { if ($key !== '{id}') { - $keyExplodedFilter = explode('{', $key); - $keyFilter = explode('}', $keyExplodedFilter[1]); + $keyExplodedFilter = explode('{', $key); + $keyFilter = explode('}', $keyExplodedFilter[1]); $filters['_search'] = $value; } } @@ -406,10 +448,12 @@ public function requestHandler(array $data, array $configuration): Response if ($this->schema !== false) { $this->session->set('schema', $this->schema->getId()->toString()); } + // Bit os savety cleanup <- dit zou eigenlijk in de hydrator moeten gebeuren -// unset($this->content['id']); + // unset($this->content['id']); unset($this->content['_id']); - unset($this->content['_self']); // todo: i don't think this does anything useful? + unset($this->content['_self']); + // todo: i don't think this does anything useful? unset($this->content['_schema']); // todo: make this a function, like eavService->getRequestExtend() @@ -429,16 +473,16 @@ public function requestHandler(array $data, array $configuration): Response $extend = $dot->all(); } - $metadataSelf = $extend['_self'] ?? []; - // todo: controlleren of de gebruiker ingelogd is + $metadataSelf = ($extend['_self'] ?? []); + // todo: controlleren of de gebruiker ingelogd is // Make a list of schema's that are allowed for this endpoint - $allowedSchemas['id'] = []; + $allowedSchemas['id'] = []; $allowedSchemas['name'] = []; if (isset($this->data['endpoint'])) { foreach ($this->data['endpoint']->getEntities() as $entity) { - $allowedSchemas['id'][] = $entity->getId()->toString(); + $allowedSchemas['id'][] = $entity->getId()->toString(); $allowedSchemas['name'][] = $entity->getName(); } } @@ -454,203 +498,216 @@ public function requestHandler(array $data, array $configuration): Response // All prepped so lets go // todo: split these into functions? switch ($this->data['method']) { - case 'GET': - // We have an id (so single object) - if (isset($this->id) && $this->id) { - $this->session->set('object', $this->id); - $result = $this->cacheService->getObject($this->id); - - // If we do not have an object we throw an 404 - if ($result === null) { - return new Response($this->serializer->serialize([ - 'message' => 'Could not find an object with id '.$this->id, - 'type' => 'Bad Request', - 'path' => implode(', ', $allowedSchemas['name']), - 'data' => ['id' => $this->id], - ], 'json'), Response::HTTP_NOT_FOUND); - } - - // Lets see if the found result is allowd for this endpoint - if (isset($this->data['endpoint']) && !in_array($result['_self']['schema']['id'], $allowedSchemas['id'])) { - return new Response('Object is not supported by this endpoint', '406'); - } - - // create log - // todo if $this->content is array and not string/null, cause someone could do a get item call with a body... - $responseLog = new Response(is_string($this->content) || is_null($this->content) ? $this->content : null, 200, ['CoreBundle' => 'GetItem']); - $session = new Session(); - $session->set('object', $this->id); - - // todo: This log is needed so we know an user has 'read' this object - $this->logService->saveLog($this->logService->makeRequest(), $responseLog, 15, is_array($this->content) ? json_encode($this->content) : $this->content); - } else { - //$this->data['query']['_schema'] = $this->data['endpoint']->getEntities()->first()->getReference(); - $result = $this->cacheService->searchObjects(null, $filters, $allowedSchemas['id']); + case 'GET': + // We have an id (so single object) + if (isset($this->id) && $this->id) { + $this->session->set('object', $this->id); + $result = $this->cacheService->getObject($this->id); + + // If we do not have an object we throw an 404 + if ($result === null) { + return new Response( + $this->serializer->serialize( + [ + 'message' => 'Could not find an object with id '.$this->id, + 'type' => 'Bad Request', + 'path' => implode(', ', $allowedSchemas['name']), + 'data' => ['id' => $this->id], + ], + 'json' + ), + Response::HTTP_NOT_FOUND + ); } - break; - case 'POST': - $eventType = 'commongateway.object.create'; - - // We have an id on a post so die - if (isset($this->id) === true && empty($this->id) === false) { - $this->session->set('object', $this->id); - $this->logger->error('You can not POST to an (existing) id, consider using PUT or PATCH instead'); - return new Response('You can not POST to an (existing) id, consider using PUT or PATCH instead', '400'); + // Lets see if the found result is allowd for this endpoint + if (isset($this->data['endpoint']) && !in_array($result['_self']['schema']['id'], $allowedSchemas['id'])) { + return new Response('Object is not supported by this endpoint', '406'); } - // We need to know the type of object that the user is trying to post, so lets look that up - if ($this->schema instanceof Entity === false) { - $this->logger->error('No schema could be established for your request'); + // create log + // todo if $this->content is array and not string/null, cause someone could do a get item call with a body... + $responseLog = new Response(is_string($this->content) || is_null($this->content) ? $this->content : null, 200, ['CoreBundle' => 'GetItem']); + $session = new Session(); + $session->set('object', $this->id); - return new Response('No schema could be established for your request', '400'); - } + // todo: This log is needed so we know an user has 'read' this object + $this->logService->saveLog($this->logService->makeRequest(), $responseLog, 15, is_array($this->content) ? json_encode($this->content) : $this->content); + } else { + // $this->data['query']['_schema'] = $this->data['endpoint']->getEntities()->first()->getReference(); + $result = $this->cacheService->searchObjects(null, $filters, $allowedSchemas['id']); + }//end if + break; + case 'POST': + $eventType = 'commongateway.object.create'; + + // We have an id on a post so die + if (isset($this->id) === true && empty($this->id) === false) { + $this->session->set('object', $this->id); + $this->logger->error('You can not POST to an (existing) id, consider using PUT or PATCH instead'); - // Lets see if the found result is allowed for this endpoint - if (isset($this->data['endpoint']) === true && in_array($this->schema->getId(), $allowedSchemas['id']) === false) { - $this->logger->error('Object is not supported by this endpoint'); + return new Response('You can not POST to an (existing) id, consider using PUT or PATCH instead', '400'); + } - return new Response('Object is not supported by this endpoint', '406'); - } + // We need to know the type of object that the user is trying to post, so lets look that up + if ($this->schema instanceof Entity === false) { + $this->logger->error('No schema could be established for your request'); - $this->object = new ObjectEntity($this->schema); - $this->object->setOwner($this->security->getUser()->getUserIdentifier()); - - $this->logger->debug('Hydrating object'); - //if ($validation = $this->object->validate($this->content) && $this->object->hydrate($content, true)) { - if ($this->object->hydrate($this->content, true)) { - $this->entityManager->persist($this->object); - $this->session->set('object', $this->object->getId()->toString()); - $this->cacheService->cacheObject($this->object); /* @todo this is hacky, the above schould alredy do this */ - } else { - // Use validation to throw an error - } + return new Response('No schema could be established for your request', '400'); + } - $result = $this->cacheService->getObject($this->object->getId()); - break; - case 'PUT': - $eventType = 'commongateway.object.update'; + // Lets see if the found result is allowed for this endpoint + if (isset($this->data['endpoint']) === true && in_array($this->schema->getId(), $allowedSchemas['id']) === false) { + $this->logger->error('Object is not supported by this endpoint'); - // We dont have an id on a PUT so die - if (!isset($this->id)) { - $this->logger->error('No id could be established for your request'); + return new Response('Object is not supported by this endpoint', '406'); + } - return new Response('No id could be established for your request', '400'); - } - $this->session->set('object', $this->id); + $this->object = new ObjectEntity($this->schema); + $this->object->setOwner($this->security->getUser()->getUserIdentifier()); - // We need to know the type of object that the user is trying to post, so lets look that up - if ($this->schema instanceof Entity === false) { - $this->logger->error('No schema could be established for your request'); + $this->logger->debug('Hydrating object'); + // if ($validation = $this->object->validate($this->content) && $this->object->hydrate($content, true)) { + if ($this->object->hydrate($this->content, true)) { + $this->entityManager->persist($this->object); + $this->session->set('object', $this->object->getId()->toString()); + $this->cacheService->cacheObject($this->object); + // @todo this is hacky, the above schould alredy do this + } else { + // Use validation to throw an error + } - return new Response('No schema could be established for your request', '400'); - } + $result = $this->cacheService->getObject($this->object->getId()); + break; + case 'PUT': + $eventType = 'commongateway.object.update'; - // Lets see if the found result is allowd for this endpoint - if (isset($this->data['endpoint']) && !in_array($this->schema->getId(), $allowedSchemas['id'])) { - $this->logger->error('Object is not supported by this endpoint'); + // We dont have an id on a PUT so die + if (!isset($this->id)) { + $this->logger->error('No id could be established for your request'); - return new Response('Object is not supported by this endpoint', '406'); - } + return new Response('No id could be established for your request', '400'); + } - $this->object = $this->entityManager->find('App:ObjectEntity', $this->id); - - //if ($validation = $this->object->validate($this->content) && $this->object->hydrate($content, true)) { - $this->logger->debug('updating object '.$this->id); - if ($this->object->hydrate($this->content, true)) { // This should be an unsafe hydration - if (array_key_exists('@dateRead', $this->content) && $this->content['@dateRead'] == false) { - $this->objectEntityService->setUnread($this->object); - } - $this->entityManager->persist($this->object); - $this->entityManager->flush(); - } else { - // Use validation to throw an error - } + $this->session->set('object', $this->id); - $result = $this->cacheService->getObject($this->object->getId()); - break; - case 'PATCH': - $eventType = 'commongateway.object.update'; + // We need to know the type of object that the user is trying to post, so lets look that up + if ($this->schema instanceof Entity === false) { + $this->logger->error('No schema could be established for your request'); - // We dont have an id on a PATCH so die - if (!isset($this->id)) { - $this->logger->error('No id could be established for your request'); + return new Response('No schema could be established for your request', '400'); + } - return new Response('No id could be established for your request', '400'); - } - $this->session->set('object', $this->id); + // Lets see if the found result is allowd for this endpoint + if (isset($this->data['endpoint']) && !in_array($this->schema->getId(), $allowedSchemas['id'])) { + $this->logger->error('Object is not supported by this endpoint'); - // We need to know the type of object that the user is trying to post, so lets look that up - if ($this->schema instanceof Entity === false) { - $this->logger->error('No schema could be established for your request'); + return new Response('Object is not supported by this endpoint', '406'); + } - return new Response('No schema could be established for your request', '400'); + $this->object = $this->entityManager->find('App:ObjectEntity', $this->id); + + // if ($validation = $this->object->validate($this->content) && $this->object->hydrate($content, true)) { + $this->logger->debug('updating object '.$this->id); + if ($this->object->hydrate($this->content, true)) { + // This should be an unsafe hydration + if (array_key_exists('@dateRead', $this->content) && $this->content['@dateRead'] == false) { + $this->objectEntityService->setUnread($this->object); } - // Lets see if the found result is allowd for this endpoint - if (isset($this->data['endpoint']) && !in_array($this->schema->getId(), $allowedSchemas['id'])) { - $this->logger->error('Object is not supported by this endpoint'); + $this->entityManager->persist($this->object); + $this->entityManager->flush(); + } else { + // Use validation to throw an error + } - return new Response('Object is not supported by this endpoint', '406'); - } + $result = $this->cacheService->getObject($this->object->getId()); + break; + case 'PATCH': + $eventType = 'commongateway.object.update'; - $this->object = $this->entityManager->find('App:ObjectEntity', $this->id); - - //if ($this->object->hydrate($this->content) && $validation = $this->object->validate()) { - $this->logger->debug('updating object '.$this->id); - if ($this->object->hydrate($this->content)) { - if (array_key_exists('@dateRead', $this->content) && $this->content['@dateRead'] == false) { - $this->objectEntityService->setUnread($this->object); - } - $this->entityManager->persist($this->object); - $this->entityManager->flush(); - } else { - // Use validation to throw an error - } + // We dont have an id on a PATCH so die + if (!isset($this->id)) { + $this->logger->error('No id could be established for your request'); - $result = $this->cacheService->getObject($this->object->getId()); - break; - case 'DELETE': + return new Response('No id could be established for your request', '400'); + } - // We dont have an id on a PUT so die - if (!isset($this->id)) { - $this->logger->error('No id could be established for your request'); + $this->session->set('object', $this->id); - return new Response('No id could be established for your request', '400'); - } - $this->session->set('object', $this->id); + // We need to know the type of object that the user is trying to post, so lets look that up + if ($this->schema instanceof Entity === false) { + $this->logger->error('No schema could be established for your request'); - // We need to know the type of object that the user is trying to post, so lets look that up - if ($this->schema instanceof Entity === false) { - $this->logger->error('No schema could be established for your request'); + return new Response('No schema could be established for your request', '400'); + } - return new Response('No schema could be established for your request', '400'); - } + // Lets see if the found result is allowd for this endpoint + if (isset($this->data['endpoint']) && !in_array($this->schema->getId(), $allowedSchemas['id'])) { + $this->logger->error('Object is not supported by this endpoint'); - // Lets see if the found result is allowd for this endpoint - if (isset($this->data['endpoint']) && !in_array($this->schema->getId(), $allowedSchemas['id'])) { - $this->logger->error('Object is not supported by this endpoint'); + return new Response('Object is not supported by this endpoint', '406'); + } - return new Response('Object is not supported by this endpoint', '406'); + $this->object = $this->entityManager->find('App:ObjectEntity', $this->id); + + // if ($this->object->hydrate($this->content) && $validation = $this->object->validate()) { + $this->logger->debug('updating object '.$this->id); + if ($this->object->hydrate($this->content)) { + if (array_key_exists('@dateRead', $this->content) && $this->content['@dateRead'] == false) { + $this->objectEntityService->setUnread($this->object); } - $this->entityManager->remove($this->object); - // $this->cacheService - removeObject($this->id); /* @todo this is hacky, the above schould alredy do this */ + $this->entityManager->persist($this->object); $this->entityManager->flush(); - $this->logger->info('Succesfully deleted object'); + } else { + // Use validation to throw an error + } - return new Response('Succesfully deleted object', '202'); - default: - break; + $result = $this->cacheService->getObject($this->object->getId()); + break; + case 'DELETE': + + // We dont have an id on a PUT so die + if (!isset($this->id)) { + $this->logger->error('No id could be established for your request'); + + return new Response('No id could be established for your request', '400'); + } + + $this->session->set('object', $this->id); + + // We need to know the type of object that the user is trying to post, so lets look that up + if ($this->schema instanceof Entity === false) { + $this->logger->error('No schema could be established for your request'); + + return new Response('No schema could be established for your request', '400'); + } + + // Lets see if the found result is allowd for this endpoint + if (isset($this->data['endpoint']) && !in_array($this->schema->getId(), $allowedSchemas['id'])) { + $this->logger->error('Object is not supported by this endpoint'); + + return new Response('Object is not supported by this endpoint', '406'); + } + + $this->entityManager->remove($this->object); + // $this->cacheService - removeObject($this->id); /* @todo this is hacky, the above schould alredy do this */ + $this->entityManager->flush(); + $this->logger->info('Succesfully deleted object'); + + return new Response('Succesfully deleted object', '202'); + default: + break; $this->logger->error('Unkown method'.$this->data['method']); return new Response('Unkown method'.$this->data['method'], '404'); - } + }//end switch $this->entityManager->flush(); if (isset($eventType) === true && isset($result) === true) { - $event = new ActionEvent($eventType, ['response' => $result, 'entity' => $this->object->getEntity()->getReference() ?? $this->object->getEntity()->getId()->toString()]); + $event = new ActionEvent($eventType, ['response' => $result, 'entity' => ($this->object->getEntity()->getReference() ?? $this->object->getEntity()->getId()->toString())]); $this->eventDispatcher->dispatch($event, $event->getType()); // If we have a response return that @@ -670,7 +727,9 @@ public function requestHandler(array $data, array $configuration): Response } return $this->createResponse($result); - } + + }//end requestHandler() + /** * If embedded should be shown or not. @@ -686,10 +745,9 @@ public function shouldWeUnsetEmbedded($result, array $embeddedConfig) return $result; } - if ( - isset($result) + if (isset($result) && (isset($embeddedConfig['unset']['except']) === true && isset($this->data['headers']['accept']) === true - && empty(array_intersect($embeddedConfig['unset']['except'], $this->data['headers']['accept'])) === true) + && empty(array_intersect($embeddedConfig['unset']['except'], $this->data['headers']['accept'])) === true) || isset($this->data['headers']['accept']) === false || isset($embeddedConfig['unset']['except']) === false ) { @@ -703,7 +761,9 @@ public function shouldWeUnsetEmbedded($result, array $embeddedConfig) } return $result; - } + + }//end shouldWeUnsetEmbedded() + /** * If embedded should be shown or not. @@ -716,12 +776,14 @@ public function checkEmbedded($result) { if (isset($result->embedded)) { unset($result->embedded); - } elseif (isset($result['embedded'])) { + } else if (isset($result['embedded'])) { unset($result['embedded']); } return $result; - } + + }//end checkEmbedded() + /** * @TODO @@ -740,9 +802,12 @@ private function handleMetadataSelf(&$result, array $metadataSelf) // todo: $this->id is sometimes empty, it should never be an empty string if (isset($result['results']) && $this->data['method'] === 'GET' && empty($this->id)) { - array_walk($result['results'], function (&$record) { - $record = iterator_to_array($record); - }); + array_walk( + $result['results'], + function (&$record) { + $record = iterator_to_array($record); + } + ); foreach ($result['results'] as &$collectionItem) { $this->handleMetadataSelf($collectionItem, $metadataSelf); } @@ -753,19 +818,24 @@ private function handleMetadataSelf(&$result, array $metadataSelf) if (empty($result['id']) || !Uuid::isValid($result['id'])) { return; } + $objectEntity = $this->entityManager->getRepository('App:ObjectEntity')->findOneBy(['id' => $result['id']]); if (!$objectEntity instanceof ObjectEntity) { return; } + if ($this->data['method'] === 'GET' && !empty($this->id)) { $metadataSelf['dateRead'] = 'getItem'; } + $this->responseService->xCommongatewayMetadata = $metadataSelf; $resultMetadataSelf = (array) $result['_self']; $this->responseService->addToMetadata($resultMetadataSelf, 'dateRead', $objectEntity); $result['_self'] = $resultMetadataSelf; - } + + }//end handleMetadataSelf() + /** * @param array $data The data from the call @@ -775,54 +845,57 @@ private function handleMetadataSelf(&$result, array $metadataSelf) */ public function itemRequestHandler(array $data, array $configuration): array { - $this->data = $data; + $this->data = $data; $this->configuration = $configuration; - $method = $this->data['request']->getMethod(); + $method = $this->data['request']->getMethod(); $content = $this->data['request']->getContent(); // Lets see if we have an object if (array_key_exists('id', $this->data)) { $this->id = $data['id']; - $object = $this->cacheService->getObject($data['id']); + $object = $this->cacheService->getObject($data['id']); if ($object === null) { // Throw not found return []; } + $this->object = $object; } switch ($method) { - case 'GET': - break; - case 'PUT': + case 'GET': + break; + case 'PUT': - if ($validation = $this->object->validate($content) && $this->object->hydrate($content, true)) { - $this->entityManager->persist($this->object); - } else { - // Use validation to throw an error - } - break; - case 'PATCH': - if ($this->object->hydrate($content) && $validation = $this->object->validate()) { - $this->entityManager->persist($this->object); - } else { - // Use validation to throw an error - } - break; - case 'DELETE': - $this->entityManager->remove($this->object); + if ($validation = $this->object->validate($content) && $this->object->hydrate($content, true)) { + $this->entityManager->persist($this->object); + } else { + // Use validation to throw an error + } + break; + case 'PATCH': + if ($this->object->hydrate($content) && $validation = $this->object->validate()) { + $this->entityManager->persist($this->object); + } else { + // Use validation to throw an error + } + break; + case 'DELETE': + $this->entityManager->remove($this->object); - return new Response('', '202'); - break; - default: + return new Response('', '202'); break; - } + default: + break; + }//end switch $this->entityManager->flush(); return $this->createResponse($this->object); - } + + }//end itemRequestHandler() + /** * This function searches all the objectEntities and formats the data. @@ -834,15 +907,16 @@ public function itemRequestHandler(array $data, array $configuration): array */ public function searchRequestHandler(array $data, array $configuration): array { - $this->data = $data; + $this->data = $data; $this->configuration = $configuration; if (!$searchEntityId = $this->configuration['searchEntityId']) { $objectEntities = $this->entityManager->getRepository('App:ObjectEntity')->findAll(); } else { - $searchEntity = $this->entityManager->getRepository('App:Entity')->findBy($searchEntityId); + $searchEntity = $this->entityManager->getRepository('App:Entity')->findBy($searchEntityId); $objectEntities = $this->entityManager->getRepository('App:ObjectEntity')->findAll(); } + $response = []; foreach ($objectEntities as $objectEntity) { $response[] = [ @@ -858,7 +932,9 @@ public function searchRequestHandler(array $data, array $configuration): array ); return $this->data; - } + + }//end searchRequestHandler() + /** * Determines the proxy source from configuration, then use proxy handler to proxy the request. @@ -875,8 +951,10 @@ public function proxyRequestHandler(array $parameters, array $configuration): ar $data['response'] = $this->proxyHandler($parameters, $configuration, $source); return $data; + }//end proxyRequestHandler() + /** * Creating the response object. * @@ -889,7 +967,6 @@ public function createResponse($data): Response if ($data instanceof ObjectEntity) { $data = $data->toArray(); } else { - // } return new Response( @@ -897,5 +974,8 @@ public function createResponse($data): Response 200, ['content-type' => 'application/json'] ); - } -} + + }//end createResponse() + + +}//end class diff --git a/src/Service/SchemaService.php b/src/Service/SchemaService.php index 88c2d5fd..27949772 100644 --- a/src/Service/SchemaService.php +++ b/src/Service/SchemaService.php @@ -20,6 +20,7 @@ */ class SchemaService { + /** * @var EntityManagerInterface */ @@ -35,6 +36,7 @@ class SchemaService */ private SessionInterface $session; + /** * @param EntityManagerInterface $entityManager The entity manager */ @@ -43,9 +45,11 @@ public function __construct( LoggerInterface $schemaLogger ) { $this->entityManager = $entityManager; - $this->logger = $schemaLogger; + $this->logger = $schemaLogger; + }//end __construct() + /** * Validates the objects in the EAV setup. * @@ -64,8 +68,10 @@ public function validateObjects(): int // ToDo: Build. } } + }//end validateObjects() + /** * Validates the objects in the EAV setup. * @@ -83,8 +89,10 @@ public function validateValues(): int $this->logger->error('Value '.$value->getStringValue().' ('.$value->getId().') that belongs to '.$value->getAttribute()->getName().' ('.$value->getAttribute()->getId().') is orpahned'); } } + }//end validateValues() + /** * Validates the schemas in the EAV setup. * @@ -103,8 +111,10 @@ public function validateSchemas(): int }//end foreach return 1; + }//end validateSchemas() + /** * Validates a single schema. * @@ -151,13 +161,15 @@ public function validateSchema(Entity $schema): bool if ($status === true) { $this->logger->info('Schema '.$schema->getName().' ('.$schema->getId().') has been checked and is fine'); - } elseif ($status === false) { + } else if ($status === false) { $this->logger->error('Schema '.$schema->getName().' ('.$schema->getId().') has been checked and has an error'); } return $status; + }//end validateSchema() + /** * Validates a single atribute. * @@ -196,8 +208,10 @@ public function validateAtribute(Attribute $attribute): bool } return $status; + }//end validateAtribute() + /** * Handles forced id's on object entities. * @@ -206,7 +220,7 @@ public function validateAtribute(Attribute $attribute): bool * * @return ObjectEntity The PERSISTED object entity on the forced id */ - public function hydrate(ObjectEntity $objectEntity, array $hydrate = []): ObjectEntity + public function hydrate(ObjectEntity $objectEntity, array $hydrate=[]): ObjectEntity { // This savety dosn't make sense but we need it. if ($objectEntity->getEntity() === null) { @@ -262,8 +276,9 @@ public function hydrate(ObjectEntity $objectEntity, array $hydrate = []): Object $newObject = new ObjectEntity($valueObject->getAttribute()->getObject()); $newObject = $this->hydrate($newObject, $subvalue); $valueObject->addObject($newObject); - } else { // Is not an array. - $idValue = $subvalue; + } else { + // Is not an array. + $idValue = $subvalue; $subvalue = $this->entityManager->getRepository('App:ObjectEntity')->findOneBy(['id' => $idValue]); // Savety. if ($subvalue === null) { @@ -276,7 +291,7 @@ public function hydrate(ObjectEntity $objectEntity, array $hydrate = []): Object } else { // The use of gettype is discoureged, but we don't use it as a bl here and only for logging text purposes. So a design decicion was made te allow it. $this->logger->error($valueObject->getAttribute()->getName().' Is a multiple so should be filled with an array, but provided value was '.$value.'(type: '.gettype($value).')'); - } + }//end if continue; }//end if @@ -290,21 +305,22 @@ public function hydrate(ObjectEntity $objectEntity, array $hydrate = []): Object } $newObject = new ObjectEntity($valueObject->getAttribute()->getObject()); - $value = $this->hydrate($newObject, $value); + $value = $this->hydrate($newObject, $value); $valueObject->setValue($value); - } else { // Is not an array. + } else { + // Is not an array. $idValue = $value; - $value = $this->entityManager->getRepository('App:ObjectEntity')->findOneBy(['id' => $idValue]); + $value = $this->entityManager->getRepository('App:ObjectEntity')->findOneBy(['id' => $idValue]); // Savety. if ($value === null) { $this->logger->error('Could not find an object for id '.$idValue.' (SchemaService->hydrate)'); } else { $valueObject->setValue($value); } - } + }//end if } else { $valueObject->setValue($value); - } + }//end if // Do the normal stuf. $objectEntity->addObjectValue($valueObject); @@ -318,5 +334,8 @@ public function hydrate(ObjectEntity $objectEntity, array $hydrate = []): Object $this->entityManager->flush(); return $objectEntity; + }//end hydrate() + + }//end class diff --git a/src/Subscriber/CacheDatabaseSubscriber.php b/src/Subscriber/CacheDatabaseSubscriber.php index fea69bd2..df1e2528 100644 --- a/src/Subscriber/CacheDatabaseSubscriber.php +++ b/src/Subscriber/CacheDatabaseSubscriber.php @@ -1,7 +1,6 @@ cacheService = $cacheService; + $this->cacheService = $cacheService; $this->entityManager = $entityManager; - $this->session = $session; - } + $this->session = $session; + + }//end __construct() + // this method can only return the event names; you cannot define a // custom method name to execute when each event triggers @@ -46,12 +51,16 @@ public function getSubscribedEvents(): array Events::preRemove, Events::postUpdate, ]; - } + + }//end getSubscribedEvents() + public function postUpdate(LifecycleEventArgs $args): void { $this->postPersist($args); - } + + }//end postUpdate() + /** * Updates the chache whenever an object is put into the database. @@ -69,17 +78,21 @@ public function postPersist(LifecycleEventArgs $args): void return; } + if ($object instanceof Entity) { $this->cacheService->cacheShema($object); return; } + if ($object instanceof Endpoint) { $this->cacheService->cacheEndpoint($object); return; } - } + + }//end postPersist() + /** * Remove objects from the cache afther they are removed from the database. @@ -98,15 +111,20 @@ public function preRemove(LifecycleEventArgs $args): void return; } + if ($object instanceof Entity) { $this->cacheService->removeSchema($object); return; } + if ($object instanceof Endpoint) { $this->cacheService->removeEndpoint($object); return; } - } -} + + }//end preRemove() + + +}//end class diff --git a/src/Subscriber/DoctrineToGatewayEventSubscriber.php b/src/Subscriber/DoctrineToGatewayEventSubscriber.php index 4a929112..d8b2d6ad 100644 --- a/src/Subscriber/DoctrineToGatewayEventSubscriber.php +++ b/src/Subscriber/DoctrineToGatewayEventSubscriber.php @@ -1,7 +1,6 @@ cacheService = $cacheService; - $this->entityManager = $entityManager; - $this->session = $session; + $this->cacheService = $cacheService; + $this->entityManager = $entityManager; + $this->session = $session; $this->eventDispatcher = $eventDispatcher; - $this->logger = new Logger('object'); - } + $this->logger = new Logger('object'); + + }//end __construct() + // this method can only return the event names; you cannot define a // custom method name to execute when each event triggers @@ -75,7 +82,9 @@ public function getSubscribedEvents(): array Events::preFlush, Events::postFlush, ]; - } + + }//end getSubscribedEvents() + /** * Deleting object from database. @@ -97,15 +106,17 @@ public function preRemove(LifecycleEventArgs $args): void $this->logger->info( 'Deleting object from database', [ - 'object' => $object->getId(), - 'entity' => $object->getEntity()->getId(), + 'object' => $object->getId(), + 'entity' => $object->getEntity()->getId(), ] ); // Throw the event $event = new ActionEvent('commongateway.object.pre.delete', ['object' => $object]); $this->eventDispatcher->dispatch($event, 'commongateway.object.pre.delete'); - } + + }//end preRemove() + /** * Creating object in database. @@ -127,15 +138,17 @@ public function prePersist(LifecycleEventArgs $args): void $this->logger->info( 'Creating object in database', [ - 'object' => $object->getId(), - 'entity' => $object->getEntity()->getId(), + 'object' => $object->getId(), + 'entity' => $object->getEntity()->getId(), ] ); // Throw the event $event = new ActionEvent('commongateway.object.pre.create', ['object' => $object]); $this->eventDispatcher->dispatch($event, 'commongateway.object.pre.create'); - } + + }//end prePersist() + /** * Updating object to database. @@ -157,15 +170,17 @@ public function preUpdate(LifecycleEventArgs $args): void $this->logger->info( 'Updating object to database', [ - 'object' => $object->getId(), - 'entity' => $object->getEntity()->getId(), + 'object' => $object->getId(), + 'entity' => $object->getEntity()->getId(), ] ); // Throw the event $event = new ActionEvent('commongateway.object.pre.update', ['object' => $object]); $this->eventDispatcher->dispatch($event, 'commongateway.object.pre.update'); - } + + }//end preUpdate() + /** * Deleted object from database. @@ -186,14 +201,15 @@ public function postRemove(LifecycleEventArgs $args): void // Write the log $this->logger->info( 'Deleted object from database', - [ - ] + [] ); // Throw the event $event = new ActionEvent('commongateway.object.post.delete', []); $this->eventDispatcher->dispatch($event, 'commongateway.object.post.delete'); - } + + }//end postRemove() + /** * Created object in database. @@ -215,15 +231,17 @@ public function postPersist(LifecycleEventArgs $args): void $this->logger->info( 'Created object in database', [ - 'object' => $object->getId(), - 'entity' => $object->getEntity()->getId(), + 'object' => $object->getId(), + 'entity' => $object->getEntity()->getId(), ] ); // Throw the event $event = new ActionEvent('commongateway.object.post.create', ['object' => $object]); $this->eventDispatcher->dispatch($event, 'commongateway.object.post.create'); - } + + }//end postPersist() + /** * Updated object in database. @@ -245,15 +263,17 @@ public function postUpdate(LifecycleEventArgs $args): void $this->logger->info( 'Updated object in database', [ - 'object' => $object->getId(), - 'entity' => $object->getEntity()->getId(), + 'object' => $object->getId(), + 'entity' => $object->getEntity()->getId(), ] ); // Throw the event $event = new ActionEvent('commongateway.object.post.update', ['object' => $object]); $this->eventDispatcher->dispatch($event, 'commongateway.object.post.update'); - } + + }//end postUpdate() + /** * Read object from database. @@ -275,14 +295,16 @@ public function postLoad(LifecycleEventArgs $args): void $this->logger->info( 'Read object from database', [ - 'object' => $object->getId(), + 'object' => $object->getId(), ] ); // Throw the event $event = new ActionEvent('commongateway.object.post.read', ['object' => $object]); $this->eventDispatcher->dispatch($event, 'commongateway.object.post.read'); - } + + }//end postLoad() + /** * Flushing entity manager. @@ -296,14 +318,15 @@ public function preFlush(PreFlushEventArgs $args): void // Write the log $this->logger->info( 'Flushing entity manager', - [ - ] + [] ); // Throw the event $event = new ActionEvent('commongateway.object.pre.flush', []); $this->eventDispatcher->dispatch($event, 'commongateway.object.pre.flush'); - } + + }//end preFlush() + /** * Flushed entity manager. @@ -317,12 +340,14 @@ public function postFlush(PostFlushEventArgs $args): void // Write the log $this->logger->info( 'Flushed entity manager', - [ - ] + [] ); // Throw the event $event = new ActionEvent('commongateway.object.post.flush', []); $this->eventDispatcher->dispatch($event, 'commongateway.object.post.flush'); - } -} + + }//end postFlush() + + +}//end class diff --git a/src/Subscriber/ObjectReferenceSubscriber.php b/src/Subscriber/ObjectReferenceSubscriber.php index 9a999475..a9c2227e 100644 --- a/src/Subscriber/ObjectReferenceSubscriber.php +++ b/src/Subscriber/ObjectReferenceSubscriber.php @@ -1,7 +1,6 @@ entityManager = $entityManager; - $this->eavService = $eavService; - } + $this->eavService = $eavService; + + }//end __construct() + // this method can only return the event names; you cannot define a // custom method name to execute when each event triggers @@ -40,7 +44,9 @@ public function getSubscribedEvents(): array Events::postPersist, Events::postUpdate, ]; - } + + }//end getSubscribedEvents() + /** * Checks whether we should check attributes and entities for connections. @@ -54,13 +60,12 @@ public function postPersist(LifecycleEventArgs $args): void $object = $args->getObject(); // Let see if we need to hook an attribute to an entity - if ( - $object instanceof Attribute // It's an attribute + if ($object instanceof Attribute // It's an attribute && ($object->getSchema() || $object->getReference()) // It has a reference && !$object->getObject() // It isn't currently connected to a schema ) { - $reference = $object->getReference() ?? $object->getSchema(); - $entity = $this->entityManager->getRepository('App:Entity')->findOneBy(['reference' => $reference]); + $reference = ($object->getReference() ?? $object->getSchema()); + $entity = $this->entityManager->getRepository('App:Entity')->findOneBy(['reference' => $reference]); if ($entity !== null) { $object->setObject($entity); if ($object->getInversedByPropertyName() && !$object->getInversedBy()) { @@ -73,8 +78,8 @@ public function postPersist(LifecycleEventArgs $args): void return; } - if ( - $object instanceof Entity // Is it an entity + + if ($object instanceof Entity // Is it an entity && $object->getReference() // Does it have a reference ) { $attributes = $this->entityManager->getRepository('App:Attribute')->findBy(['schema' => $object->getReference()]); @@ -82,6 +87,7 @@ public function postPersist(LifecycleEventArgs $args): void if ($attribute instanceof Attribute === false) { continue; } + $attribute->setObject($object); if ($attribute->getInversedByPropertyName() && !$attribute->getInversedBy()) { $attribute = $object->getAttributeByName($attribute->getInversedByPropertyName()); @@ -93,10 +99,15 @@ public function postPersist(LifecycleEventArgs $args): void return; } - } + + }//end postPersist() + public function postUpdate(LifecycleEventArgs $args): void { $this->postPersist($args); - } -} + + }//end postUpdate() + + +}//end class diff --git a/src/Subscriber/ObjectUriSubscriber.php b/src/Subscriber/ObjectUriSubscriber.php index 7ce3b7d3..0ffcf9f8 100644 --- a/src/Subscriber/ObjectUriSubscriber.php +++ b/src/Subscriber/ObjectUriSubscriber.php @@ -1,7 +1,6 @@ parameterBag = $parameterBag; - $this->session = $session; - } + $this->session = $session; + + }//end __construct() + // this method can only return the event names; you cannot define a // custom method name to execute when each event triggers @@ -33,12 +37,16 @@ public function getSubscribedEvents(): array Events::postPersist, Events::postUpdate, ]; - } + + }//end getSubscribedEvents() + public function postUpdate(LifecycleEventArgs $args): void { $this->postPersist($args); - } + + }//end postUpdate() + /** * Updates the chache whenever an object is put into the database. @@ -58,5 +66,8 @@ public function postPersist(LifecycleEventArgs $args): void return; } - } -} + + }//end postPersist() + + +}//end class From 21c1b7d28ce1a8effa21f6fffdcab9e8ec0d728f Mon Sep 17 00:00:00 2001 From: Ruben van der Linde Date: Fri, 24 Mar 2023 09:33:57 +0100 Subject: [PATCH 4/7] Add remark linting --- .github/workflows/remarklint.yml | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 .github/workflows/remarklint.yml diff --git a/.github/workflows/remarklint.yml b/.github/workflows/remarklint.yml new file mode 100644 index 00000000..d69d1ec1 --- /dev/null +++ b/.github/workflows/remarklint.yml @@ -0,0 +1,28 @@ +name: remark-lint + +on: [pull_request,push] + +env: # environment variables (available in any part of the action) + NODE_VERSION: 16 + +jobs: + remark-lint: + name: runner / remark-lint + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: install remark presets + run: npm install remark-cli remark-preset-lint-consistent remark-preset-lint-recommended remark-lint-list-item-indent + shell: bash + - name: run remark + run: npx remark . --output --use remark-preset-lint-consistent --use remark-preset-lint-recommended --use remark-lint-list-item-indent + - name: Git commit + run: | + git config user.name "GitHub Actions" + git config user.email "" + git add . + git reset package.json + git reset package-lock.json + git reset node_modules + git commit -m "Update src from remark-lint" || echo "No changes to commit" + git push \ No newline at end of file From b503eb8aea98c03a994affd92324362b0855a8ff Mon Sep 17 00:00:00 2001 From: GitHub Actions <> Date: Fri, 24 Mar 2023 08:34:26 +0000 Subject: [PATCH 5/7] Update src from remark-lint --- LICENSE.md | 582 +++++++++--------- README.md | 8 +- .../CoreBundle/Service/RequestService.md | 147 ++--- docs/classes/README.md | 16 +- docs/classes/Service/AuthenticationService.md | 255 +++----- docs/classes/Service/CacheService.md | 211 ++----- docs/classes/Service/CallService.md | 119 ++-- docs/classes/Service/ComposerService.md | 103 +--- docs/classes/Service/EavService.md | 57 +- docs/classes/Service/FileService.md | 27 +- docs/classes/Service/InstallationService.md | 83 +-- docs/classes/Service/RequestService.md | 177 ++---- 12 files changed, 637 insertions(+), 1148 deletions(-) diff --git a/LICENSE.md b/LICENSE.md index e421bd46..f495b9f8 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -6,302 +6,298 @@ Licensed under the EUPL **Table of Contents** -* [EUPL text in English](#eupl-text-in-english) -* [EUPL text in Dutch (governing law)](#eupl-text-in-dutch) +* [EUPL text in English](#eupl-text-in-english) +* [EUPL text in Dutch (governing law)](#eupl-text-in-dutch) ## EUPL text in English -``` -EUROPEAN UNION PUBLIC LICENCE v. 1.2 -EUPL © the European Union 2007, 2016 - -This European Union Public Licence (the ‘EUPL’) applies to the Work (as defined below) which is provided under the -terms of this Licence. Any use of the Work, other than as authorised under this Licence is prohibited (to the extent such -use is covered by a right of the copyright holder of the Work). -The Work is provided under the terms of this Licence when the Licensor (as defined below) has placed the following -notice immediately following the copyright notice for the Work: - Licensed under the EUPL -or has expressed by any other means his willingness to license under the EUPL. - -1.Definitions -In this Licence, the following terms have the following meaning: -— ‘The Licence’:this Licence. -— ‘The Original Work’:the work or software distributed or communicated by the Licensor under this Licence, available -as Source Code and also as Executable Code as the case may be. -— ‘Derivative Works’:the works or software that could be created by the Licensee, based upon the Original Work or -modifications thereof. This Licence does not define the extent of modification or dependence on the Original Work -required in order to classify a work as a Derivative Work; this extent is determined by copyright law applicable in -the country mentioned in Article 15. -— ‘The Work’:the Original Work or its Derivative Works. -— ‘The Source Code’:the human-readable form of the Work which is the most convenient for people to study and -modify. -— ‘The Executable Code’:any code which has generally been compiled and which is meant to be interpreted by -a computer as a program. -— ‘The Licensor’:the natural or legal person that distributes or communicates the Work under the Licence. -— ‘Contributor(s)’:any natural or legal person who modifies the Work under the Licence, or otherwise contributes to -the creation of a Derivative Work. -— ‘The Licensee’ or ‘You’:any natural or legal person who makes any usage of the Work under the terms of the -Licence. -— ‘Distribution’ or ‘Communication’:any act of selling, giving, lending, renting, distributing, communicating, -transmitting, or otherwise making available, online or offline, copies of the Work or providing access to its essential -functionalities at the disposal of any other natural or legal person. - -2.Scope of the rights granted by the Licence -The Licensor hereby grants You a worldwide, royalty-free, non-exclusive, sublicensable licence to do the following, for -the duration of copyright vested in the Original Work: -— use the Work in any circumstance and for all usage, -— reproduce the Work, -— modify the Work, and make Derivative Works based upon the Work, -— communicate to the public, including the right to make available or display the Work or copies thereof to the public -and perform publicly, as the case may be, the Work, -— distribute the Work or copies thereof, -— lend and rent the Work or copies thereof, -— sublicense rights in the Work or copies thereof. -Those rights can be exercised on any media, supports and formats, whether now known or later invented, as far as the -applicable law permits so. -In the countries where moral rights apply, the Licensor waives his right to exercise his moral right to the extent allowed -by law in order to make effective the licence of the economic rights here above listed. -The Licensor grants to the Licensee royalty-free, non-exclusive usage rights to any patents held by the Licensor, to the -extent necessary to make use of the rights granted on the Work under this Licence. - -3.Communication of the Source Code -The Licensor may provide the Work either in its Source Code form, or as Executable Code. If the Work is provided as -Executable Code, the Licensor provides in addition a machine-readable copy of the Source Code of the Work along with -each copy of the Work that the Licensor distributes or indicates, in a notice following the copyright notice attached to -the Work, a repository where the Source Code is easily and freely accessible for as long as the Licensor continues to -distribute or communicate the Work. - -4.Limitations on copyright -Nothing in this Licence is intended to deprive the Licensee of the benefits from any exception or limitation to the -exclusive rights of the rights owners in the Work, of the exhaustion of those rights or of other applicable limitations -thereto. - -5.Obligations of the Licensee -The grant of the rights mentioned above is subject to some restrictions and obligations imposed on the Licensee. Those -obligations are the following: - -Attribution right: The Licensee shall keep intact all copyright, patent or trademarks notices and all notices that refer to -the Licence and to the disclaimer of warranties. The Licensee must include a copy of such notices and a copy of the -Licence with every copy of the Work he/she distributes or communicates. The Licensee must cause any Derivative Work -to carry prominent notices stating that the Work has been modified and the date of modification. - -Copyleft clause: If the Licensee distributes or communicates copies of the Original Works or Derivative Works, this -Distribution or Communication will be done under the terms of this Licence or of a later version of this Licence unless -the Original Work is expressly distributed only under this version of the Licence — for example by communicating -‘EUPL v. 1.2 only’. The Licensee (becoming Licensor) cannot offer or impose any additional terms or conditions on the -Work or Derivative Work that alter or restrict the terms of the Licence. - -Compatibility clause: If the Licensee Distributes or Communicates Derivative Works or copies thereof based upon both -the Work and another work licensed under a Compatible Licence, this Distribution or Communication can be done -under the terms of this Compatible Licence. For the sake of this clause, ‘Compatible Licence’ refers to the licences listed -in the appendix attached to this Licence. Should the Licensee's obligations under the Compatible Licence conflict with -his/her obligations under this Licence, the obligations of the Compatible Licence shall prevail. - -Provision of Source Code: When distributing or communicating copies of the Work, the Licensee will provide -a machine-readable copy of the Source Code or indicate a repository where this Source will be easily and freely available -for as long as the Licensee continues to distribute or communicate the Work. -Legal Protection: This Licence does not grant permission to use the trade names, trademarks, service marks, or names -of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and -reproducing the content of the copyright notice. - -6.Chain of Authorship -The original Licensor warrants that the copyright in the Original Work granted hereunder is owned by him/her or -licensed to him/her and that he/she has the power and authority to grant the Licence. -Each Contributor warrants that the copyright in the modifications he/she brings to the Work are owned by him/her or -licensed to him/her and that he/she has the power and authority to grant the Licence. -Each time You accept the Licence, the original Licensor and subsequent Contributors grant You a licence to their contributions -to the Work, under the terms of this Licence. - -7.Disclaimer of Warranty -The Work is a work in progress, which is continuously improved by numerous Contributors. It is not a finished work -and may therefore contain defects or ‘bugs’ inherent to this type of development. -For the above reason, the Work is provided under the Licence on an ‘as is’ basis and without warranties of any kind -concerning the Work, including without limitation merchantability, fitness for a particular purpose, absence of defects or -errors, accuracy, non-infringement of intellectual property rights other than copyright as stated in Article 6 of this -Licence. -This disclaimer of warranty is an essential part of the Licence and a condition for the grant of any rights to the Work. - -8.Disclaimer of Liability -Except in the cases of wilful misconduct or damages directly caused to natural persons, the Licensor will in no event be -liable for any direct or indirect, material or moral, damages of any kind, arising out of the Licence or of the use of the -Work, including without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, loss -of data or any commercial damage, even if the Licensor has been advised of the possibility of such damage. However, -the Licensor will be liable under statutory product liability laws as far such laws apply to the Work. - -9.Additional agreements -While distributing the Work, You may choose to conclude an additional agreement, defining obligations or services -consistent with this Licence. However, if accepting obligations, You may act only on your own behalf and on your sole -responsibility, not on behalf of the original Licensor or any other Contributor, and only if You agree to indemnify, -defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against such Contributor by -the fact You have accepted any warranty or additional liability. - -10.Acceptance of the Licence -The provisions of this Licence can be accepted by clicking on an icon ‘I agree’ placed under the bottom of a window -displaying the text of this Licence or by affirming consent in any other similar way, in accordance with the rules of -applicable law. Clicking on that icon indicates your clear and irrevocable acceptance of this Licence and all of its terms -and conditions. -Similarly, you irrevocably accept this Licence and all of its terms and conditions by exercising any rights granted to You -by Article 2 of this Licence, such as the use of the Work, the creation by You of a Derivative Work or the Distribution -or Communication by You of the Work or copies thereof. - -11.Information to the public -In case of any Distribution or Communication of the Work by means of electronic communication by You (for example, -by offering to download the Work from a remote location) the distribution channel or media (for example, a website) -must at least provide to the public the information requested by the applicable law regarding the Licensor, the Licence -and the way it may be accessible, concluded, stored and reproduced by the Licensee. - -12.Termination of the Licence -The Licence and the rights granted hereunder will terminate automatically upon any breach by the Licensee of the terms -of the Licence. -Such a termination will not terminate the licences of any person who has received the Work from the Licensee under -the Licence, provided such persons remain in full compliance with the Licence. - -13.Miscellaneous -Without prejudice of Article 9 above, the Licence represents the complete agreement between the Parties as to the -Work. -If any provision of the Licence is invalid or unenforceable under applicable law, this will not affect the validity or -enforceability of the Licence as a whole. Such provision will be construed or reformed so as necessary to make it valid -and enforceable. -The European Commission may publish other linguistic versions or new versions of this Licence or updated versions of -the Appendix, so far this is required and reasonable, without reducing the scope of the rights granted by the Licence. -New versions of the Licence will be published with a unique version number. -All linguistic versions of this Licence, approved by the European Commission, have identical value. Parties can take -advantage of the linguistic version of their choice. - -14.Jurisdiction -Without prejudice to specific agreement between parties, -— any litigation resulting from the interpretation of this License, arising between the European Union institutions, -bodies, offices or agencies, as a Licensor, and any Licensee, will be subject to the jurisdiction of the Court of Justice -of the European Union, as laid down in article 272 of the Treaty on the Functioning of the European Union, -— any litigation arising between other parties and resulting from the interpretation of this License, will be subject to -the exclusive jurisdiction of the competent court where the Licensor resides or conducts its primary business. - -15.Applicable Law -Without prejudice to specific agreement between parties, -— this Licence shall be governed by the law of the European Union Member State where the Licensor has his seat, -resides or has his registered office, -— this licence shall be governed by Belgian law if the Licensor has no seat, residence or registered office inside -a European Union Member State. - - - Appendix - -‘Compatible Licences’ according to Article 5 EUPL are: -— GNU General Public License (GPL) v. 2, v. 3 -— GNU Affero General Public License (AGPL) v. 3 -— Open Software License (OSL) v. 2.1, v. 3.0 -— Eclipse Public License (EPL) v. 1.0 -— CeCILL v. 2.0, v. 2.1 -— Mozilla Public Licence (MPL) v. 2 -— GNU Lesser General Public Licence (LGPL) v. 2.1, v. 3 -— Creative Commons Attribution-ShareAlike v. 3.0 Unported (CC BY-SA 3.0) for works other than software -— European Union Public Licence (EUPL) v. 1.1, v. 1.2 -— Québec Free and Open-Source Licence — Reciprocity (LiLiQ-R) or Strong Reciprocity (LiLiQ-R+). - -The European Commission may update this Appendix to later versions of the above licences without producing -a new version of the EUPL, as long as they provide the rights granted in Article 2 of this Licence and protect the -covered Source Code from exclusive appropriation. -All other changes or additions to this Appendix require the production of a new EUPL version. -``` + EUROPEAN UNION PUBLIC LICENCE v. 1.2 + EUPL © the European Union 2007, 2016 + + This European Union Public Licence (the ‘EUPL’) applies to the Work (as defined below) which is provided under the + terms of this Licence. Any use of the Work, other than as authorised under this Licence is prohibited (to the extent such + use is covered by a right of the copyright holder of the Work). + The Work is provided under the terms of this Licence when the Licensor (as defined below) has placed the following + notice immediately following the copyright notice for the Work: + Licensed under the EUPL + or has expressed by any other means his willingness to license under the EUPL. + + 1.Definitions + In this Licence, the following terms have the following meaning: + — ‘The Licence’:this Licence. + — ‘The Original Work’:the work or software distributed or communicated by the Licensor under this Licence, available + as Source Code and also as Executable Code as the case may be. + — ‘Derivative Works’:the works or software that could be created by the Licensee, based upon the Original Work or + modifications thereof. This Licence does not define the extent of modification or dependence on the Original Work + required in order to classify a work as a Derivative Work; this extent is determined by copyright law applicable in + the country mentioned in Article 15. + — ‘The Work’:the Original Work or its Derivative Works. + — ‘The Source Code’:the human-readable form of the Work which is the most convenient for people to study and + modify. + — ‘The Executable Code’:any code which has generally been compiled and which is meant to be interpreted by + a computer as a program. + — ‘The Licensor’:the natural or legal person that distributes or communicates the Work under the Licence. + — ‘Contributor(s)’:any natural or legal person who modifies the Work under the Licence, or otherwise contributes to + the creation of a Derivative Work. + — ‘The Licensee’ or ‘You’:any natural or legal person who makes any usage of the Work under the terms of the + Licence. + — ‘Distribution’ or ‘Communication’:any act of selling, giving, lending, renting, distributing, communicating, + transmitting, or otherwise making available, online or offline, copies of the Work or providing access to its essential + functionalities at the disposal of any other natural or legal person. + + 2.Scope of the rights granted by the Licence + The Licensor hereby grants You a worldwide, royalty-free, non-exclusive, sublicensable licence to do the following, for + the duration of copyright vested in the Original Work: + — use the Work in any circumstance and for all usage, + — reproduce the Work, + — modify the Work, and make Derivative Works based upon the Work, + — communicate to the public, including the right to make available or display the Work or copies thereof to the public + and perform publicly, as the case may be, the Work, + — distribute the Work or copies thereof, + — lend and rent the Work or copies thereof, + — sublicense rights in the Work or copies thereof. + Those rights can be exercised on any media, supports and formats, whether now known or later invented, as far as the + applicable law permits so. + In the countries where moral rights apply, the Licensor waives his right to exercise his moral right to the extent allowed + by law in order to make effective the licence of the economic rights here above listed. + The Licensor grants to the Licensee royalty-free, non-exclusive usage rights to any patents held by the Licensor, to the + extent necessary to make use of the rights granted on the Work under this Licence. + + 3.Communication of the Source Code + The Licensor may provide the Work either in its Source Code form, or as Executable Code. If the Work is provided as + Executable Code, the Licensor provides in addition a machine-readable copy of the Source Code of the Work along with + each copy of the Work that the Licensor distributes or indicates, in a notice following the copyright notice attached to + the Work, a repository where the Source Code is easily and freely accessible for as long as the Licensor continues to + distribute or communicate the Work. + + 4.Limitations on copyright + Nothing in this Licence is intended to deprive the Licensee of the benefits from any exception or limitation to the + exclusive rights of the rights owners in the Work, of the exhaustion of those rights or of other applicable limitations + thereto. + + 5.Obligations of the Licensee + The grant of the rights mentioned above is subject to some restrictions and obligations imposed on the Licensee. Those + obligations are the following: + + Attribution right: The Licensee shall keep intact all copyright, patent or trademarks notices and all notices that refer to + the Licence and to the disclaimer of warranties. The Licensee must include a copy of such notices and a copy of the + Licence with every copy of the Work he/she distributes or communicates. The Licensee must cause any Derivative Work + to carry prominent notices stating that the Work has been modified and the date of modification. + + Copyleft clause: If the Licensee distributes or communicates copies of the Original Works or Derivative Works, this + Distribution or Communication will be done under the terms of this Licence or of a later version of this Licence unless + the Original Work is expressly distributed only under this version of the Licence — for example by communicating + ‘EUPL v. 1.2 only’. The Licensee (becoming Licensor) cannot offer or impose any additional terms or conditions on the + Work or Derivative Work that alter or restrict the terms of the Licence. + + Compatibility clause: If the Licensee Distributes or Communicates Derivative Works or copies thereof based upon both + the Work and another work licensed under a Compatible Licence, this Distribution or Communication can be done + under the terms of this Compatible Licence. For the sake of this clause, ‘Compatible Licence’ refers to the licences listed + in the appendix attached to this Licence. Should the Licensee's obligations under the Compatible Licence conflict with + his/her obligations under this Licence, the obligations of the Compatible Licence shall prevail. + + Provision of Source Code: When distributing or communicating copies of the Work, the Licensee will provide + a machine-readable copy of the Source Code or indicate a repository where this Source will be easily and freely available + for as long as the Licensee continues to distribute or communicate the Work. + Legal Protection: This Licence does not grant permission to use the trade names, trademarks, service marks, or names + of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and + reproducing the content of the copyright notice. + + 6.Chain of Authorship + The original Licensor warrants that the copyright in the Original Work granted hereunder is owned by him/her or + licensed to him/her and that he/she has the power and authority to grant the Licence. + Each Contributor warrants that the copyright in the modifications he/she brings to the Work are owned by him/her or + licensed to him/her and that he/she has the power and authority to grant the Licence. + Each time You accept the Licence, the original Licensor and subsequent Contributors grant You a licence to their contributions + to the Work, under the terms of this Licence. + + 7.Disclaimer of Warranty + The Work is a work in progress, which is continuously improved by numerous Contributors. It is not a finished work + and may therefore contain defects or ‘bugs’ inherent to this type of development. + For the above reason, the Work is provided under the Licence on an ‘as is’ basis and without warranties of any kind + concerning the Work, including without limitation merchantability, fitness for a particular purpose, absence of defects or + errors, accuracy, non-infringement of intellectual property rights other than copyright as stated in Article 6 of this + Licence. + This disclaimer of warranty is an essential part of the Licence and a condition for the grant of any rights to the Work. + + 8.Disclaimer of Liability + Except in the cases of wilful misconduct or damages directly caused to natural persons, the Licensor will in no event be + liable for any direct or indirect, material or moral, damages of any kind, arising out of the Licence or of the use of the + Work, including without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, loss + of data or any commercial damage, even if the Licensor has been advised of the possibility of such damage. However, + the Licensor will be liable under statutory product liability laws as far such laws apply to the Work. + + 9.Additional agreements + While distributing the Work, You may choose to conclude an additional agreement, defining obligations or services + consistent with this Licence. However, if accepting obligations, You may act only on your own behalf and on your sole + responsibility, not on behalf of the original Licensor or any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against such Contributor by + the fact You have accepted any warranty or additional liability. + + 10.Acceptance of the Licence + The provisions of this Licence can be accepted by clicking on an icon ‘I agree’ placed under the bottom of a window + displaying the text of this Licence or by affirming consent in any other similar way, in accordance with the rules of + applicable law. Clicking on that icon indicates your clear and irrevocable acceptance of this Licence and all of its terms + and conditions. + Similarly, you irrevocably accept this Licence and all of its terms and conditions by exercising any rights granted to You + by Article 2 of this Licence, such as the use of the Work, the creation by You of a Derivative Work or the Distribution + or Communication by You of the Work or copies thereof. + + 11.Information to the public + In case of any Distribution or Communication of the Work by means of electronic communication by You (for example, + by offering to download the Work from a remote location) the distribution channel or media (for example, a website) + must at least provide to the public the information requested by the applicable law regarding the Licensor, the Licence + and the way it may be accessible, concluded, stored and reproduced by the Licensee. + + 12.Termination of the Licence + The Licence and the rights granted hereunder will terminate automatically upon any breach by the Licensee of the terms + of the Licence. + Such a termination will not terminate the licences of any person who has received the Work from the Licensee under + the Licence, provided such persons remain in full compliance with the Licence. + + 13.Miscellaneous + Without prejudice of Article 9 above, the Licence represents the complete agreement between the Parties as to the + Work. + If any provision of the Licence is invalid or unenforceable under applicable law, this will not affect the validity or + enforceability of the Licence as a whole. Such provision will be construed or reformed so as necessary to make it valid + and enforceable. + The European Commission may publish other linguistic versions or new versions of this Licence or updated versions of + the Appendix, so far this is required and reasonable, without reducing the scope of the rights granted by the Licence. + New versions of the Licence will be published with a unique version number. + All linguistic versions of this Licence, approved by the European Commission, have identical value. Parties can take + advantage of the linguistic version of their choice. + + 14.Jurisdiction + Without prejudice to specific agreement between parties, + — any litigation resulting from the interpretation of this License, arising between the European Union institutions, + bodies, offices or agencies, as a Licensor, and any Licensee, will be subject to the jurisdiction of the Court of Justice + of the European Union, as laid down in article 272 of the Treaty on the Functioning of the European Union, + — any litigation arising between other parties and resulting from the interpretation of this License, will be subject to + the exclusive jurisdiction of the competent court where the Licensor resides or conducts its primary business. + + 15.Applicable Law + Without prejudice to specific agreement between parties, + — this Licence shall be governed by the law of the European Union Member State where the Licensor has his seat, + resides or has his registered office, + — this licence shall be governed by Belgian law if the Licensor has no seat, residence or registered office inside + a European Union Member State. + + + Appendix + + ‘Compatible Licences’ according to Article 5 EUPL are: + — GNU General Public License (GPL) v. 2, v. 3 + — GNU Affero General Public License (AGPL) v. 3 + — Open Software License (OSL) v. 2.1, v. 3.0 + — Eclipse Public License (EPL) v. 1.0 + — CeCILL v. 2.0, v. 2.1 + — Mozilla Public Licence (MPL) v. 2 + — GNU Lesser General Public Licence (LGPL) v. 2.1, v. 3 + — Creative Commons Attribution-ShareAlike v. 3.0 Unported (CC BY-SA 3.0) for works other than software + — European Union Public Licence (EUPL) v. 1.1, v. 1.2 + — Québec Free and Open-Source Licence — Reciprocity (LiLiQ-R) or Strong Reciprocity (LiLiQ-R+). + + The European Commission may update this Appendix to later versions of the above licences without producing + a new version of the EUPL, as long as they provide the rights granted in Article 2 of this Licence and protect the + covered Source Code from exclusive appropriation. + All other changes or additions to this Appendix require the production of a new EUPL version. ## EUPL text in Dutch -``` -OPENBARE LICENTIE VAN DE EUROPESE UNIE v. 1.2. -EUPL © Europese Unie 2007, 2016 -Deze openbare licentie van de Europese Unie („EUPL”) is van toepassing op het werk (zoals hieronder gedefinieerd) dat onder de voorwaarden van deze licentie wordt verstrekt. Elk gebruik van het werk dat niet door deze licentie is toegestaan, is verboden (voor zover dit gebruik valt onder een recht van de houder van het auteursrecht op het werk). Het werk wordt verstrekt onder de voorwaarden van deze licentie wanneer de licentiegever (zoals hieronder gedefinieerd), direct volgend op de kennisgeving inzake het auteursrecht op het werk, de volgende kennisgeving opneemt: - In licentie gegeven krachtens de EUPL -of op een andere wijze zijn bereidheid te kennen heeft gegeven krachtens de EUPL in licentie te geven. - -1.Definities -In deze licentie wordt verstaan onder: -— „de licentie”:de onderhavige licentie; -— „het oorspronkelijke werk”:het werk dat of de software die door de licentiegever krachtens deze licentie wordt verspreid of medegedeeld, en dat/die beschikbaar is als broncode en, in voorkomend geval, ook als uitvoerbare code; -— „bewerkingen”:de werken of software die de licentiehouder kan creëren op grond van het oorspronkelijke werk of wijzigingen ervan. In deze licentie wordt niet gedefinieerd welke mate van wijziging of afhankelijkheid van het oorspronkelijke werk vereist is om een werk als een bewerking te kunnen aanmerken; dat wordt bepaald conform het auteursrecht dat van toepassing is in de in artikel 15 bedoelde staat; -— „het werk”:het oorspronkelijke werk of de bewerkingen ervan; -— „de broncode”:de voor mensen leesbare vorm van het werk, die het gemakkelijkste door mensen kan worden bestudeerd en gewijzigd; -— „de uitvoerbare code”:elke code die over het algemeen is gecompileerd en is bedoeld om door een computer als een programma te worden uitgevoerd; -— „de licentiegever”:de natuurlijke of rechtspersoon die het werk krachtens de licentie verspreidt of mededeelt; -— „bewerker(s)”:elke natuurlijke of rechtspersoon die het werk krachtens de licentie wijzigt of op een andere wijze bijdraagt tot de totstandkoming van een bewerking; -— „de licentiehouder” of „u”:elke natuurlijke of rechtspersoon die het werk onder de voorwaarden van de licentie gebruikt; — „verspreiding” of „mededeling”:het verkopen, geven, uitlenen, verhuren, verspreiden, mededelen, doorgeven, of op een andere wijze online of offline beschikbaar stellen van kopieën van het werk of het verlenen van toegang tot de essentiële functies ervan ten behoeve van andere natuurlijke of rechtspersonen. - -2.Draagwijdte van de uit hoofde van de licentie verleende rechten -De licentiegever verleent u hierbij een wereldwijde, royaltyvrije, niet-exclusieve, voor een sublicentie in aanmerking komende licentie, om voor de duur van het aan het oorspronkelijke werk verbonden auteursrecht, het volgende te doen: -— het werk in alle omstandigheden en voor ongeacht welk doel te gebruiken; -— het werk te verveelvoudigen; -— het werk te wijzigen en op grond van het werk bewerkingen te ontwikkelen; -— het werk aan het publiek mede te delen, waaronder het recht om het werk of kopieën ervan aan het publiek ter beschikking te stellen of te vertonen, en het werk, in voorkomend geval, in het openbaar uit te voeren; -— het werk of kopieën ervan te verspreiden; -— het werk of kopieën ervan uit te lenen en te verhuren; -— de rechten op het werk of op kopieën ervan in sublicentie te geven. -Deze rechten kunnen worden uitgeoefend met gebruikmaking van alle thans bekende of nog uit te vinden media, dragers en formaten, voor zover het toepasselijke recht dit toestaat. In de landen waar immateriële rechten van toepassing zijn, doet de licentiegever afstand van zijn recht op uitoefening van zijn immateriële rechten in de mate die door het toepasselijke recht wordt toegestaan teneinde een doeltreffende uitoefening van de bovenvermelde in licentie gegeven economische rechten mogelijk te maken. De licentiegever verleent de licentiehouder een royaltyvrij, niet-exclusief gebruiksrecht op alle octrooien van de licentiegever, voor zover dit noodzakelijk is om de uit hoofde van deze licentie verleende rechten op het werk te gebruiken. - -3.Mededeling van de broncode -De licentiegever kan het werk verstrekken in zijn broncode of als uitvoerbare code. Indien het werk als uitvoerbare code wordt verstrekt, verstrekt de licentiegever bij elke door hem verspreide kopie van het werk tevens een machinaal leesbare kopie van de broncode van het werk of geeft hij in een mededeling, volgende op de bij het werk gevoegde auteursrechtelijke kennisgeving, de plaats aan waar de broncode gemakkelijk en vrij toegankelijk is, zolang de licentiegever het werk blijft verspreiden of mededelen. - -4.Beperkingen van het auteursrecht -Geen enkele bepaling in deze licentie heeft ten doel de licentiehouder het recht te ontnemen een beroep te doen op een uitzondering op of een beperking van de exclusieve rechten van de rechthebbenden op het werk, of op de uitputting van die rechten of andere toepasselijke beperkingen daarvan. - -5.Verplichtingen van de licentiehouder -De verlening van de bovenvermelde rechten is onderworpen aan een aantal aan de licentiehouder opgelegde beperkingen en verplichtingen. Het gaat om de onderstaande verplichtingen. - -Attributierecht: de licentiehouder moet alle auteurs-, octrooi- of merkenrechtelijke kennisgevingen onverlet laten alsook alle kennisgevingen die naar de licentie en de afwijzing van garanties verwijzen. De licentiehouder moet een afschrift van deze kennisgevingen en een afschrift van de licentie bij elke kopie van het werk voegen die hij verspreidt of mededeelt. De licentiehouder moet in elke bewerking duidelijk aangeven dat het werk is gewijzigd, en eveneens de datum van wijziging vermelden. - -Copyleftclausule: wanneer de licentiehouder kopieën van het oorspronkelijke werk of bewerkingen verspreidt of mededeelt, geschiedt die verspreiding of mededeling onder de voorwaarden van deze licentie of van een latere versie van deze licentie, tenzij het oorspronkelijke werk uitdrukkelijk alleen onder deze versie van de licentie wordt verspreid — bijvoorbeeld door de mededeling „alleen EUPL v. 1.2”. De licentiehouder (die licentiegever wordt) kan met betrekking tot het werk of de bewerkingen geen aanvullende bepalingen of voorwaarden opleggen of stellen die de voorwaarden van de licentie wijzigen of beperken. - -Verenigbaarheidsclausule: wanneer de licentiehouder bewerkingen of kopieën ervan verspreidt of mededeelt die zijn gebaseerd op het werk en op een ander werk dat uit hoofde van een verenigbare licentie in licentie is gegeven, kan die verspreiding of mededeling geschieden onder de voorwaarden van deze verenigbare licentie. Voor de toepassing van deze clausule wordt onder „verenigbare licentie” verstaan, de licenties die in het aanhangsel bij deze licentie zijn opgesomd. Indien de verplichtingen van de licentiehouder uit hoofde van de verenigbare licentie in strijd zijn met diens verplichtingen uit hoofde van deze licentie, hebben de verplichtingen van de verenigbare licentie voorrang. - -Verstrekking van de broncode: bij de verspreiding of mededeling van kopieën van het werk verstrekt de licentiehouder een machinaal leesbare kopie van de broncode of geeft hij aan waar deze broncode gemakkelijk en vrij toegankelijk is, zolang de licentiehouder het werk blijft verspreiden of mededelen. - -Juridische bescherming: deze licentie verleent geen toestemming om handelsnamen, handelsmerken, dienstmerken of namen van de licentiegever te gebruiken, behalve wanneer dit op grond van een redelijk en normaal gebruik noodzakelijk is om de oorsprong van het werk te beschrijven en de inhoud van de auteursrechtelijke kennisgeving te herhalen. - -6.Auteursketen -De oorspronkelijke licentiegever garandeert dat hij houder is van het hierbij verleende auteursrecht op het oorspronkelijke werk dan wel dat dit hem in licentie is gegeven en dat hij de bevoegdheid heeft de licentie te verlenen. Elke bewerker garandeert dat hij houder is van het auteursrecht op de door hem aan het werk aangebrachte wijzigingen dan wel dat dit hem in licentie is gegeven en dat hij de bevoegdheid heeft de licentie te verlenen. Telkens wanneer u de licentie aanvaardt, verlenen de oorspronkelijke licentiegever en de opeenvolgende bewerkers u een licentie op hun bijdragen aan het werk onder de voorwaarden van deze licentie. - -7.Uitsluiting van garantie -Het werk is een werk in ontwikkeling, dat voortdurend door vele bewerkers wordt verbeterd. Het is een onvoltooid werk, dat bijgevolg nog tekortkomingen of programmeerfouten („bugs”) kan vertonen, die onlosmakelijk verbonden zijn met dit soort ontwikkeling. Om die reden wordt het werk op grond van de licentie verstrekt „zoals het is” en zonder enige garantie met betrekking tot het werk te geven, met inbegrip van, maar niet beperkt tot garanties met betrekking tot de verhandelbaarheid, de geschiktheid voor een specifiek doel, de afwezigheid van tekortkomingen of fouten, de nauwkeurigheid, de eerbiediging van andere intellectuele-eigendomsrechten dan het in artikel 6 van deze licentie bedoelde auteursrecht. Deze uitsluiting van garantie is een essentieel onderdeel van de licentie en een voorwaarde voor de verlening van rechten op het werk. - -8.Uitsluiting van aansprakelijkheid -Behoudens in het geval van een opzettelijke fout of directe schade aan natuurlijke personen, is de licentiegever in geen enkel geval aansprakelijk voor ongeacht welke directe of indirecte, materiële of immateriële schade die voortvloeit uit de licentie of het gebruik van het werk, met inbegrip van, maar niet beperkt tot schade als gevolg van het verlies van goodwill, verloren werkuren, een computerdefect of computerfout, het verlies van gegevens, of enige andere commerciële schade, zelfs indien de licentiegever werd gewezen op de mogelijkheid van dergelijke schade. De licentiegever is echter aansprakelijk op grond van de wetgeving inzake productaansprakelijkheid, voor zover deze wetgeving op het werk van toepassing is. - -9.Aanvullende overeenkomsten -Bij de verspreiding van het werk kunt u ervoor kiezen een aanvullende overeenkomst te sluiten, waarin de verplichtingen of diensten overeenkomstig deze licentie worden omschreven. Indien deze verplichtingen worden aanvaard, kunt u echter alleen in eigen naam en onder eigen verantwoordelijkheid handelen, en dus niet in naam van de oorspronkelijke licentiegever of een bewerker, en kunt u voorts alleen handelen indien u ermee instemt alle bewerkers schadeloos te stellen, te verdedigen of te vrijwaren met betrekking tot de aansprakelijkheid van of vorderingen tegen deze bewerkers op grond van het feit dat u een garantie of aanvullende aansprakelijkheid hebt aanvaard. - -10.Aanvaarding van de licentie -De bepalingen van deze licentie kunnen worden aanvaard door te klikken op het pictogram „Ik ga akkoord”, dat zich bevindt onderaan het venster waarin de tekst van deze licentie is weergegeven, of door overeenkomstig de toepasselijke wetsbepalingen op een soortgelijke wijze met de licentie in te stemmen. Door op dat pictogram te klikken geeft u aan dat u deze licentie en alle voorwaarden ervan ondubbelzinnig en onherroepelijk aanvaardt. Evenzo aanvaardt u onherroepelijk deze licentie en alle voorwaarden ervan door uitoefening van de rechten die u in artikel 2 van deze licentie zijn verleend, zoals het gebruik van het werk, het creëren door u van een bewerking of de verspreiding of mededeling door u van het werk of kopieën ervan. - -11.Voorlichting van het publiek -Indien u het werk verspreidt of mededeelt door middel van elektronische communicatiemiddelen (bijvoorbeeld door voor te stellen het werk op afstand te downloaden), moet het distributiekanaal of het medium (bijvoorbeeld een website) het publiek ten minste de gegevens verschaffen die door het toepasselijke recht zijn voorgeschreven met betrekking tot de licentiegever, de licentie en de wijze waarop deze kan worden geraadpleegd, gesloten, opgeslagen en gereproduceerd door de licentiehouder. - -12.Einde van de licentie -De licentie en de uit hoofde daarvan verleende rechten eindigen automatisch bij elke inbreuk door de licentiehouder op de voorwaarden van de licentie. Dit einde beëindigt niet de licenties van personen die het werk van de licentiehouder krachtens de licentie hebben ontvangen, mits deze personen zich volledig aan de licentie houden. - -13.Overige -Onverminderd artikel 9 vormt de licentie de gehele overeenkomst tussen de partijen met betrekking tot het werk. Indien een bepaling van de licentie volgens het toepasselijke recht ongeldig is of niet uitvoerbaar is, doet dit geen afbreuk aan de geldigheid of uitvoerbaarheid van de licentie in haar geheel. Deze bepaling dient zodanig te worden uitgelegd of gewijzigd dat zij geldig en uitvoerbaar wordt. De Europese Commissie kan, voor zover dit noodzakelijk en redelijk is, versies in andere talen of nieuwe versies van deze licentie of geactualiseerde versies van dit aanhangsel publiceren, zonder de draagwijdte van de uit hoofde van de licentie verleende rechten te beperken. Nieuwe versies van de licentie zullen worden gepubliceerd met een uniek versienummer. Alle door de Europese Commissie goedgekeurde taalversies van deze licentie hebben dezelfde waarde. De partijen kunnen zich beroepen op de taalversie van hun keuze. - -14.Bevoegd gerecht -Onverminderd specifieke overeenkomsten tussen de partijen, -— vallen alle geschillen tussen de instellingen, organen en instanties van de Europese Unie, als licentiegeefster, en een licentiehouder in verband met de uitlegging van deze licentie onder de bevoegdheid van het Hof van Justitie van de Europese Unie, conform artikel 272 van het Verdrag betreffende de werking van de Europese Unie, -— vallen alle geschillen tussen andere partijen in verband met de uitlegging van deze licentie onder de uitsluitende bevoegdheid van het bevoegde gerecht van de plaats waar de licentiegever is gevestigd of zijn voornaamste activiteit uitoefent. - -15.Toepasselijk recht -Onverminderd specifieke overeenkomsten tussen de partijen, -— wordt deze licentie beheerst door het recht van de lidstaat van de Europese Unie waar de licentiegever zijn statutaire zetel, verblijfplaats of hoofdkantoor heeft, -— wordt deze licentie beheerst door het Belgische recht indien de licentiegever geen statutaire zetel, verblijfplaats of hoofdkantoor heeft in een lidstaat van de Europese Unie. - - -Aanhangsel -„Verenigbare licenties” in de zin van artikel 5 EUPL zijn: -— GNU General Public License (GPL) v. 2, v. 3 -— GNU Affero General Public License (AGPL) v. 3 -— Open Software License (OSL) v. 2.1, v. 3.0 -— Eclipse Public License (EPL) v. 1.0 -— CeCILL v. 2.0, v. 2.1 -— Mozilla Public Licence (MPL) v. 2 -— GNU Lesser General Public Licence (LGPL) v. 2.1, v. 3 -— Creative Commons Attribution-ShareAlike v. 3.0 Unported (CC BY-SA 3.0) voor andere werken dan software -— European Union Public Licence (EUPL) v. 1.1, v. 1.2 -— Québec Free and Open-Source Licence — Reciprocity (LiLiQ-R) of Strong Reciprocity (LiLiQ-R+). -De Europese Commissie kan dit aanhangsel actualiseren in geval van latere versies van de bovengenoemde licenties zonder dat er een nieuwe EUPL-versie wordt ontwikkeld, zolang die versies de uit hoofde van artikel 2 van deze licentie verleende rechten verlenen en ze de betrokken broncode beschermen tegen exclusieve toe-eigening. -Voor alle andere wijzigingen van of aanvullingen op dit aanhangsel is de ontwikkeling van een nieuwe EUPL-versie vereist. -``` + OPENBARE LICENTIE VAN DE EUROPESE UNIE v. 1.2. + EUPL © Europese Unie 2007, 2016 + Deze openbare licentie van de Europese Unie („EUPL”) is van toepassing op het werk (zoals hieronder gedefinieerd) dat onder de voorwaarden van deze licentie wordt verstrekt. Elk gebruik van het werk dat niet door deze licentie is toegestaan, is verboden (voor zover dit gebruik valt onder een recht van de houder van het auteursrecht op het werk). Het werk wordt verstrekt onder de voorwaarden van deze licentie wanneer de licentiegever (zoals hieronder gedefinieerd), direct volgend op de kennisgeving inzake het auteursrecht op het werk, de volgende kennisgeving opneemt: + In licentie gegeven krachtens de EUPL + of op een andere wijze zijn bereidheid te kennen heeft gegeven krachtens de EUPL in licentie te geven. + + 1.Definities + In deze licentie wordt verstaan onder: + — „de licentie”:de onderhavige licentie; + — „het oorspronkelijke werk”:het werk dat of de software die door de licentiegever krachtens deze licentie wordt verspreid of medegedeeld, en dat/die beschikbaar is als broncode en, in voorkomend geval, ook als uitvoerbare code; + — „bewerkingen”:de werken of software die de licentiehouder kan creëren op grond van het oorspronkelijke werk of wijzigingen ervan. In deze licentie wordt niet gedefinieerd welke mate van wijziging of afhankelijkheid van het oorspronkelijke werk vereist is om een werk als een bewerking te kunnen aanmerken; dat wordt bepaald conform het auteursrecht dat van toepassing is in de in artikel 15 bedoelde staat; + — „het werk”:het oorspronkelijke werk of de bewerkingen ervan; + — „de broncode”:de voor mensen leesbare vorm van het werk, die het gemakkelijkste door mensen kan worden bestudeerd en gewijzigd; + — „de uitvoerbare code”:elke code die over het algemeen is gecompileerd en is bedoeld om door een computer als een programma te worden uitgevoerd; + — „de licentiegever”:de natuurlijke of rechtspersoon die het werk krachtens de licentie verspreidt of mededeelt; + — „bewerker(s)”:elke natuurlijke of rechtspersoon die het werk krachtens de licentie wijzigt of op een andere wijze bijdraagt tot de totstandkoming van een bewerking; + — „de licentiehouder” of „u”:elke natuurlijke of rechtspersoon die het werk onder de voorwaarden van de licentie gebruikt; — „verspreiding” of „mededeling”:het verkopen, geven, uitlenen, verhuren, verspreiden, mededelen, doorgeven, of op een andere wijze online of offline beschikbaar stellen van kopieën van het werk of het verlenen van toegang tot de essentiële functies ervan ten behoeve van andere natuurlijke of rechtspersonen. + + 2.Draagwijdte van de uit hoofde van de licentie verleende rechten + De licentiegever verleent u hierbij een wereldwijde, royaltyvrije, niet-exclusieve, voor een sublicentie in aanmerking komende licentie, om voor de duur van het aan het oorspronkelijke werk verbonden auteursrecht, het volgende te doen: + — het werk in alle omstandigheden en voor ongeacht welk doel te gebruiken; + — het werk te verveelvoudigen; + — het werk te wijzigen en op grond van het werk bewerkingen te ontwikkelen; + — het werk aan het publiek mede te delen, waaronder het recht om het werk of kopieën ervan aan het publiek ter beschikking te stellen of te vertonen, en het werk, in voorkomend geval, in het openbaar uit te voeren; + — het werk of kopieën ervan te verspreiden; + — het werk of kopieën ervan uit te lenen en te verhuren; + — de rechten op het werk of op kopieën ervan in sublicentie te geven. + Deze rechten kunnen worden uitgeoefend met gebruikmaking van alle thans bekende of nog uit te vinden media, dragers en formaten, voor zover het toepasselijke recht dit toestaat. In de landen waar immateriële rechten van toepassing zijn, doet de licentiegever afstand van zijn recht op uitoefening van zijn immateriële rechten in de mate die door het toepasselijke recht wordt toegestaan teneinde een doeltreffende uitoefening van de bovenvermelde in licentie gegeven economische rechten mogelijk te maken. De licentiegever verleent de licentiehouder een royaltyvrij, niet-exclusief gebruiksrecht op alle octrooien van de licentiegever, voor zover dit noodzakelijk is om de uit hoofde van deze licentie verleende rechten op het werk te gebruiken. + + 3.Mededeling van de broncode + De licentiegever kan het werk verstrekken in zijn broncode of als uitvoerbare code. Indien het werk als uitvoerbare code wordt verstrekt, verstrekt de licentiegever bij elke door hem verspreide kopie van het werk tevens een machinaal leesbare kopie van de broncode van het werk of geeft hij in een mededeling, volgende op de bij het werk gevoegde auteursrechtelijke kennisgeving, de plaats aan waar de broncode gemakkelijk en vrij toegankelijk is, zolang de licentiegever het werk blijft verspreiden of mededelen. + + 4.Beperkingen van het auteursrecht + Geen enkele bepaling in deze licentie heeft ten doel de licentiehouder het recht te ontnemen een beroep te doen op een uitzondering op of een beperking van de exclusieve rechten van de rechthebbenden op het werk, of op de uitputting van die rechten of andere toepasselijke beperkingen daarvan. + + 5.Verplichtingen van de licentiehouder + De verlening van de bovenvermelde rechten is onderworpen aan een aantal aan de licentiehouder opgelegde beperkingen en verplichtingen. Het gaat om de onderstaande verplichtingen. + + Attributierecht: de licentiehouder moet alle auteurs-, octrooi- of merkenrechtelijke kennisgevingen onverlet laten alsook alle kennisgevingen die naar de licentie en de afwijzing van garanties verwijzen. De licentiehouder moet een afschrift van deze kennisgevingen en een afschrift van de licentie bij elke kopie van het werk voegen die hij verspreidt of mededeelt. De licentiehouder moet in elke bewerking duidelijk aangeven dat het werk is gewijzigd, en eveneens de datum van wijziging vermelden. + + Copyleftclausule: wanneer de licentiehouder kopieën van het oorspronkelijke werk of bewerkingen verspreidt of mededeelt, geschiedt die verspreiding of mededeling onder de voorwaarden van deze licentie of van een latere versie van deze licentie, tenzij het oorspronkelijke werk uitdrukkelijk alleen onder deze versie van de licentie wordt verspreid — bijvoorbeeld door de mededeling „alleen EUPL v. 1.2”. De licentiehouder (die licentiegever wordt) kan met betrekking tot het werk of de bewerkingen geen aanvullende bepalingen of voorwaarden opleggen of stellen die de voorwaarden van de licentie wijzigen of beperken. + + Verenigbaarheidsclausule: wanneer de licentiehouder bewerkingen of kopieën ervan verspreidt of mededeelt die zijn gebaseerd op het werk en op een ander werk dat uit hoofde van een verenigbare licentie in licentie is gegeven, kan die verspreiding of mededeling geschieden onder de voorwaarden van deze verenigbare licentie. Voor de toepassing van deze clausule wordt onder „verenigbare licentie” verstaan, de licenties die in het aanhangsel bij deze licentie zijn opgesomd. Indien de verplichtingen van de licentiehouder uit hoofde van de verenigbare licentie in strijd zijn met diens verplichtingen uit hoofde van deze licentie, hebben de verplichtingen van de verenigbare licentie voorrang. + + Verstrekking van de broncode: bij de verspreiding of mededeling van kopieën van het werk verstrekt de licentiehouder een machinaal leesbare kopie van de broncode of geeft hij aan waar deze broncode gemakkelijk en vrij toegankelijk is, zolang de licentiehouder het werk blijft verspreiden of mededelen. + + Juridische bescherming: deze licentie verleent geen toestemming om handelsnamen, handelsmerken, dienstmerken of namen van de licentiegever te gebruiken, behalve wanneer dit op grond van een redelijk en normaal gebruik noodzakelijk is om de oorsprong van het werk te beschrijven en de inhoud van de auteursrechtelijke kennisgeving te herhalen. + + 6.Auteursketen + De oorspronkelijke licentiegever garandeert dat hij houder is van het hierbij verleende auteursrecht op het oorspronkelijke werk dan wel dat dit hem in licentie is gegeven en dat hij de bevoegdheid heeft de licentie te verlenen. Elke bewerker garandeert dat hij houder is van het auteursrecht op de door hem aan het werk aangebrachte wijzigingen dan wel dat dit hem in licentie is gegeven en dat hij de bevoegdheid heeft de licentie te verlenen. Telkens wanneer u de licentie aanvaardt, verlenen de oorspronkelijke licentiegever en de opeenvolgende bewerkers u een licentie op hun bijdragen aan het werk onder de voorwaarden van deze licentie. + + 7.Uitsluiting van garantie + Het werk is een werk in ontwikkeling, dat voortdurend door vele bewerkers wordt verbeterd. Het is een onvoltooid werk, dat bijgevolg nog tekortkomingen of programmeerfouten („bugs”) kan vertonen, die onlosmakelijk verbonden zijn met dit soort ontwikkeling. Om die reden wordt het werk op grond van de licentie verstrekt „zoals het is” en zonder enige garantie met betrekking tot het werk te geven, met inbegrip van, maar niet beperkt tot garanties met betrekking tot de verhandelbaarheid, de geschiktheid voor een specifiek doel, de afwezigheid van tekortkomingen of fouten, de nauwkeurigheid, de eerbiediging van andere intellectuele-eigendomsrechten dan het in artikel 6 van deze licentie bedoelde auteursrecht. Deze uitsluiting van garantie is een essentieel onderdeel van de licentie en een voorwaarde voor de verlening van rechten op het werk. + + 8.Uitsluiting van aansprakelijkheid + Behoudens in het geval van een opzettelijke fout of directe schade aan natuurlijke personen, is de licentiegever in geen enkel geval aansprakelijk voor ongeacht welke directe of indirecte, materiële of immateriële schade die voortvloeit uit de licentie of het gebruik van het werk, met inbegrip van, maar niet beperkt tot schade als gevolg van het verlies van goodwill, verloren werkuren, een computerdefect of computerfout, het verlies van gegevens, of enige andere commerciële schade, zelfs indien de licentiegever werd gewezen op de mogelijkheid van dergelijke schade. De licentiegever is echter aansprakelijk op grond van de wetgeving inzake productaansprakelijkheid, voor zover deze wetgeving op het werk van toepassing is. + + 9.Aanvullende overeenkomsten + Bij de verspreiding van het werk kunt u ervoor kiezen een aanvullende overeenkomst te sluiten, waarin de verplichtingen of diensten overeenkomstig deze licentie worden omschreven. Indien deze verplichtingen worden aanvaard, kunt u echter alleen in eigen naam en onder eigen verantwoordelijkheid handelen, en dus niet in naam van de oorspronkelijke licentiegever of een bewerker, en kunt u voorts alleen handelen indien u ermee instemt alle bewerkers schadeloos te stellen, te verdedigen of te vrijwaren met betrekking tot de aansprakelijkheid van of vorderingen tegen deze bewerkers op grond van het feit dat u een garantie of aanvullende aansprakelijkheid hebt aanvaard. + + 10.Aanvaarding van de licentie + De bepalingen van deze licentie kunnen worden aanvaard door te klikken op het pictogram „Ik ga akkoord”, dat zich bevindt onderaan het venster waarin de tekst van deze licentie is weergegeven, of door overeenkomstig de toepasselijke wetsbepalingen op een soortgelijke wijze met de licentie in te stemmen. Door op dat pictogram te klikken geeft u aan dat u deze licentie en alle voorwaarden ervan ondubbelzinnig en onherroepelijk aanvaardt. Evenzo aanvaardt u onherroepelijk deze licentie en alle voorwaarden ervan door uitoefening van de rechten die u in artikel 2 van deze licentie zijn verleend, zoals het gebruik van het werk, het creëren door u van een bewerking of de verspreiding of mededeling door u van het werk of kopieën ervan. + + 11.Voorlichting van het publiek + Indien u het werk verspreidt of mededeelt door middel van elektronische communicatiemiddelen (bijvoorbeeld door voor te stellen het werk op afstand te downloaden), moet het distributiekanaal of het medium (bijvoorbeeld een website) het publiek ten minste de gegevens verschaffen die door het toepasselijke recht zijn voorgeschreven met betrekking tot de licentiegever, de licentie en de wijze waarop deze kan worden geraadpleegd, gesloten, opgeslagen en gereproduceerd door de licentiehouder. + + 12.Einde van de licentie + De licentie en de uit hoofde daarvan verleende rechten eindigen automatisch bij elke inbreuk door de licentiehouder op de voorwaarden van de licentie. Dit einde beëindigt niet de licenties van personen die het werk van de licentiehouder krachtens de licentie hebben ontvangen, mits deze personen zich volledig aan de licentie houden. + + 13.Overige + Onverminderd artikel 9 vormt de licentie de gehele overeenkomst tussen de partijen met betrekking tot het werk. Indien een bepaling van de licentie volgens het toepasselijke recht ongeldig is of niet uitvoerbaar is, doet dit geen afbreuk aan de geldigheid of uitvoerbaarheid van de licentie in haar geheel. Deze bepaling dient zodanig te worden uitgelegd of gewijzigd dat zij geldig en uitvoerbaar wordt. De Europese Commissie kan, voor zover dit noodzakelijk en redelijk is, versies in andere talen of nieuwe versies van deze licentie of geactualiseerde versies van dit aanhangsel publiceren, zonder de draagwijdte van de uit hoofde van de licentie verleende rechten te beperken. Nieuwe versies van de licentie zullen worden gepubliceerd met een uniek versienummer. Alle door de Europese Commissie goedgekeurde taalversies van deze licentie hebben dezelfde waarde. De partijen kunnen zich beroepen op de taalversie van hun keuze. + + 14.Bevoegd gerecht + Onverminderd specifieke overeenkomsten tussen de partijen, + — vallen alle geschillen tussen de instellingen, organen en instanties van de Europese Unie, als licentiegeefster, en een licentiehouder in verband met de uitlegging van deze licentie onder de bevoegdheid van het Hof van Justitie van de Europese Unie, conform artikel 272 van het Verdrag betreffende de werking van de Europese Unie, + — vallen alle geschillen tussen andere partijen in verband met de uitlegging van deze licentie onder de uitsluitende bevoegdheid van het bevoegde gerecht van de plaats waar de licentiegever is gevestigd of zijn voornaamste activiteit uitoefent. + + 15.Toepasselijk recht + Onverminderd specifieke overeenkomsten tussen de partijen, + — wordt deze licentie beheerst door het recht van de lidstaat van de Europese Unie waar de licentiegever zijn statutaire zetel, verblijfplaats of hoofdkantoor heeft, + — wordt deze licentie beheerst door het Belgische recht indien de licentiegever geen statutaire zetel, verblijfplaats of hoofdkantoor heeft in een lidstaat van de Europese Unie. + + + Aanhangsel + „Verenigbare licenties” in de zin van artikel 5 EUPL zijn: + — GNU General Public License (GPL) v. 2, v. 3 + — GNU Affero General Public License (AGPL) v. 3 + — Open Software License (OSL) v. 2.1, v. 3.0 + — Eclipse Public License (EPL) v. 1.0 + — CeCILL v. 2.0, v. 2.1 + — Mozilla Public Licence (MPL) v. 2 + — GNU Lesser General Public Licence (LGPL) v. 2.1, v. 3 + — Creative Commons Attribution-ShareAlike v. 3.0 Unported (CC BY-SA 3.0) voor andere werken dan software + — European Union Public Licence (EUPL) v. 1.1, v. 1.2 + — Québec Free and Open-Source Licence — Reciprocity (LiLiQ-R) of Strong Reciprocity (LiLiQ-R+). + De Europese Commissie kan dit aanhangsel actualiseren in geval van latere versies van de bovengenoemde licenties zonder dat er een nieuwe EUPL-versie wordt ontwikkeld, zolang die versies de uit hoofde van artikel 2 van deze licentie verleende rechten verlenen en ze de betrokken broncode beschermen tegen exclusieve toe-eigening. + Voor alle andere wijzigingen van of aanvullingen op dit aanhangsel is de ontwikkeling van een nieuwe EUPL-versie vereist. diff --git a/README.md b/README.md index 35da02ec..e751896c 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ -# CoreBundle [![Codacy Badge](https://app.codacy.com/project/badge/Grade/b6de6f6071044e1783a145afa27f1829)](https://www.codacy.com/gh/CommonGateway/CoreBundle/dashboard?utm_source=github.com&utm_medium=referral&utm_content=CommonGateway/CoreBundle&utm_campaign=Badge_Grade) - +# CoreBundle [![Codacy Badge](https://app.codacy.com/project/badge/Grade/b6de6f6071044e1783a145afa27f1829)](https://www.codacy.com/gh/CommonGateway/CoreBundle/dashboard?utm_source=github.com\&utm_medium=referral\&utm_content=CommonGateway/CoreBundle\&utm_campaign=Badge_Grade) This project holds the common-gateway core bundel -## Licence -This project is released under the [EUPL licence program](https://joinup.ec.europa.eu/collection/eupl/introduction-eupl-licence). \ No newline at end of file +## Licence + +This project is released under the [EUPL licence program](https://joinup.ec.europa.eu/collection/eupl/introduction-eupl-licence). diff --git a/docs/classes/CommonGateway/CoreBundle/Service/RequestService.md b/docs/classes/CommonGateway/CoreBundle/Service/RequestService.md index 1ce0a5ab..c8bc486c 100644 --- a/docs/classes/CommonGateway/CoreBundle/Service/RequestService.md +++ b/docs/classes/CommonGateway/CoreBundle/Service/RequestService.md @@ -1,16 +1,12 @@ -# CommonGateway\CoreBundle\Service\RequestService +# CommonGateway\CoreBundle\Service\RequestService Handles incomming request from endpoints or controllers that relate to the gateways object structure (eav). - - - - ## Methods | Name | Description | |------|-------------| -|[__construct](#requestservice__construct)|| +|[\_\_construct](#requestservice__construct)|| |[checkEmbedded](#requestservicecheckembedded)|If embedded should be shown or not.| |[createResponse](#requestservicecreateresponse)|Creating the response object.| |[getId](#requestservicegetid)|Get the ID from given parameters.| @@ -22,10 +18,7 @@ Handles incomming request from endpoints or controllers that relate to the gatew |[searchRequestHandler](#requestservicesearchrequesthandler)|This function searches all the objectEntities and formats the data.| |[shouldWeUnsetEmbedded](#requestserviceshouldweunsetembedded)|If embedded should be shown or not.| - - - -### RequestService::__construct +### RequestService::\_\_construct **Description** @@ -33,10 +26,6 @@ Handles incomming request from endpoints or controllers that relate to the gatew __construct (void) ``` - - - - **Parameters** `This function has no parameters.` @@ -45,11 +34,9 @@ Handles incomming request from endpoints or controllers that relate to the gatew `void` -
- -### RequestService::checkEmbedded +### RequestService::checkEmbedded **Description** @@ -57,26 +44,20 @@ Handles incomming request from endpoints or controllers that relate to the gatew public checkEmbedded (object|array $result) ``` -If embedded should be shown or not. - - +If embedded should be shown or not. **Parameters** -* `(object|array) $result` -: fetched result +* `(object|array) $result` + : fetched result **Return Values** `array|null` - - -
- -### RequestService::createResponse +### RequestService::createResponse **Description** @@ -84,25 +65,19 @@ If embedded should be shown or not. public createResponse ( $data) ``` -Creating the response object. - - +Creating the response object. **Parameters** -* `() $data` +* `() $data` **Return Values** `\CommonGateway\CoreBundle\Service\Response` - - -
- -### RequestService::getId +### RequestService::getId **Description** @@ -110,25 +85,19 @@ Creating the response object. public getId (array $object) ``` -Get the ID from given parameters. - - +Get the ID from given parameters. **Parameters** -* `(array) $object` +* `(array) $object` **Return Values** `string|false` - - -
- -### RequestService::getSchema +### RequestService::getSchema **Description** @@ -136,25 +105,19 @@ Get the ID from given parameters. public getSchema (array $parameters) ``` -Get the schema from given parameters returns false if no schema could be established. - - +Get the schema from given parameters returns false if no schema could be established. **Parameters** -* `(array) $parameters` +* `(array) $parameters` **Return Values** `\Entity|false` - - -
- -### RequestService::itemRequestHandler +### RequestService::itemRequestHandler **Description** @@ -162,10 +125,6 @@ Get the schema from given parameters returns false if no schema could be establi itemRequestHandler (void) ``` - - - - **Parameters** `This function has no parameters.` @@ -174,11 +133,9 @@ Get the schema from given parameters returns false if no schema could be establi `void` -
- -### RequestService::proxyHandler +### RequestService::proxyHandler **Description** @@ -186,10 +143,6 @@ Get the schema from given parameters returns false if no schema could be establi proxyHandler (void) ``` - - - - **Parameters** `This function has no parameters.` @@ -198,11 +151,9 @@ Get the schema from given parameters returns false if no schema could be establi `void` -
- -### RequestService::realRequestQueryAll +### RequestService::realRequestQueryAll **Description** @@ -210,14 +161,14 @@ Get the schema from given parameters returns false if no schema could be establi public realRequestQueryAll (string $method) ``` -A function to replace Request->query->all() because Request->query->all() will replace some characters with an underscore. +A function to replace Request->query->all() because Request->query->all() will replace some characters with an underscore. -This function will not. +This function will not. **Parameters** -* `(string) $method` -: The method of the Request +* `(string) $method` + : The method of the Request **Return Values** @@ -225,11 +176,9 @@ This function will not. > An array with all query parameters. -
- -### RequestService::requestHandler +### RequestService::requestHandler **Description** @@ -237,16 +186,14 @@ This function will not. public requestHandler (array $data, array $configuration) ``` -Handles incomming requests and is responsible for generating a response. - - +Handles incomming requests and is responsible for generating a response. **Parameters** -* `(array) $data` -: The data from the call -* `(array) $configuration` -: The configuration from the call +* `(array) $data` + : The data from the call +* `(array) $configuration` + : The configuration from the call **Return Values** @@ -254,11 +201,9 @@ Handles incomming requests and is responsible for generating a response. > The modified data -
- -### RequestService::searchRequestHandler +### RequestService::searchRequestHandler **Description** @@ -266,16 +211,14 @@ Handles incomming requests and is responsible for generating a response. public searchRequestHandler (array $data, array $configuration) ``` -This function searches all the objectEntities and formats the data. - - +This function searches all the objectEntities and formats the data. **Parameters** -* `(array) $data` -: The data from the call -* `(array) $configuration` -: The configuration from the call +* `(array) $data` + : The data from the call +* `(array) $configuration` + : The configuration from the call **Return Values** @@ -283,11 +226,9 @@ This function searches all the objectEntities and formats the data. > The modified data -
- -### RequestService::shouldWeUnsetEmbedded +### RequestService::shouldWeUnsetEmbedded **Description** @@ -295,23 +236,17 @@ This function searches all the objectEntities and formats the data. public shouldWeUnsetEmbedded (object|array $result, ?array $accept) ``` -If embedded should be shown or not. - - +If embedded should be shown or not. **Parameters** -* `(object|array) $result` -: fetched result -* `(?array) $accept` -: accept header +* `(object|array) $result` + : fetched result +* `(?array) $accept` + : accept header **Return Values** `array|null` - - -
- diff --git a/docs/classes/README.md b/docs/classes/README.md index 9e43e8dc..a4a63687 100644 --- a/docs/classes/README.md +++ b/docs/classes/README.md @@ -1,10 +1,10 @@ # CommonGateway\CoreBundle -* [Service\AuthenticationService](Service/AuthenticationService.md) -* [Service\CacheService](Service/CacheService.md) -* [Service\CallService](Service/CallService.md) -* [Service\ComposerService](Service/ComposerService.md) -* [Service\EavService](Service/EavService.md) -* [Service\FileService](Service/FileService.md) -* [Service\InstallationService](Service/InstallationService.md) -* [Service\RequestService](Service/RequestService.md) +* [Service\AuthenticationService](Service/AuthenticationService.md) +* [Service\CacheService](Service/CacheService.md) +* [Service\CallService](Service/CallService.md) +* [Service\ComposerService](Service/ComposerService.md) +* [Service\EavService](Service/EavService.md) +* [Service\FileService](Service/FileService.md) +* [Service\InstallationService](Service/InstallationService.md) +* [Service\RequestService](Service/RequestService.md) diff --git a/docs/classes/Service/AuthenticationService.md b/docs/classes/Service/AuthenticationService.md index 258a66c4..6bba294e 100644 --- a/docs/classes/Service/AuthenticationService.md +++ b/docs/classes/Service/AuthenticationService.md @@ -1,16 +1,10 @@ -# CommonGateway\CoreBundle\Service\AuthenticationService - - - - - - +# CommonGateway\CoreBundle\Service\AuthenticationService ## Methods | Name | Description | |------|-------------| -|[__construct](#authenticationservice__construct)|| +|[\_\_construct](#authenticationservice__construct)|| |[checkHS256](#authenticationservicecheckhs256)|Decides if the provided JWT token is signed with the HS256 Algorithm.| |[checkHeadersAndGetJWK](#authenticationservicecheckheadersandgetjwk)|Checks the algorithm of the JWT token and decides how to generate a JWK from the provided public key.| |[checkRS256](#authenticationservicecheckrs256)|Decides if the provided JWT token is signed with the HS256 Algorithm.| @@ -31,10 +25,7 @@ |[serializeUser](#authenticationserviceserializeuser)|Serializes a user to be used by the token authenticator.| |[verifyJWTToken](#authenticationserviceverifyjwttoken)|Verifies the JWT token and returns the payload if the JWT token is valid.| - - - -### AuthenticationService::__construct +### AuthenticationService::\_\_construct **Description** @@ -42,10 +33,6 @@ __construct (void) ``` - - - - **Parameters** `This function has no parameters.` @@ -54,11 +41,9 @@ `void` -
- -### AuthenticationService::checkHS256 +### AuthenticationService::checkHS256 **Description** @@ -66,14 +51,12 @@ public checkHS256 (\JWT $token) ``` -Decides if the provided JWT token is signed with the HS256 Algorithm. - - +Decides if the provided JWT token is signed with the HS256 Algorithm. **Parameters** -* `(\JWT) $token` -: The token provided by the user +* `(\JWT) $token` + : The token provided by the user **Return Values** @@ -81,11 +64,9 @@ Decides if the provided JWT token is signed with the HS256 Algorithm. > Whether the token is in HS256 or not -
- -### AuthenticationService::checkHeadersAndGetJWK +### AuthenticationService::checkHeadersAndGetJWK **Description** @@ -93,16 +74,14 @@ Decides if the provided JWT token is signed with the HS256 Algorithm. public checkHeadersAndGetJWK (\JWT $token, string $publicKey) ``` -Checks the algorithm of the JWT token and decides how to generate a JWK from the provided public key. - - +Checks the algorithm of the JWT token and decides how to generate a JWK from the provided public key. **Parameters** -* `(\JWT) $token` -: The JWT token sent by the user -* `(string) $publicKey` -: The public key provided by the application +* `(\JWT) $token` + : The JWT token sent by the user +* `(string) $publicKey` + : The public key provided by the application **Return Values** @@ -110,11 +89,9 @@ Checks the algorithm of the JWT token and decides how to generate a JWK from the > The resulting JWK for verifying the JWT -
- -### AuthenticationService::checkRS256 +### AuthenticationService::checkRS256 **Description** @@ -122,14 +99,12 @@ Checks the algorithm of the JWT token and decides how to generate a JWK from the public checkRS256 (\JWT $token) ``` -Decides if the provided JWT token is signed with the HS256 Algorithm. - - +Decides if the provided JWT token is signed with the HS256 Algorithm. **Parameters** -* `(\JWT) $token` -: The token provided by the user +* `(\JWT) $token` + : The token provided by the user **Return Values** @@ -137,11 +112,9 @@ Decides if the provided JWT token is signed with the HS256 Algorithm. > Whether the token is in HS256 or not -
- -### AuthenticationService::checkRS512 +### AuthenticationService::checkRS512 **Description** @@ -149,14 +122,12 @@ Decides if the provided JWT token is signed with the HS256 Algorithm. public checkRS512 (\JWT $token) ``` -Decides if the provided JWT token is signed with the RS512 Algorithm. - - +Decides if the provided JWT token is signed with the RS512 Algorithm. **Parameters** -* `(\JWT) $token` -: The token provided by the user +* `(\JWT) $token` + : The token provided by the user **Return Values** @@ -164,11 +135,9 @@ Decides if the provided JWT token is signed with the RS512 Algorithm. > Whether the token is in HS256 or not -
- -### AuthenticationService::convertRSAKeyToJWK +### AuthenticationService::convertRSAKeyToJWK **Description** @@ -176,14 +145,12 @@ Decides if the provided JWT token is signed with the RS512 Algorithm. public convertRSAKeyToJWK (string $key) ``` -Converts a string RSA key to a JWK via the filesystem. - - +Converts a string RSA key to a JWK via the filesystem. **Parameters** -* `(string) $key` -: The key to load +* `(string) $key` + : The key to load **Return Values** @@ -191,11 +158,9 @@ Converts a string RSA key to a JWK via the filesystem. > The resulting Json Web Key -
- -### AuthenticationService::convertRSAtoJWK +### AuthenticationService::convertRSAtoJWK **Description** @@ -203,13 +168,11 @@ Converts a string RSA key to a JWK via the filesystem. public convertRSAtoJWK (\Source $source) ``` -Converts a RSA private key to a JWK. - - +Converts a RSA private key to a JWK. **Parameters** -* `(\Source) $source` +* `(\Source) $source` **Return Values** @@ -217,11 +180,9 @@ Converts a RSA private key to a JWK. > The resulting Json Web Key -
- -### AuthenticationService::createJwtToken +### AuthenticationService::createJwtToken **Description** @@ -229,16 +190,14 @@ Converts a RSA private key to a JWK. public createJwtToken (string $key, array $payload) ``` -Creates a JWT token to identify with on the application. - - +Creates a JWT token to identify with on the application. **Parameters** -* `(string) $key` -: The private key to create a JWT token with -* `(array) $payload` -: The payload to create a JWT token with +* `(string) $key` + : The private key to create a JWT token with +* `(array) $payload` + : The payload to create a JWT token with **Return Values** @@ -246,11 +205,9 @@ Creates a JWT token to identify with on the application. > The resulting JWT token -
- -### AuthenticationService::getAlgorithm +### AuthenticationService::getAlgorithm **Description** @@ -258,14 +215,12 @@ Creates a JWT token to identify with on the application. public getAlgorithm (\Source $source) ``` -Determines the algorithm for the JWT token to create from the source. - - +Determines the algorithm for the JWT token to create from the source. **Parameters** -* `(\Source) $source` -: The source to determine the algorithm for +* `(\Source) $source` + : The source to determine the algorithm for **Return Values** @@ -273,11 +228,9 @@ Determines the algorithm for the JWT token to create from the source. > The algorithm to use -
- -### AuthenticationService::getApplicationId +### AuthenticationService::getApplicationId **Description** @@ -285,14 +238,12 @@ Determines the algorithm for the JWT token to create from the source. public getApplicationId (\Source $source) ``` -Gets an application id for a source. - - +Gets an application id for a source. **Parameters** -* `(\Source) $source` -: The source to dermine the application id for +* `(\Source) $source` + : The source to dermine the application id for **Return Values** @@ -300,11 +251,9 @@ Gets an application id for a source. > The application ID to use -
- -### AuthenticationService::getAuthentication +### AuthenticationService::getAuthentication **Description** @@ -312,10 +261,6 @@ Gets an application id for a source. getAuthentication (void) ``` - - - - **Parameters** `This function has no parameters.` @@ -324,11 +269,9 @@ Gets an application id for a source. `void` -
- -### AuthenticationService::getCertificate +### AuthenticationService::getCertificate **Description** @@ -336,14 +279,12 @@ Gets an application id for a source. public getCertificate (array $config) ``` -Writes the certificate and ssl keys to disk, returns the filenames. - - +Writes the certificate and ssl keys to disk, returns the filenames. **Parameters** -* `(array) $config` -: The configuration as stored in the source +* `(array) $config` + : The configuration as stored in the source **Return Values** @@ -351,11 +292,9 @@ Writes the certificate and ssl keys to disk, returns the filenames. > The overrides on the configuration with filenames instead of certificate contents -
- -### AuthenticationService::getHmacToken +### AuthenticationService::getHmacToken **Description** @@ -363,10 +302,6 @@ Writes the certificate and ssl keys to disk, returns the filenames. getHmacToken (void) ``` - - - - **Parameters** `This function has no parameters.` @@ -375,11 +310,9 @@ Writes the certificate and ssl keys to disk, returns the filenames. `void` -
- -### AuthenticationService::getJWK +### AuthenticationService::getJWK **Description** @@ -387,14 +320,12 @@ Writes the certificate and ssl keys to disk, returns the filenames. public getJWK (string $algorithm, \Source $source) ``` -Gets a JWK for a source based on the algorithm of the source. - - +Gets a JWK for a source based on the algorithm of the source. **Parameters** -* `(string) $algorithm` -* `(\Source) $source` +* `(string) $algorithm` +* `(\Source) $source` **Return Values** @@ -402,11 +333,9 @@ Gets a JWK for a source based on the algorithm of the source. > The resulting Json Web Key -
- -### AuthenticationService::getJwtPayload +### AuthenticationService::getJwtPayload **Description** @@ -414,14 +343,12 @@ Gets a JWK for a source based on the algorithm of the source. public getJwtPayload (\Source $source) ``` -Creates the JWT payload to identify at an external source. - - +Creates the JWT payload to identify at an external source. **Parameters** -* `(\Source) $source` -: The source to create a payload for +* `(\Source) $source` + : The source to create a payload for **Return Values** @@ -429,11 +356,9 @@ Creates the JWT payload to identify at an external source. > The JWT payload to use -
- -### AuthenticationService::getJwtToken +### AuthenticationService::getJwtToken **Description** @@ -441,14 +366,12 @@ Creates the JWT payload to identify at an external source. public getJwtToken (\Source $source) ``` -Create a JWT token from Component settings. - - +Create a JWT token from Component settings. **Parameters** -* `(\Source) $source` -: The source to authenticate to +* `(\Source) $source` + : The source to authenticate to **Return Values** @@ -456,11 +379,9 @@ Create a JWT token from Component settings. > The resulting JWT token -
- -### AuthenticationService::getTokenFromUrl +### AuthenticationService::getTokenFromUrl **Description** @@ -468,10 +389,6 @@ Create a JWT token from Component settings. getTokenFromUrl (void) ``` - - - - **Parameters** `This function has no parameters.` @@ -480,11 +397,9 @@ Create a JWT token from Component settings. `void` -
- -### AuthenticationService::removeFiles +### AuthenticationService::removeFiles **Description** @@ -492,26 +407,20 @@ Create a JWT token from Component settings. public removeFiles (array $config) ``` -Removes certificates and private keys from disk if they are not necessary anymore. - - +Removes certificates and private keys from disk if they are not necessary anymore. **Parameters** -* `(array) $config` -: The configuration with filenames +* `(array) $config` + : The configuration with filenames **Return Values** `void` - - -
- -### AuthenticationService::serializeUser +### AuthenticationService::serializeUser **Description** @@ -519,16 +428,14 @@ Removes certificates and private keys from disk if they are not necessary anymor public serializeUser (\User $user, \SessionInterface $session) ``` -Serializes a user to be used by the token authenticator. - - +Serializes a user to be used by the token authenticator. **Parameters** -* `(\User) $user` -: The user to be serialized -* `(\SessionInterface) $session` -: The session to use +* `(\User) $user` + : The user to be serialized +* `(\SessionInterface) $session` + : The session to use **Return Values** @@ -536,11 +443,9 @@ Serializes a user to be used by the token authenticator. > The serialized user -
- -### AuthenticationService::verifyJWTToken +### AuthenticationService::verifyJWTToken **Description** @@ -548,16 +453,14 @@ Serializes a user to be used by the token authenticator. public verifyJWTToken (string $token, string $publicKey) ``` -Verifies the JWT token and returns the payload if the JWT token is valid. - - +Verifies the JWT token and returns the payload if the JWT token is valid. **Parameters** -* `(string) $token` -: The token to verify -* `(string) $publicKey` -: The public key to verify the token to +* `(string) $token` + : The token to verify +* `(string) $publicKey` + : The public key to verify the token to **Return Values** @@ -565,12 +468,10 @@ Verifies the JWT token and returns the payload if the JWT token is valid. > The payload of the token - **Throws Exceptions** - `\HttpException` + > Thrown when the token cannot be verified
- diff --git a/docs/classes/Service/CacheService.md b/docs/classes/Service/CacheService.md index 3c92a1fb..ea0b448c 100644 --- a/docs/classes/Service/CacheService.md +++ b/docs/classes/Service/CacheService.md @@ -1,18 +1,14 @@ -# CommonGateway\CoreBundle\Service\CacheService +# CommonGateway\CoreBundle\Service\CacheService Service to call external sources. -This service provides a guzzle wrapper to work with sources in the common gateway. - - - - +This service provides a guzzle wrapper to work with sources in the common gateway. ## Methods | Name | Description | |------|-------------| -|[__construct](#cacheservice__construct)|| +|[\_\_construct](#cacheservice__construct)|| |[cacheEndpoint](#cacheservicecacheendpoint)|Put a single endpoint into the cache.| |[cacheObject](#cacheservicecacheobject)|Put a single object into the cache.| |[cacheShema](#cacheservicecacheshema)|Put a single schema into the cache.| @@ -29,10 +25,7 @@ This service provides a guzzle wrapper to work with sources in the common gatewa |[setStyle](#cacheservicesetstyle)|Set symfony style in order to output to the console.| |[warmup](#cacheservicewarmup)|Throws all available objects into the cache.| - - - -### CacheService::__construct +### CacheService::\_\_construct **Description** @@ -40,10 +33,6 @@ This service provides a guzzle wrapper to work with sources in the common gatewa __construct (void) ``` - - - - **Parameters** `This function has no parameters.` @@ -52,11 +41,9 @@ This service provides a guzzle wrapper to work with sources in the common gatewa `void` -
- -### CacheService::cacheEndpoint +### CacheService::cacheEndpoint **Description** @@ -64,25 +51,19 @@ This service provides a guzzle wrapper to work with sources in the common gatewa public cacheEndpoint (\Endpoint $endpoint) ``` -Put a single endpoint into the cache. - - +Put a single endpoint into the cache. **Parameters** -* `(\Endpoint) $endpoint` +* `(\Endpoint) $endpoint` **Return Values** `\Endpoint` - - -
- -### CacheService::cacheObject +### CacheService::cacheObject **Description** @@ -90,25 +71,19 @@ Put a single endpoint into the cache. public cacheObject (\ObjectEntity $objectEntity) ``` -Put a single object into the cache. - - +Put a single object into the cache. **Parameters** -* `(\ObjectEntity) $objectEntity` +* `(\ObjectEntity) $objectEntity` **Return Values** `\ObjectEntity` - - -
- -### CacheService::cacheShema +### CacheService::cacheShema **Description** @@ -116,25 +91,19 @@ Put a single object into the cache. public cacheShema (\Entity $entity) ``` -Put a single schema into the cache. - - +Put a single schema into the cache. **Parameters** -* `(\Entity) $entity` +* `(\Entity) $entity` **Return Values** `\Entity` - - -
- -### CacheService::cleanup +### CacheService::cleanup **Description** @@ -142,9 +111,7 @@ Put a single schema into the cache. public cleanup (void) ``` -Remov non-exisitng items from the cashe. - - +Remov non-exisitng items from the cashe. **Parameters** @@ -154,11 +121,9 @@ Remov non-exisitng items from the cashe. `void` -
- -### CacheService::getEndpoint +### CacheService::getEndpoint **Description** @@ -166,25 +131,19 @@ Remov non-exisitng items from the cashe. public getEndpoint (\Uuid $id) ``` -Get a single endpoint from the cache. - - +Get a single endpoint from the cache. **Parameters** -* `(\Uuid) $id` +* `(\Uuid) $id` **Return Values** `array|null` - - -
- -### CacheService::getEndpoints +### CacheService::getEndpoints **Description** @@ -192,10 +151,6 @@ Get a single endpoint from the cache. getEndpoints (void) ``` - - - - **Parameters** `This function has no parameters.` @@ -204,11 +159,9 @@ Get a single endpoint from the cache. `void` -
- -### CacheService::getObject +### CacheService::getObject **Description** @@ -216,25 +169,19 @@ Get a single endpoint from the cache. public getObject (string $id) ``` -Get a single object from the cache. - - +Get a single object from the cache. **Parameters** -* `(string) $id` +* `(string) $id` **Return Values** `array|null` - - -
- -### CacheService::getSchema +### CacheService::getSchema **Description** @@ -242,25 +189,19 @@ Get a single object from the cache. public getSchema (\Uuid $id) ``` -Get a single schema from the cache. - - +Get a single schema from the cache. **Parameters** -* `(\Uuid) $id` +* `(\Uuid) $id` **Return Values** `array|null` - - -
- -### CacheService::removeEndpoint +### CacheService::removeEndpoint **Description** @@ -268,25 +209,19 @@ Get a single schema from the cache. public removeEndpoint (\Endpoint $endpoint) ``` -Removes an endpoint from the cache. - - +Removes an endpoint from the cache. **Parameters** -* `(\Endpoint) $endpoint` +* `(\Endpoint) $endpoint` **Return Values** `void` - - -
- -### CacheService::removeObject +### CacheService::removeObject **Description** @@ -294,25 +229,19 @@ Removes an endpoint from the cache. public removeObject (\ObjectEntity $objectEntity) ``` -Removes an object from the cache. - - +Removes an object from the cache. **Parameters** -* `(\ObjectEntity) $objectEntity` +* `(\ObjectEntity) $objectEntity` **Return Values** `void` - - -
- -### CacheService::removeSchema +### CacheService::removeSchema **Description** @@ -320,25 +249,19 @@ Removes an object from the cache. public removeSchema (\Entity $entity) ``` -Removes an Schema from the cache. - - +Removes an Schema from the cache. **Parameters** -* `(\Entity) $entity` +* `(\Entity) $entity` **Return Values** `void` - - -
- -### CacheService::searchObjects +### CacheService::searchObjects **Description** @@ -346,36 +269,28 @@ Removes an Schema from the cache. public searchObjects (string $search, array $filter, array $entities) ``` -Searches the object store for objects containing the search string. - - +Searches the object store for objects containing the search string. **Parameters** -* `(string) $search` -: a string to search for within the given context -* `(array) $filter` -: an array of dot.notation filters for wich to search with -* `(array) $entities` -: schemas to limit te search to +* `(string) $search` + : a string to search for within the given context +* `(array) $filter` + : an array of dot.notation filters for wich to search with +* `(array) $entities` + : schemas to limit te search to **Return Values** `array|null` - - - **Throws Exceptions** - `\Exception` -
- -### CacheService::setPagination +### CacheService::setPagination **Description** @@ -383,30 +298,24 @@ Searches the object store for objects containing the search string. public setPagination (int $limit, int $start, array $filters) ``` -Decides the pagination values. - - +Decides the pagination values. **Parameters** -* `(int) $limit` -: The resulting limit -* `(int) $start` -: The resulting start value -* `(array) $filters` -: The filters +* `(int) $limit` + : The resulting limit +* `(int) $start` + : The resulting start value +* `(array) $filters` + : The filters **Return Values** `array` - - -
- -### CacheService::setStyle +### CacheService::setStyle **Description** @@ -414,25 +323,19 @@ Decides the pagination values. public setStyle (\SymfonyStyle $io) ``` -Set symfony style in order to output to the console. - - +Set symfony style in order to output to the console. **Parameters** -* `(\SymfonyStyle) $io` +* `(\SymfonyStyle) $io` **Return Values** `self` - - -
- -### CacheService::warmup +### CacheService::warmup **Description** @@ -440,9 +343,7 @@ Set symfony style in order to output to the console. public warmup (void) ``` -Throws all available objects into the cache. - - +Throws all available objects into the cache. **Parameters** @@ -452,6 +353,4 @@ Throws all available objects into the cache. `void` -
- diff --git a/docs/classes/Service/CallService.md b/docs/classes/Service/CallService.md index 05e65f9e..f076d220 100644 --- a/docs/classes/Service/CallService.md +++ b/docs/classes/Service/CallService.md @@ -1,28 +1,21 @@ -# CommonGateway\CoreBundle\Service\CallService +# CommonGateway\CoreBundle\Service\CallService Service to call external sources. -This service provides a guzzle wrapper to work with sources in the common gateway. - - - - +This service provides a guzzle wrapper to work with sources in the common gateway. ## Methods | Name | Description | |------|-------------| -|[__construct](#callservice__construct)|| +|[\_\_construct](#callservice__construct)|| |[call](#callservicecall)|Calls a source according to given configuration.| |[decodeResponse](#callservicedecoderesponse)|Decodes a response based on the source it belongs to.| |[getAllResults](#callservicegetallresults)|Fetches all pages for a source and merges the result arrays to one array.| |[getCertificate](#callservicegetcertificate)|Writes the certificate and ssl keys to disk, returns the filenames.| |[removeFiles](#callserviceremovefiles)|Removes certificates and private keys from disk if they are not necessary anymore.| - - - -### CallService::__construct +### CallService::\_\_construct **Description** @@ -30,10 +23,6 @@ This service provides a guzzle wrapper to work with sources in the common gatewa __construct (void) ``` - - - - **Parameters** `This function has no parameters.` @@ -42,11 +31,9 @@ This service provides a guzzle wrapper to work with sources in the common gatewa `void` -
- -### CallService::call +### CallService::call **Description** @@ -54,35 +41,29 @@ This service provides a guzzle wrapper to work with sources in the common gatewa public call (\Source $source, string $endpoint, string $method, array $config, bool $asynchronous, bool $createCertificates) ``` -Calls a source according to given configuration. - - +Calls a source according to given configuration. **Parameters** -* `(\Source) $source` -: The source to call -* `(string) $endpoint` -: The endpoint on the source to call -* `(string) $method` -: The method on which to call the source -* `(array) $config` -: The additional configuration to call the source -* `(bool) $asynchronous` -: Whether or not to call the source asynchronously -* `(bool) $createCertificates` +* `(\Source) $source` + : The source to call +* `(string) $endpoint` + : The endpoint on the source to call +* `(string) $method` + : The method on which to call the source +* `(array) $config` + : The additional configuration to call the source +* `(bool) $asynchronous` + : Whether or not to call the source asynchronously +* `(bool) $createCertificates` **Return Values** `\Response` - - -
- -### CallService::decodeResponse +### CallService::decodeResponse **Description** @@ -90,16 +71,14 @@ Calls a source according to given configuration. public decodeResponse (\Source $source, \Response $response) ``` -Decodes a response based on the source it belongs to. - - +Decodes a response based on the source it belongs to. **Parameters** -* `(\Source) $source` -: The source that has been called -* `(\Response) $response` -: The response to decode +* `(\Source) $source` + : The source that has been called +* `(\Response) $response` + : The response to decode **Return Values** @@ -107,17 +86,15 @@ Decodes a response based on the source it belongs to. > The decoded response - **Throws Exceptions** - `\Exception` + > Thrown if the response does not fit any supported content type
- -### CallService::getAllResults +### CallService::getAllResults **Description** @@ -125,18 +102,16 @@ Decodes a response based on the source it belongs to. public getAllResults (\Source $source, string $endpoint, array $config) ``` -Fetches all pages for a source and merges the result arrays to one array. - - +Fetches all pages for a source and merges the result arrays to one array. **Parameters** -* `(\Source) $source` -: The source to call -* `(string) $endpoint` -: The endpoint on the source to call -* `(array) $config` -: The additional configuration to call the source +* `(\Source) $source` + : The source to call +* `(string) $endpoint` + : The endpoint on the source to call +* `(array) $config` + : The additional configuration to call the source **Return Values** @@ -144,11 +119,9 @@ Fetches all pages for a source and merges the result arrays to one array. > The array of results -
- -### CallService::getCertificate +### CallService::getCertificate **Description** @@ -156,26 +129,20 @@ Fetches all pages for a source and merges the result arrays to one array. public getCertificate (array $config) ``` -Writes the certificate and ssl keys to disk, returns the filenames. - - +Writes the certificate and ssl keys to disk, returns the filenames. **Parameters** -* `(array) $config` -: The configuration as stored in the source +* `(array) $config` + : The configuration as stored in the source **Return Values** `void` - - -
- -### CallService::removeFiles +### CallService::removeFiles **Description** @@ -183,21 +150,15 @@ Writes the certificate and ssl keys to disk, returns the filenames. public removeFiles (array $config) ``` -Removes certificates and private keys from disk if they are not necessary anymore. - - +Removes certificates and private keys from disk if they are not necessary anymore. **Parameters** -* `(array) $config` -: The configuration with filenames +* `(array) $config` + : The configuration with filenames **Return Values** `void` - - -
- diff --git a/docs/classes/Service/ComposerService.md b/docs/classes/Service/ComposerService.md index 18603ab2..d9754565 100644 --- a/docs/classes/Service/ComposerService.md +++ b/docs/classes/Service/ComposerService.md @@ -1,10 +1,4 @@ -# CommonGateway\CoreBundle\Service\ComposerService - - - - - - +# CommonGateway\CoreBundle\Service\ComposerService ## Methods @@ -19,10 +13,7 @@ |[search](#composerservicesearch)|Search for a given term.| |[upgrade](#composerserviceupgrade)|Show a single packadge installed trough composer.| - - - -### ComposerService::audit +### ComposerService::audit **Description** @@ -30,25 +21,21 @@ public audit (array $options) ``` -Search for a given term. +Search for a given term. -See https://getcomposer.org/doc/03-cli.md#show-info for a full list of al options and there function +See https://getcomposer.org/doc/03-cli.md#show-info for a full list of al options and there function **Parameters** -* `(array) $options` +* `(array) $options` **Return Values** `array` - - -
- -### ComposerService::getAll +### ComposerService::getAll **Description** @@ -56,25 +43,21 @@ See https://getcomposer.org/doc/03-cli.md#show-info for a full list of al option public getAll (array $options) ``` -Show al packadges installed trough composer. +Show al packadges installed trough composer. -See https://getcomposer.org/doc/03-cli.md#show-info for a full list of al options and there function +See https://getcomposer.org/doc/03-cli.md#show-info for a full list of al options and there function **Parameters** -* `(array) $options` +* `(array) $options` **Return Values** `array` - - -
- -### ComposerService::getLockFile +### ComposerService::getLockFile **Description** @@ -82,9 +65,7 @@ See https://getcomposer.org/doc/03-cli.md#show-info for a full list of al option public getLockFile (void) ``` -Gets all installed plugins from the lock file. - - +Gets all installed plugins from the lock file. **Parameters** @@ -94,11 +75,9 @@ Gets all installed plugins from the lock file. `void` -
- -### ComposerService::getSingle +### ComposerService::getSingle **Description** @@ -106,25 +85,21 @@ Gets all installed plugins from the lock file. public getSingle (array $options) ``` -Show a single packadge installed trough composer. +Show a single packadge installed trough composer. -See https://getcomposer.org/doc/03-cli.md#show-info for a full list of al options and there function +See https://getcomposer.org/doc/03-cli.md#show-info for a full list of al options and there function **Parameters** -* `(array) $options` +* `(array) $options` **Return Values** `array` - - -
- -### ComposerService::remove +### ComposerService::remove **Description** @@ -132,25 +107,21 @@ See https://getcomposer.org/doc/03-cli.md#show-info for a full list of al option public remove (array $options) ``` -Show a single packadge installed trough composer. +Show a single packadge installed trough composer. -See https://getcomposer.org/doc/03-cli.md#show-info for a full list of al options and there function +See https://getcomposer.org/doc/03-cli.md#show-info for a full list of al options and there function **Parameters** -* `(array) $options` +* `(array) $options` **Return Values** `array` - - -
- -### ComposerService::require +### ComposerService::require **Description** @@ -158,25 +129,21 @@ See https://getcomposer.org/doc/03-cli.md#show-info for a full list of al option public require (array $options) ``` -Show a single packadge installed trough composer. +Show a single packadge installed trough composer. -See https://getcomposer.org/doc/03-cli.md#show-info for a full list of al options and there function +See https://getcomposer.org/doc/03-cli.md#show-info for a full list of al options and there function **Parameters** -* `(array) $options` +* `(array) $options` **Return Values** `array` - - -
- -### ComposerService::search +### ComposerService::search **Description** @@ -184,25 +151,21 @@ See https://getcomposer.org/doc/03-cli.md#show-info for a full list of al option public search (array $options) ``` -Search for a given term. +Search for a given term. -See https://getcomposer.org/doc/03-cli.md#show-info for a full list of al options and there function +See https://getcomposer.org/doc/03-cli.md#show-info for a full list of al options and there function **Parameters** -* `(array) $options` +* `(array) $options` **Return Values** `array` - - -
- -### ComposerService::upgrade +### ComposerService::upgrade **Description** @@ -210,20 +173,16 @@ See https://getcomposer.org/doc/03-cli.md#show-info for a full list of al option public upgrade (array $options) ``` -Show a single packadge installed trough composer. +Show a single packadge installed trough composer. -See https://getcomposer.org/doc/03-cli.md#show-info for a full list of al options and there function +See https://getcomposer.org/doc/03-cli.md#show-info for a full list of al options and there function **Parameters** -* `(array) $options` +* `(array) $options` **Return Values** `array` - - -
- diff --git a/docs/classes/Service/EavService.md b/docs/classes/Service/EavService.md index ab30d725..f66c1ffa 100644 --- a/docs/classes/Service/EavService.md +++ b/docs/classes/Service/EavService.md @@ -1,24 +1,15 @@ -# CommonGateway\CoreBundle\Service\EavService - - - - - - +# CommonGateway\CoreBundle\Service\EavService ## Methods | Name | Description | |------|-------------| -|[__construct](#eavservice__construct)|| +|[\_\_construct](#eavservice__construct)|| |[checkAttributeforEntity](#eavservicecheckattributeforentity)|Checks an atribute to see if a schema for its reference has becomme available.| |[checkEntityforAttribute](#eavservicecheckentityforattribute)|Checks an entity to see if there are anny atributtes waiting for it.| |[deleteAllObjects](#eavservicedeleteallobjects)|Removes all object entities from the database (should obviusly not be used in production).| - - - -### EavService::__construct +### EavService::\_\_construct **Description** @@ -26,10 +17,6 @@ __construct (void) ``` - - - - **Parameters** `This function has no parameters.` @@ -38,11 +25,9 @@ `void` -
- -### EavService::checkAttributeforEntity +### EavService::checkAttributeforEntity **Description** @@ -50,25 +35,19 @@ public checkAttributeforEntity (\Attribute $attribute) ``` -Checks an atribute to see if a schema for its reference has becomme available. - - +Checks an atribute to see if a schema for its reference has becomme available. **Parameters** -* `(\Attribute) $attribute` +* `(\Attribute) $attribute` **Return Values** `\Attribute` - - -
- -### EavService::checkEntityforAttribute +### EavService::checkEntityforAttribute **Description** @@ -76,25 +55,19 @@ Checks an atribute to see if a schema for its reference has becomme available. public checkEntityforAttribute (\Entity $entity) ``` -Checks an entity to see if there are anny atributtes waiting for it. - - +Checks an entity to see if there are anny atributtes waiting for it. **Parameters** -* `(\Entity) $entity` +* `(\Entity) $entity` **Return Values** `\Entity` - - -
- -### EavService::deleteAllObjects +### EavService::deleteAllObjects **Description** @@ -102,14 +75,12 @@ Checks an entity to see if there are anny atributtes waiting for it. public deleteAllObjects (\Entity|null $entity) ``` -Removes all object entities from the database (should obviusly not be used in production). - - +Removes all object entities from the database (should obviusly not be used in production). **Parameters** -* `(\Entity|null) $entity` -: An optionall entity to remove all the objects from +* `(\Entity|null) $entity` + : An optionall entity to remove all the objects from **Return Values** @@ -117,6 +88,4 @@ Removes all object entities from the database (should obviusly not be used in pr > True is succesfull or false otherwise -
- diff --git a/docs/classes/Service/FileService.md b/docs/classes/Service/FileService.md index 009f335c..34c173e3 100644 --- a/docs/classes/Service/FileService.md +++ b/docs/classes/Service/FileService.md @@ -1,10 +1,4 @@ -# CommonGateway\CoreBundle\Service\FileService - - - - - - +# CommonGateway\CoreBundle\Service\FileService ## Methods @@ -13,10 +7,7 @@ |[removeFile](#fileserviceremovefile)|| |[writeFile](#fileservicewritefile)|| - - - -### FileService::removeFile +### FileService::removeFile **Description** @@ -24,10 +15,6 @@ removeFile (void) ``` - - - - **Parameters** `This function has no parameters.` @@ -36,11 +23,9 @@ `void` -
- -### FileService::writeFile +### FileService::writeFile **Description** @@ -48,10 +33,6 @@ writeFile (void) ``` - - - - **Parameters** `This function has no parameters.` @@ -60,6 +41,4 @@ `void` -
- diff --git a/docs/classes/Service/InstallationService.md b/docs/classes/Service/InstallationService.md index 02551adc..35eb0be2 100644 --- a/docs/classes/Service/InstallationService.md +++ b/docs/classes/Service/InstallationService.md @@ -1,27 +1,20 @@ -# CommonGateway\CoreBundle\Service\InstallationService +# CommonGateway\CoreBundle\Service\InstallationService The installation service is used to install plugins (or actually symfony bundles) on the gateway. -This class breaks complexity, methods and coupling rules. This could be solved by deviding the class into smaller classes but that would deminisch the readability of the code as a whole. All the code in this class is only used in an installation context, and it makes more sense to keep it together. Therefore, a design decision was made to keep al this code in one class. - - - - +This class breaks complexity, methods and coupling rules. This could be solved by deviding the class into smaller classes but that would deminisch the readability of the code as a whole. All the code in this class is only used in an installation context, and it makes more sense to keep it together. Therefore, a design decision was made to keep al this code in one class. ## Methods | Name | Description | |------|-------------| -|[__construct](#installationservice__construct)|| +|[\_\_construct](#installationservice__construct)|| |[addActionConfiguration](#installationserviceaddactionconfiguration)|This function creates default configuration for the action.| |[install](#installationserviceinstall)|Installs the files from a bundle.| |[overrideConfig](#installationserviceoverrideconfig)|Overrides the default configuration of an Action. Will also set entity and source to id if a reference is given.| |[update](#installationserviceupdate)|Updates all commonground bundles on the common gateway installation.| - - - -### InstallationService::__construct +### InstallationService::\_\_construct **Description** @@ -29,10 +22,6 @@ This class breaks complexity, methods and coupling rules. This could be solved b __construct (void) ``` - - - - **Parameters** `This function has no parameters.` @@ -41,11 +30,9 @@ This class breaks complexity, methods and coupling rules. This could be solved b `void` -
- -### InstallationService::addActionConfiguration +### InstallationService::addActionConfiguration **Description** @@ -53,26 +40,20 @@ This class breaks complexity, methods and coupling rules. This could be solved b public addActionConfiguration (mixed $actionHandler) ``` -This function creates default configuration for the action. - - +This function creates default configuration for the action. **Parameters** -* `(mixed) $actionHandler` -: The actionHandler for witch the default configuration is set. +* `(mixed) $actionHandler` + : The actionHandler for witch the default configuration is set. **Return Values** `array` - - -
- -### InstallationService::install +### InstallationService::install **Description** @@ -80,16 +61,16 @@ This function creates default configuration for the action. public install (string $bundle, array $config) ``` -Installs the files from a bundle. +Installs the files from a bundle. -Based on the default action handler so schould supoprt a config parrameter even if we do not use it +Based on the default action handler so schould supoprt a config parrameter even if we do not use it **Parameters** -* `(string) $bundle` -: The bundle. -* `(array) $config` -: Optional config. +* `(string) $bundle` + : The bundle. +* `(array) $config` + : Optional config. **Return Values** @@ -97,17 +78,13 @@ Based on the default action handler so schould supoprt a config parrameter even > The result of the installation. - **Throws Exceptions** - `\Exception` -
- -### InstallationService::overrideConfig +### InstallationService::overrideConfig **Description** @@ -115,26 +92,20 @@ Based on the default action handler so schould supoprt a config parrameter even public overrideConfig (array $defaultConfig, array $overrides) ``` -Overrides the default configuration of an Action. Will also set entity and source to id if a reference is given. - - +Overrides the default configuration of an Action. Will also set entity and source to id if a reference is given. **Parameters** -* `(array) $defaultConfig` -* `(array) $overrides` +* `(array) $defaultConfig` +* `(array) $overrides` **Return Values** `array` - - -
- -### InstallationService::update +### InstallationService::update **Description** @@ -142,27 +113,21 @@ Overrides the default configuration of an Action. Will also set entity and sourc public update (array $config) ``` -Updates all commonground bundles on the common gateway installation. +Updates all commonground bundles on the common gateway installation. -This functions serves as the jump of point for the `commengateway:plugins:update` command +This functions serves as the jump of point for the `commengateway:plugins:update` command **Parameters** -* `(array) $config` -: The (optional) configuration +* `(array) $config` + : The (optional) configuration **Return Values** `int` - - - **Throws Exceptions** - `\Exception` -
- diff --git a/docs/classes/Service/RequestService.md b/docs/classes/Service/RequestService.md index f85720d3..dadfb09d 100644 --- a/docs/classes/Service/RequestService.md +++ b/docs/classes/Service/RequestService.md @@ -1,16 +1,12 @@ -# CommonGateway\CoreBundle\Service\RequestService +# CommonGateway\CoreBundle\Service\RequestService Handles incomming request from endpoints or controllers that relate to the gateways object structure (eav). - - - - ## Methods | Name | Description | |------|-------------| -|[__construct](#requestservice__construct)|| +|[\_\_construct](#requestservice__construct)|| |[checkEmbedded](#requestservicecheckembedded)|If embedded should be shown or not.| |[createResponse](#requestservicecreateresponse)|Creating the response object.| |[getId](#requestservicegetid)|Get the ID from given parameters.| @@ -24,10 +20,7 @@ Handles incomming request from endpoints or controllers that relate to the gatew |[searchRequestHandler](#requestservicesearchrequesthandler)|This function searches all the objectEntities and formats the data.| |[shouldWeUnsetEmbedded](#requestserviceshouldweunsetembedded)|If embedded should be shown or not.| - - - -### RequestService::__construct +### RequestService::\_\_construct **Description** @@ -35,10 +28,6 @@ Handles incomming request from endpoints or controllers that relate to the gatew __construct (void) ``` - - - - **Parameters** `This function has no parameters.` @@ -47,11 +36,9 @@ Handles incomming request from endpoints or controllers that relate to the gatew `void` -
- -### RequestService::checkEmbedded +### RequestService::checkEmbedded **Description** @@ -59,26 +46,20 @@ Handles incomming request from endpoints or controllers that relate to the gatew public checkEmbedded (object|array $result) ``` -If embedded should be shown or not. - - +If embedded should be shown or not. **Parameters** -* `(object|array) $result` -: fetched result +* `(object|array) $result` + : fetched result **Return Values** `array|null` - - -
- -### RequestService::createResponse +### RequestService::createResponse **Description** @@ -86,25 +67,19 @@ If embedded should be shown or not. public createResponse ( $data) ``` -Creating the response object. - - +Creating the response object. **Parameters** -* `() $data` +* `() $data` **Return Values** `\CommonGateway\CoreBundle\Service\Response` - - -
- -### RequestService::getId +### RequestService::getId **Description** @@ -112,25 +87,19 @@ Creating the response object. public getId (array $object) ``` -Get the ID from given parameters. - - +Get the ID from given parameters. **Parameters** -* `(array) $object` +* `(array) $object` **Return Values** `string|false` - - -
- -### RequestService::getSchema +### RequestService::getSchema **Description** @@ -138,25 +107,19 @@ Get the ID from given parameters. public getSchema (array $parameters) ``` -Get the schema from given parameters returns false if no schema could be established. - - +Get the schema from given parameters returns false if no schema could be established. **Parameters** -* `(array) $parameters` +* `(array) $parameters` **Return Values** `\Entity|false` - - -
- -### RequestService::getScopes +### RequestService::getScopes **Description** @@ -164,9 +127,7 @@ Get the schema from given parameters returns false if no schema could be establi public getScopes (void) ``` -Get a scopes array for the current user (or of the anonymus if no user s logged in). - - +Get a scopes array for the current user (or of the anonymus if no user s logged in). **Parameters** @@ -176,13 +137,9 @@ Get a scopes array for the current user (or of the anonymus if no user s logged `array` - - -
- -### RequestService::itemRequestHandler +### RequestService::itemRequestHandler **Description** @@ -190,10 +147,6 @@ Get a scopes array for the current user (or of the anonymus if no user s logged itemRequestHandler (void) ``` - - - - **Parameters** `This function has no parameters.` @@ -202,11 +155,9 @@ Get a scopes array for the current user (or of the anonymus if no user s logged `void` -
- -### RequestService::proxyHandler +### RequestService::proxyHandler **Description** @@ -214,10 +165,6 @@ Get a scopes array for the current user (or of the anonymus if no user s logged proxyHandler (void) ``` - - - - **Parameters** `This function has no parameters.` @@ -226,11 +173,9 @@ Get a scopes array for the current user (or of the anonymus if no user s logged `void` -
- -### RequestService::proxyRequestHandler +### RequestService::proxyRequestHandler **Description** @@ -238,16 +183,14 @@ Get a scopes array for the current user (or of the anonymus if no user s logged public proxyRequestHandler (array $parameters, array $configuration) ``` -Determines the proxy source from configuration, then use proxy handler to proxy the request. - - +Determines the proxy source from configuration, then use proxy handler to proxy the request. **Parameters** -* `(array) $parameters` -: The parameters of the request. -* `(array) $configuration` -: The configuration of the action. +* `(array) $parameters` + : The parameters of the request. +* `(array) $configuration` + : The configuration of the action. **Return Values** @@ -255,11 +198,9 @@ Determines the proxy source from configuration, then use proxy handler to proxy > The result of the proxy. -
- -### RequestService::realRequestQueryAll +### RequestService::realRequestQueryAll **Description** @@ -267,16 +208,16 @@ Determines the proxy source from configuration, then use proxy handler to proxy public realRequestQueryAll (string $method, string|null $queryString) ``` -A function to replace Request->query->all() because Request->query->all() will replace some characters with an underscore. +A function to replace Request->query->all() because Request->query->all() will replace some characters with an underscore. -This function will not. +This function will not. **Parameters** -* `(string) $method` -: The method of the Request -* `(string|null) $queryString` -: A queryString from a request if we want to give it to this function instead of using global var $_SERVER. +* `(string) $method` + : The method of the Request +* `(string|null) $queryString` + : A queryString from a request if we want to give it to this function instead of using global var $\_SERVER. **Return Values** @@ -284,11 +225,9 @@ This function will not. > An array with all query parameters. -
- -### RequestService::requestHandler +### RequestService::requestHandler **Description** @@ -296,16 +235,14 @@ This function will not. public requestHandler (array $data, array $configuration) ``` -Handles incomming requests and is responsible for generating a response. - - +Handles incomming requests and is responsible for generating a response. **Parameters** -* `(array) $data` -: The data from the call -* `(array) $configuration` -: The configuration from the call +* `(array) $data` + : The data from the call +* `(array) $configuration` + : The configuration from the call **Return Values** @@ -313,11 +250,9 @@ Handles incomming requests and is responsible for generating a response. > The modified data -
- -### RequestService::searchRequestHandler +### RequestService::searchRequestHandler **Description** @@ -325,16 +260,14 @@ Handles incomming requests and is responsible for generating a response. public searchRequestHandler (array $data, array $configuration) ``` -This function searches all the objectEntities and formats the data. - - +This function searches all the objectEntities and formats the data. **Parameters** -* `(array) $data` -: The data from the call -* `(array) $configuration` -: The configuration from the call +* `(array) $data` + : The data from the call +* `(array) $configuration` + : The configuration from the call **Return Values** @@ -342,11 +275,9 @@ This function searches all the objectEntities and formats the data. > The modified data -
- -### RequestService::shouldWeUnsetEmbedded +### RequestService::shouldWeUnsetEmbedded **Description** @@ -354,23 +285,17 @@ This function searches all the objectEntities and formats the data. public shouldWeUnsetEmbedded (object|array $result, array $embeddedConfig) ``` -If embedded should be shown or not. - - +If embedded should be shown or not. **Parameters** -* `(object|array) $result` -: fetched result -* `(array) $embeddedConfig` -: Application configuration ['embedded'] +* `(object|array) $result` + : fetched result +* `(array) $embeddedConfig` + : Application configuration \['embedded'] **Return Values** `array|null` - - -
- From b94d1d82275ae3c6eaaf55c7c7b6a5acb5a266fa Mon Sep 17 00:00:00 2001 From: Ruben van der Linde Date: Fri, 24 Mar 2023 10:17:40 +0100 Subject: [PATCH 6/7] config update --- .phpcs.xml => phpcs.xml | 10 +--------- phpmd.xml | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+), 9 deletions(-) rename .phpcs.xml => phpcs.xml (95%) create mode 100644 phpmd.xml diff --git a/.phpcs.xml b/phpcs.xml similarity index 95% rename from .phpcs.xml rename to phpcs.xml index d1faa5c7..c45e7e7d 100644 --- a/.phpcs.xml +++ b/phpcs.xml @@ -3,10 +3,7 @@ The coding standard for PHP_CodeSniffer itself, for more config -> for https://github.com/squizlabs/PHP_CodeSniffer/wiki/Configuration-Options. README.md - LICENSE.md - CoreBundle.php src - DependencyInjection @@ -112,12 +109,7 @@
- - - - - - + diff --git a/phpmd.xml b/phpmd.xml new file mode 100644 index 00000000..8263ac35 --- /dev/null +++ b/phpmd.xml @@ -0,0 +1,19 @@ + + + + My custom rule set that checks my code... + + + + + + + + + \ No newline at end of file From adeff094ac509f73825bde9a8ba97e0b40d00819 Mon Sep 17 00:00:00 2001 From: GitHub Actions <> Date: Fri, 24 Mar 2023 09:18:11 +0000 Subject: [PATCH 7/7] Update src from PHP Codesniffer --- src/Service/CacheService.php | 6 +++--- src/Service/CallService.php | 12 ++++++------ src/Service/EndpointService.php | 2 +- src/Service/InstallationService.php | 6 +++--- src/Service/RequestService.php | 6 +++--- 5 files changed, 16 insertions(+), 16 deletions(-) diff --git a/src/Service/CacheService.php b/src/Service/CacheService.php index 47ef37c9..9369cfe9 100644 --- a/src/Service/CacheService.php +++ b/src/Service/CacheService.php @@ -407,7 +407,7 @@ public function searchObjects(string $search=null, array $filter=[], array $enti $this->setPagination($limit, $start, $completeFilter); // Order - $order = isset($completeFilter['_order']) ? str_replace(['ASC', 'asc', 'DESC', 'desc'], [1, 1, -1, -1], $completeFilter['_order']) : []; + $order = isset($completeFilter['_order']) ? str_replace(['ASC', 'asc', 'DESC', 'desc'], [1, 1, -1, -1], $completeFilter['_order']) : []; !empty($order) && $order[array_keys($order)[0]] = (int) $order[array_keys($order)[0]]; // Find / Search @@ -953,7 +953,7 @@ public function getEndpoints(array $filter): ?Endpoint $collection = $this->client->endpoints->json; if (isset($filter['path'])) { - $path = $filter['path']; + $path = $filter['path']; $filter['$where'] = "\"$path\".match(this.pathRegex)"; unset($filter['path']); } @@ -998,7 +998,7 @@ public function cacheShema(Entity $entity): Entity $collection = $this->client->schemas->json; // Remap the array - $array = $entity->toSchema(null); + $array = $entity->toSchema(null); $array['reference'] = $array['$id']; $array['schema'] = $array['$schema']; unset($array['$id']); diff --git a/src/Service/CallService.php b/src/Service/CallService.php index e24c76d1..df81acd5 100644 --- a/src/Service/CallService.php +++ b/src/Service/CallService.php @@ -63,12 +63,12 @@ public function __construct( LoggerInterface $callLogger ) { $this->authenticationService = $authenticationService; - $this->client = new Client([]); - $this->entityManager = $entityManager; - $this->fileService = $fileService; - $this->mappingService = $mappingService; - $this->session = $session; - $this->logger = $callLogger; + $this->client = new Client([]); + $this->entityManager = $entityManager; + $this->fileService = $fileService; + $this->mappingService = $mappingService; + $this->session = $session; + $this->logger = $callLogger; }//end __construct() diff --git a/src/Service/EndpointService.php b/src/Service/EndpointService.php index f27905e8..6ef67ef2 100644 --- a/src/Service/EndpointService.php +++ b/src/Service/EndpointService.php @@ -112,7 +112,7 @@ public function handleRequest(Request $request): Response // Get the parameters. $this->logger->debug('Determine parameters for request'); - $parameters = $this->getParametersFromRequest(); + $parameters = $this->getParametersFromRequest(); $parameters['endpoint'] = $endpoint; $parameters['accept'] = $accept; $parameters['body'] = $this->decodeBody(); diff --git a/src/Service/InstallationService.php b/src/Service/InstallationService.php index b1f9d6bf..5477298b 100644 --- a/src/Service/InstallationService.php +++ b/src/Service/InstallationService.php @@ -1133,10 +1133,10 @@ private function handleSubSchemaEndpoints(array $baseEndpointData, array $subSch continue; } - $path = $subSchemaEndpoint->getPath(); + $path = $subSchemaEndpoint->getPath(); $path[array_search('id', $path)] = '{'.strtolower($entity->getName()).'._self.id}'; - $path[] = $subSchemaEndpointData['path']; - $path[] = '{id}'; + $path[] = $subSchemaEndpointData['path']; + $path[] = '{id}'; $subSchemaEndpoint->setPath($path); $pathRegex = rtrim($subSchemaEndpoint->getPathRegex(), '$'); diff --git a/src/Service/RequestService.php b/src/Service/RequestService.php index 36089f24..ae554ff1 100644 --- a/src/Service/RequestService.php +++ b/src/Service/RequestService.php @@ -106,8 +106,8 @@ public function __construct( $this->security = $security; $this->eventDispatcher = $eventDispatcher; $this->serializer = $serializer; - $this->session = $session; - $this->logger = $requestLogger; + $this->session = $session; + $this->logger = $requestLogger; }//end __construct() @@ -830,7 +830,7 @@ function (&$record) { } $this->responseService->xCommongatewayMetadata = $metadataSelf; - $resultMetadataSelf = (array) $result['_self']; + $resultMetadataSelf = (array) $result['_self']; $this->responseService->addToMetadata($resultMetadataSelf, 'dateRead', $objectEntity); $result['_self'] = $resultMetadataSelf;