From 3921d659837ee6172894f7f85e486be69eb721af Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Tue, 19 Sep 2023 18:51:55 +0200 Subject: [PATCH 01/13] test with symfony 7 and php 8.3 --- .github/workflows/test-application.yaml | 4 ++-- CHANGELOG.md | 10 ++++++++++ composer.json | 2 +- src/PHPCR/Util/Console/Command/NodeDumpCommand.php | 11 ++--------- src/PHPCR/Util/Console/Command/NodeMoveCommand.php | 11 ++--------- src/PHPCR/Util/Console/Command/NodeRemoveCommand.php | 11 ++--------- src/PHPCR/Util/Console/Command/NodeTouchCommand.php | 11 ++--------- .../Util/Console/Command/NodeTypeListCommand.php | 10 ++-------- .../Util/Console/Command/NodeTypeRegisterCommand.php | 9 ++------- src/PHPCR/Util/Console/Command/NodesUpdateCommand.php | 11 ++--------- .../Util/Console/Command/WorkspaceCreateCommand.php | 10 ++-------- .../Util/Console/Command/WorkspaceDeleteCommand.php | 10 ++-------- .../Util/Console/Command/WorkspaceExportCommand.php | 10 ++-------- .../Util/Console/Command/WorkspaceImportCommand.php | 10 ++-------- .../Util/Console/Command/WorkspaceListCommand.php | 10 ++-------- .../Util/Console/Command/WorkspacePurgeCommand.php | 10 ++-------- .../Util/Console/Command/WorkspaceQueryCommand.php | 10 ++-------- .../Util/Console/Helper/PhpcrConsoleDumperHelper.php | 5 +---- src/PHPCR/Util/Console/Helper/PhpcrHelper.php | 5 +---- 19 files changed, 43 insertions(+), 127 deletions(-) diff --git a/.github/workflows/test-application.yaml b/.github/workflows/test-application.yaml index 9e15c895..a4226ab4 100644 --- a/.github/workflows/test-application.yaml +++ b/.github/workflows/test-application.yaml @@ -22,10 +22,10 @@ jobs: - php-version: '7.3' - php-version: '7.4' - php-version: '8.0' - - php-version: '8.0' - dev-dependencies: true - php-version: '8.1' - php-version: '8.2' + - php-version: '8.3' + - php-version: '8.3' steps: - name: Checkout project diff --git a/CHANGELOG.md b/CHANGELOG.md index b85a5882..53f113a6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,16 @@ Changelog ========= +2.x +--- + +2.0.0 (unreleased) +------------------ + +* Support Symfony 7 +* Test with PHP 8.3 +* Adjusted commands to have the return type declarations. + 1.x --- diff --git a/composer.json b/composer.json index 655bd180..e4e125dc 100644 --- a/composer.json +++ b/composer.json @@ -29,7 +29,7 @@ "require": { "php": "^7.2 || ^8.0", "phpcr/phpcr": "~2.1.0", - "symfony/console": "^2.3 || ^3.0 || ^4.0 || ^5.0 || ^6.0" + "symfony/console": "^2.3 || ^3.0 || ^4.0 || ^5.0 || ^6.0 || ^7.0" }, "require-dev": { "ramsey/uuid": "^3.5", diff --git a/src/PHPCR/Util/Console/Command/NodeDumpCommand.php b/src/PHPCR/Util/Console/Command/NodeDumpCommand.php index 10cdf181..dcfbd686 100644 --- a/src/PHPCR/Util/Console/Command/NodeDumpCommand.php +++ b/src/PHPCR/Util/Console/Command/NodeDumpCommand.php @@ -23,12 +23,7 @@ */ class NodeDumpCommand extends BaseCommand { - /** - * {@inheritdoc} - * - * @throws InvalidArgumentException - */ - protected function configure() + protected function configure(): void { $this ->setName('phpcr:node:dump') @@ -56,13 +51,11 @@ protected function configure() } /** - * {@inheritdoc} - * * @throws InvalidArgumentException * @throws Exception * @throws RepositoryException */ - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { $session = $this->getPhpcrSession(); $dumperHelper = $this->getPhpcrConsoleDumperHelper(); diff --git a/src/PHPCR/Util/Console/Command/NodeMoveCommand.php b/src/PHPCR/Util/Console/Command/NodeMoveCommand.php index d0f3fd4a..2eef8c19 100644 --- a/src/PHPCR/Util/Console/Command/NodeMoveCommand.php +++ b/src/PHPCR/Util/Console/Command/NodeMoveCommand.php @@ -17,12 +17,7 @@ */ class NodeMoveCommand extends BaseCommand { - /** - * {@inheritdoc} - * - * @throws InvalidArgumentException - */ - protected function configure() + protected function configure(): void { $this ->setName('phpcr:node:move') @@ -43,11 +38,9 @@ protected function configure() } /** - * {@inheritdoc} - * * @throws InvalidArgumentException */ - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { $session = $this->getPhpcrSession(); diff --git a/src/PHPCR/Util/Console/Command/NodeRemoveCommand.php b/src/PHPCR/Util/Console/Command/NodeRemoveCommand.php index 280fb5a7..0ee74319 100644 --- a/src/PHPCR/Util/Console/Command/NodeRemoveCommand.php +++ b/src/PHPCR/Util/Console/Command/NodeRemoveCommand.php @@ -21,12 +21,7 @@ */ class NodeRemoveCommand extends BaseCommand { - /** - * {@inheritdoc} - * - * @throws CliInvalidArgumentException - */ - protected function configure() + protected function configure(): void { parent::configure(); @@ -53,12 +48,10 @@ protected function configure() } /** - * {@inheritdoc} - * * @throws CliInvalidArgumentException * @throws InvalidArgumentException */ - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { $session = $this->getPhpcrSession(); diff --git a/src/PHPCR/Util/Console/Command/NodeTouchCommand.php b/src/PHPCR/Util/Console/Command/NodeTouchCommand.php index 7ca3f0e8..e3cd0f45 100644 --- a/src/PHPCR/Util/Console/Command/NodeTouchCommand.php +++ b/src/PHPCR/Util/Console/Command/NodeTouchCommand.php @@ -21,12 +21,7 @@ */ class NodeTouchCommand extends BaseNodeManipulationCommand { - /** - * {@inheritdoc} - * - * @throws InvalidArgumentException - */ - protected function configure() + protected function configure(): void { parent::configure(); @@ -73,11 +68,9 @@ protected function configure() } /** - * {@inheritdoc} - * * @throws InvalidArgumentException */ - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { $helper = $this->getPhpcrHelper(); $session = $this->getPhpcrSession(); diff --git a/src/PHPCR/Util/Console/Command/NodeTypeListCommand.php b/src/PHPCR/Util/Console/Command/NodeTypeListCommand.php index 2f95fa56..557e6fa7 100644 --- a/src/PHPCR/Util/Console/Command/NodeTypeListCommand.php +++ b/src/PHPCR/Util/Console/Command/NodeTypeListCommand.php @@ -15,10 +15,7 @@ */ class NodeTypeListCommand extends BaseCommand { - /** - * {@inheritdoc} - */ - protected function configure() + protected function configure(): void { $this ->setName('phpcr:node-type:list') @@ -31,10 +28,7 @@ protected function configure() ); } - /** - * {@inheritdoc} - */ - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { $session = $this->getPhpcrSession(); $ntm = $session->getWorkspace()->getNodeTypeManager(); diff --git a/src/PHPCR/Util/Console/Command/NodeTypeRegisterCommand.php b/src/PHPCR/Util/Console/Command/NodeTypeRegisterCommand.php index 9cf78edd..0534b2cc 100644 --- a/src/PHPCR/Util/Console/Command/NodeTypeRegisterCommand.php +++ b/src/PHPCR/Util/Console/Command/NodeTypeRegisterCommand.php @@ -26,10 +26,7 @@ */ class NodeTypeRegisterCommand extends BaseCommand { - /** - * {@inheritdoc} - */ - protected function configure() + protected function configure(): void { $this ->setName('phpcr:node-type:register') @@ -62,11 +59,9 @@ protected function configure() } /** - * {@inheritdoc} - * * @throws InvalidArgumentException */ - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { $definitions = $input->getArgument('cnd-file'); diff --git a/src/PHPCR/Util/Console/Command/NodesUpdateCommand.php b/src/PHPCR/Util/Console/Command/NodesUpdateCommand.php index 50aa22d0..6e29b1dd 100644 --- a/src/PHPCR/Util/Console/Command/NodesUpdateCommand.php +++ b/src/PHPCR/Util/Console/Command/NodesUpdateCommand.php @@ -20,12 +20,7 @@ */ class NodesUpdateCommand extends BaseNodeManipulationCommand { - /** - * {@inheritdoc} - * - * @throws CliInvalidArgumentException - */ - protected function configure() + protected function configure(): void { parent::configure(); @@ -85,12 +80,10 @@ protected function configure() } /** - * {@inheritdoc} - * * @throws CliInvalidArgumentException * @throws InvalidArgumentException */ - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { $query = $input->getOption('query'); $queryLanguage = strtoupper($input->getOption('query-language')); diff --git a/src/PHPCR/Util/Console/Command/WorkspaceCreateCommand.php b/src/PHPCR/Util/Console/Command/WorkspaceCreateCommand.php index c0ac8a6e..b9c14012 100644 --- a/src/PHPCR/Util/Console/Command/WorkspaceCreateCommand.php +++ b/src/PHPCR/Util/Console/Command/WorkspaceCreateCommand.php @@ -18,10 +18,7 @@ */ class WorkspaceCreateCommand extends BaseCommand { - /** - * {@inheritdoc} - */ - protected function configure() + protected function configure(): void { $this ->setName('phpcr:workspace:create') @@ -42,10 +39,7 @@ protected function configure() ); } - /** - * {@inheritdoc} - */ - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { $session = $this->getPhpcrSession(); diff --git a/src/PHPCR/Util/Console/Command/WorkspaceDeleteCommand.php b/src/PHPCR/Util/Console/Command/WorkspaceDeleteCommand.php index 9200fe66..fd63d406 100644 --- a/src/PHPCR/Util/Console/Command/WorkspaceDeleteCommand.php +++ b/src/PHPCR/Util/Console/Command/WorkspaceDeleteCommand.php @@ -17,10 +17,7 @@ */ class WorkspaceDeleteCommand extends BaseCommand { - /** - * {@inheritdoc} - */ - protected function configure() + protected function configure(): void { $this ->setName('phpcr:workspace:delete') @@ -37,10 +34,7 @@ protected function configure() ); } - /** - * {@inheritdoc} - */ - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { $session = $this->getPhpcrSession(); diff --git a/src/PHPCR/Util/Console/Command/WorkspaceExportCommand.php b/src/PHPCR/Util/Console/Command/WorkspaceExportCommand.php index 5708e79b..c8e0f7b3 100644 --- a/src/PHPCR/Util/Console/Command/WorkspaceExportCommand.php +++ b/src/PHPCR/Util/Console/Command/WorkspaceExportCommand.php @@ -17,10 +17,7 @@ */ class WorkspaceExportCommand extends BaseCommand { - /** - * {@inheritdoc} - */ - protected function configure() + protected function configure(): void { parent::configure(); @@ -42,10 +39,7 @@ protected function configure() ); } - /** - * {@inheritdoc} - */ - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { $session = $this->getPhpcrSession(); $repo = $session->getRepository(); diff --git a/src/PHPCR/Util/Console/Command/WorkspaceImportCommand.php b/src/PHPCR/Util/Console/Command/WorkspaceImportCommand.php index 4b6578db..1641d7f5 100644 --- a/src/PHPCR/Util/Console/Command/WorkspaceImportCommand.php +++ b/src/PHPCR/Util/Console/Command/WorkspaceImportCommand.php @@ -24,10 +24,7 @@ class WorkspaceImportCommand extends BaseCommand 'throw' => ImportUUIDBehaviorInterface::IMPORT_UUID_COLLISION_THROW, ]; - /** - * {@inheritdoc} - */ - protected function configure() + protected function configure(): void { parent::configure(); @@ -62,10 +59,7 @@ protected function configure() ); } - /** - * {@inheritdoc} - */ - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { $filename = $input->getArgument('filename'); $parentPath = $input->getOption('parentpath'); diff --git a/src/PHPCR/Util/Console/Command/WorkspaceListCommand.php b/src/PHPCR/Util/Console/Command/WorkspaceListCommand.php index 3165f8b9..4210891c 100644 --- a/src/PHPCR/Util/Console/Command/WorkspaceListCommand.php +++ b/src/PHPCR/Util/Console/Command/WorkspaceListCommand.php @@ -14,10 +14,7 @@ */ class WorkspaceListCommand extends BaseCommand { - /** - * {@inheritdoc} - */ - protected function configure() + protected function configure(): void { $this ->setName('phpcr:workspace:list') @@ -29,10 +26,7 @@ protected function configure() ); } - /** - * {@inheritdoc} - */ - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { $session = $this->getPhpcrSession(); diff --git a/src/PHPCR/Util/Console/Command/WorkspacePurgeCommand.php b/src/PHPCR/Util/Console/Command/WorkspacePurgeCommand.php index c8c8f81a..c33baa92 100644 --- a/src/PHPCR/Util/Console/Command/WorkspacePurgeCommand.php +++ b/src/PHPCR/Util/Console/Command/WorkspacePurgeCommand.php @@ -17,10 +17,7 @@ */ class WorkspacePurgeCommand extends BaseCommand { - /** - * {@inheritdoc} - */ - protected function configure() + protected function configure(): void { parent::configure(); @@ -36,10 +33,7 @@ protected function configure() ); } - /** - * {@inheritdoc} - */ - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { $session = $this->getPhpcrSession(); $force = $input->getOption('force'); diff --git a/src/PHPCR/Util/Console/Command/WorkspaceQueryCommand.php b/src/PHPCR/Util/Console/Command/WorkspaceQueryCommand.php index f4d7fc15..d7015fff 100644 --- a/src/PHPCR/Util/Console/Command/WorkspaceQueryCommand.php +++ b/src/PHPCR/Util/Console/Command/WorkspaceQueryCommand.php @@ -18,10 +18,7 @@ */ class WorkspaceQueryCommand extends BaseCommand { - /** - * {@inheritdoc} - */ - protected function configure() + protected function configure(): void { parent::configure(); @@ -34,10 +31,7 @@ protected function configure() ->setHelp('The query command executes a JCR query statement on the content repository'); } - /** - * {@inheritdoc} - */ - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { $sql = $input->getArgument('query'); $language = $input->getOption('language'); diff --git a/src/PHPCR/Util/Console/Helper/PhpcrConsoleDumperHelper.php b/src/PHPCR/Util/Console/Helper/PhpcrConsoleDumperHelper.php index d7d3cdbd..04c35226 100644 --- a/src/PHPCR/Util/Console/Helper/PhpcrConsoleDumperHelper.php +++ b/src/PHPCR/Util/Console/Helper/PhpcrConsoleDumperHelper.php @@ -43,10 +43,7 @@ public function getTreeWalker(OutputInterface $output, $options) return $treeWalker; } - /** - * {@inheritdoc} - */ - public function getName() + public function getName(): string { return 'phpcr_console_dumper'; } diff --git a/src/PHPCR/Util/Console/Helper/PhpcrHelper.php b/src/PHPCR/Util/Console/Helper/PhpcrHelper.php index edb6edc4..8e044dd5 100644 --- a/src/PHPCR/Util/Console/Helper/PhpcrHelper.php +++ b/src/PHPCR/Util/Console/Helper/PhpcrHelper.php @@ -44,10 +44,7 @@ public function getSession() return $this->session; } - /** - * {@inheritdoc} - */ - public function getName() + public function getName(): string { return 'phpcr'; } From 6399c4e2306e6596af760751649070335f191c25 Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Tue, 28 Nov 2023 08:19:14 +0100 Subject: [PATCH 02/13] use php-cs-fixer --- .github/workflows/static.yml | 13 ++ .gitignore | 4 +- .php-cs-fixer.dist.php | 18 +++ .styleci.yml | 6 - composer.json | 3 +- .../Util/CND/Exception/ParserException.php | 2 +- src/PHPCR/Util/CND/Parser/AbstractParser.php | 13 +- src/PHPCR/Util/CND/Parser/CndParser.php | 55 +++---- src/PHPCR/Util/CND/Reader/BufferReader.php | 9 +- .../Util/CND/Scanner/AbstractScanner.php | 2 - .../CND/Scanner/Context/ScannerContext.php | 3 - src/PHPCR/Util/CND/Scanner/GenericScanner.php | 36 ++--- src/PHPCR/Util/CND/Scanner/GenericToken.php | 16 +- .../Scanner/TokenFilter/TokenFilterChain.php | 4 +- .../TokenFilter/TokenFilterInterface.php | 4 +- .../Scanner/TokenFilter/TokenTypeFilter.php | 4 +- src/PHPCR/Util/CND/Scanner/TokenQueue.php | 4 +- src/PHPCR/Util/CND/Writer/CndWriter.php | 2 +- .../Util/Console/Command/BaseCommand.php | 12 +- .../Util/Console/Command/NodeDumpCommand.php | 5 +- .../Console/Command/NodeRemoveCommand.php | 5 +- .../Util/Console/Command/NodeTouchCommand.php | 8 +- .../Command/NodeTypeRegisterCommand.php | 23 ++- .../Console/Command/NodesUpdateCommand.php | 27 ++-- .../Command/WorkspaceExportCommand.php | 2 +- .../Command/WorkspaceImportCommand.php | 8 +- .../Helper/PhpcrConsoleDumperHelper.php | 6 +- src/PHPCR/Util/Console/Helper/PhpcrHelper.php | 23 ++- .../TreeDumper/ConsoleDumperItemVisitor.php | 2 - .../TreeDumper/ConsoleDumperNodeVisitor.php | 10 +- .../ConsoleDumperPropertyVisitor.php | 10 +- .../Helper/TreeDumper/SystemNodeFilter.php | 4 +- src/PHPCR/Util/NodeHelper.php | 55 +++---- src/PHPCR/Util/PathHelper.php | 50 +++--- .../Util/QOM/BaseQomToSqlQueryConverter.php | 37 +---- src/PHPCR/Util/QOM/BaseSqlGenerator.php | 25 +-- .../QOM/NotSupportedConstraintException.php | 4 +- .../Util/QOM/NotSupportedOperandException.php | 4 +- .../Util/QOM/QomToSql1QueryConverter.php | 25 ++- .../Util/QOM/QomToSql2QueryConverter.php | 43 ++--- src/PHPCR/Util/QOM/QueryBuilder.php | 150 ++++++++---------- src/PHPCR/Util/QOM/Sql1Generator.php | 12 +- src/PHPCR/Util/QOM/Sql2Generator.php | 17 +- src/PHPCR/Util/QOM/Sql2Scanner.php | 24 +-- .../Util/QOM/Sql2ToQomQueryConverter.php | 75 ++++----- src/PHPCR/Util/TraversingItemVisitor.php | 47 +++--- src/PHPCR/Util/TreeWalker.php | 15 +- src/PHPCR/Util/TreeWalkerFilterInterface.php | 4 - src/PHPCR/Util/UUIDHelper.php | 2 +- src/PHPCR/Util/ValueConverter.php | 36 +++-- tests/PHPCR/Tests/Stubs/MockNode.php | 3 +- .../PHPCR/Tests/Stubs/MockNodeTypeManager.php | 3 +- tests/PHPCR/Tests/Stubs/MockRow.php | 3 +- .../Util/CND/Reader/BufferReaderTest.php | 4 +- .../Tests/Util/CND/Reader/FileReaderTest.php | 13 +- .../Util/CND/Scanner/GenericScannerTest.php | 6 +- .../Tests/Util/CND/Scanner/TokenTest.php | 4 +- .../Util/Console/Command/BaseCommandTest.php | 2 +- .../Console/Command/NodeDumpCommandTest.php | 3 +- .../Console/Command/NodeRemoveCommandTest.php | 7 +- .../Console/Command/NodeTouchCommandTest.php | 13 +- .../Command/NodesUpdateCommandTest.php | 35 ++-- .../Command/WorkspaceCreateCommandTest.php | 2 +- .../Command/WorkspaceDeleteCommandTest.php | 4 +- .../Command/WorkspaceImportCommandTest.php | 2 +- .../Helper/PhpcrConsoleDumperHelperTest.php | 8 +- tests/PHPCR/Tests/Util/NodeHelperTest.php | 14 +- tests/PHPCR/Tests/Util/PathHelperTest.php | 5 +- .../PHPCR/Tests/Util/QOM/QueryBuilderTest.php | 6 +- .../Tests/Util/QOM/Sql1GeneratorTest.php | 3 +- .../Tests/Util/QOM/Sql2GeneratorTest.php | 3 +- .../PHPCR/Tests/Util/QOM/Sql2ScannerTest.php | 1 - tests/PHPCR/Tests/Util/ValueConverterTest.php | 30 ++-- tests/bootstrap.php | 2 +- 74 files changed, 484 insertions(+), 660 deletions(-) create mode 100644 .php-cs-fixer.dist.php delete mode 100644 .styleci.yml diff --git a/.github/workflows/static.yml b/.github/workflows/static.yml index 98bf6419..0f89ba68 100644 --- a/.github/workflows/static.yml +++ b/.github/workflows/static.yml @@ -40,3 +40,16 @@ jobs: uses: docker://oskarstark/phpstan-ga:1.8.0 with: args: analyze --no-progress -c phpstan.tests.neon.dist + + php-cs-fixer: + name: PHP-CS-Fixer + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v3 + + - name: PHP-CS-Fixer + uses: docker://oskarstark/php-cs-fixer-ga + with: + args: --dry-run --diff diff --git a/.gitignore b/.gitignore index bb6966fc..35e5af6d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,5 @@ cli-config.php - +.php-cs-fixer.cache vendor/ composer.phar -composer.lock \ No newline at end of file +composer.lock diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php new file mode 100644 index 00000000..92bc7484 --- /dev/null +++ b/.php-cs-fixer.dist.php @@ -0,0 +1,18 @@ +in(__DIR__.'/src') + ->in(__DIR__.'/tests') + ->name('*.php') +; + +$config = new PhpCsFixer\Config(); + +return $config + ->setRiskyAllowed(true) + ->setRules([ + '@Symfony' => true, + 'single_line_throw' => false, + ]) + ->setFinder($finder) +; diff --git a/.styleci.yml b/.styleci.yml deleted file mode 100644 index 5e45ebb5..00000000 --- a/.styleci.yml +++ /dev/null @@ -1,6 +0,0 @@ -preset: recommended - -enabled: - - no_useless_else -disabled: - - align_double_arrow diff --git a/composer.json b/composer.json index e4e125dc..d76537da 100644 --- a/composer.json +++ b/composer.json @@ -34,7 +34,8 @@ "require-dev": { "ramsey/uuid": "^3.5", "phpunit/phpunit": "^7.5 || ^8.0 || ^9.0", - "phpstan/phpstan": "^1.9" + "phpstan/phpstan": "^1.9", + "friendsofphp/php-cs-fixer": "^3.40" }, "suggest": { "ramsey/uuid": "A library for generating RFC 4122 version 1, 3, 4, and 5 universally unique identifiers (UUID)." diff --git a/src/PHPCR/Util/CND/Exception/ParserException.php b/src/PHPCR/Util/CND/Exception/ParserException.php index a08d67e4..5652ee1f 100644 --- a/src/PHPCR/Util/CND/Exception/ParserException.php +++ b/src/PHPCR/Util/CND/Exception/ParserException.php @@ -19,7 +19,7 @@ public function __construct(TokenQueue $queue, $msg) // construct a lookup of the next tokens $lookup = ''; - for ($i = 1; $i <= 5; $i++) { + for ($i = 1; $i <= 5; ++$i) { if ($queue->isEof()) { break; } diff --git a/src/PHPCR/Util/CND/Parser/AbstractParser.php b/src/PHPCR/Util/CND/Parser/AbstractParser.php index e01aae62..a7f3aba3 100644 --- a/src/PHPCR/Util/CND/Parser/AbstractParser.php +++ b/src/PHPCR/Util/CND/Parser/AbstractParser.php @@ -34,7 +34,7 @@ abstract class AbstractParser * Return false otherwise. * * @param int $type The expected token type - * @param null|string $data The expected data or null + * @param string|null $data The expected data or null * @param bool $ignoreCase whether to do string comparisons case insensitive or sensitive * * @return bool @@ -65,8 +65,7 @@ protected function checkToken($type, $data = null, $ignoreCase = false) /** * Check if the token data is one of the elements of the data array. * - * @param int $type - * @param array $data + * @param int $type * * @return bool */ @@ -86,11 +85,11 @@ protected function checkTokenIn($type, array $data, $ignoreCase = false) * otherwise throw an exception. * * @param int $type The expected token type - * @param null|string $data The expected token data or null - * - * @throws ParserException + * @param string|null $data The expected token data or null * * @return Token + * + * @throws ParserException */ protected function expectToken($type, $data = null) { @@ -110,7 +109,7 @@ protected function expectToken($type, $data = null) * return false. * * @param int $type The expected token type - * @param null|string $data The expected token data or null + * @param string|null $data The expected token data or null * * @return bool|Token */ diff --git a/src/PHPCR/Util/CND/Parser/CndParser.php b/src/PHPCR/Util/CND/Parser/CndParser.php index dab5dc9e..59249d78 100644 --- a/src/PHPCR/Util/CND/Parser/CndParser.php +++ b/src/PHPCR/Util/CND/Parser/CndParser.php @@ -35,30 +35,30 @@ class CndParser extends AbstractParser { // node type attributes - private $ORDERABLE = ['o', 'ord', 'orderable']; //, 'variant' => true); - private $MIXIN = ['m', 'mix', 'mixin']; //, 'variant' => true); - private $ABSTRACT = ['a', 'abs', 'abstract']; //, 'variant' => true); - private $NOQUERY = ['noquery', 'nq']; //, 'variant' => false); - private $QUERY = ['query', 'q']; //, 'variant' => false); - private $PRIMARYITEM = ['primaryitem', '!']; //, 'variant' => false); + private $ORDERABLE = ['o', 'ord', 'orderable']; // , 'variant' => true); + private $MIXIN = ['m', 'mix', 'mixin']; // , 'variant' => true); + private $ABSTRACT = ['a', 'abs', 'abstract']; // , 'variant' => true); + private $NOQUERY = ['noquery', 'nq']; // , 'variant' => false); + private $QUERY = ['query', 'q']; // , 'variant' => false); + private $PRIMARYITEM = ['primaryitem', '!']; // , 'variant' => false); // common for properties and child definitions - private $PRIMARY = ['!', 'pri', 'primary']; //, 'variant' => true), - private $AUTOCREATED = ['a', 'aut', 'autocreated']; //, 'variant' => true), - private $MANDATORY = ['m', 'man', 'mandatory']; //, 'variant' => true), - private $PROTECTED = ['p', 'pro', 'protected']; //, 'variant' => true), + private $PRIMARY = ['!', 'pri', 'primary']; // , 'variant' => true), + private $AUTOCREATED = ['a', 'aut', 'autocreated']; // , 'variant' => true), + private $MANDATORY = ['m', 'man', 'mandatory']; // , 'variant' => true), + private $PROTECTED = ['p', 'pro', 'protected']; // , 'variant' => true), private $OPV = ['COPY', 'VERSION', 'INITIALIZE', 'COMPUTE', 'IGNORE', 'ABORT']; // property type attributes - private $MULTIPLE = ['*', 'mul', 'multiple']; //, 'variant' => true), - private $QUERYOPS = ['qop', 'queryops']; //, 'variant' => true), // Needs special handling ! - private $NOFULLTEXT = ['nof', 'nofulltext']; //, 'variant' => true), - private $NOQUERYORDER = ['nqord', 'noqueryorder']; //, 'variant' => true), + private $MULTIPLE = ['*', 'mul', 'multiple']; // , 'variant' => true), + private $QUERYOPS = ['qop', 'queryops']; // , 'variant' => true), // Needs special handling ! + private $NOFULLTEXT = ['nof', 'nofulltext']; // , 'variant' => true), + private $NOQUERYORDER = ['nqord', 'noqueryorder']; // , 'variant' => true), // child node attributes // multiple is actually a jackrabbit specific synonym for sns // http://www.mail-archive.com/users@jackrabbit.apache.org/msg19268.html - private $SNS = ['*', 'sns', 'multiple']; //, 'variant' => true), + private $SNS = ['*', 'sns', 'multiple']; // , 'variant' => true), /** * @var NodeTypeManagerInterface @@ -75,9 +75,6 @@ class CndParser extends AbstractParser */ protected $nodeTypes = []; - /** - * @param NodeTypeManagerInterface $ntm - */ public function __construct(NodeTypeManagerInterface $ntm) { $this->ntm = $ntm; @@ -130,7 +127,7 @@ private function parse(ReaderInterface $reader) return [ 'namespaces' => $this->namespaces, - 'nodeTypes' => $this->nodeTypes, + 'nodeTypes' => $this->nodeTypes, ]; } @@ -350,7 +347,7 @@ protected function parsePropDef(NodeTypeTemplateInterface $nodeType) // Next token is '<' and two token later it's not '=', i.e. not 'tokenQueue->peek(); $next2 = $this->tokenQueue->peek(2); - if ($next1 && $next1->getData() === '<' && (!$next2 || $next2->getData() !== '=')) { + if ($next1 && '<' === $next1->getData() && (!$next2 || '=' !== $next2->getData())) { $this->parseValueConstraints($property); } } @@ -678,7 +675,7 @@ protected function parseCndString() $type = $token->getType(); $data = $token->getData(); - if ($type === Token::TK_STRING) { + if (Token::TK_STRING === $type) { $string = substr($data, 1, -1); $this->tokenQueue->next(); @@ -686,13 +683,13 @@ protected function parseCndString() } // If it's not an identifier or a symbol allowed in a string, break - if ($type !== Token::TK_IDENTIFIER && $type !== Token::TK_SYMBOL - || ($type === Token::TK_SYMBOL && $data !== '_' && $data !== ':')) { + if (Token::TK_IDENTIFIER !== $type && Token::TK_SYMBOL !== $type + || (Token::TK_SYMBOL === $type && '_' !== $data && ':' !== $data)) { break; } // Detect spaces (an identifier cannot be followed by an identifier as it would have been read as a single token) - if ($type === Token::TK_IDENTIFIER && $lastType === Token::TK_IDENTIFIER) { + if (Token::TK_IDENTIFIER === $type && Token::TK_IDENTIFIER === $lastType) { break; } @@ -702,7 +699,7 @@ protected function parseCndString() $lastType = $type; } - if ($string === '') { + if ('' === $string) { throw new ParserException($this->tokenQueue, sprintf("Expected CND string, found '%s': ", $this->tokenQueue->peek()->getData())); } @@ -752,10 +749,10 @@ protected function parseQueryOperator() switch ($data) { case '<': - $op = ($nextData === '>' ? '>=' : ($nextData === '=' ? '<=' : '<')); + $op = ('>' === $nextData ? '>=' : ('=' === $nextData ? '<=' : '<')); break; case '>': - $op = ($nextData === '=' ? '>=' : '>'); + $op = ('=' === $nextData ? '>=' : '>'); break; case '=': $op = '='; @@ -766,9 +763,9 @@ protected function parseQueryOperator() } // Consume the correct number of tokens - if ($op === 'LIKE' || strlen($op) === 1) { + if ('LIKE' === $op || 1 === strlen($op)) { $this->tokenQueue->next(); - } elseif (strlen($op) === 2) { + } elseif (2 === strlen($op)) { $this->tokenQueue->next(); $this->tokenQueue->next(); } diff --git a/src/PHPCR/Util/CND/Reader/BufferReader.php b/src/PHPCR/Util/CND/Reader/BufferReader.php index e38c00df..20db884d 100644 --- a/src/PHPCR/Util/CND/Reader/BufferReader.php +++ b/src/PHPCR/Util/CND/Reader/BufferReader.php @@ -115,6 +115,7 @@ public function currentChar() public function isEof() { $currentChar = $this->currentChar(); + // substr after end of string returned false in PHP 5 and returns '' since PHP 7 return in_array($currentChar, [$this->getEofMarker(), false, ''], true) || $this->startPos > strlen($this->buffer) @@ -129,12 +130,12 @@ public function isEof() public function forward() { if ($this->forwardPos < strlen($this->buffer)) { - $this->forwardPos++; - $this->nextCurCol++; + ++$this->forwardPos; + ++$this->nextCurCol; } - if ($this->current() === "\n") { - $this->nextCurLine++; + if ("\n" === $this->current()) { + ++$this->nextCurLine; $this->nextCurCol = 1; } diff --git a/src/PHPCR/Util/CND/Scanner/AbstractScanner.php b/src/PHPCR/Util/CND/Scanner/AbstractScanner.php index f61f0dd1..35eb208f 100644 --- a/src/PHPCR/Util/CND/Scanner/AbstractScanner.php +++ b/src/PHPCR/Util/CND/Scanner/AbstractScanner.php @@ -30,8 +30,6 @@ public function resetQueue() } /** - * @param Token $token - * * @return Token|void */ public function applyFilters(Token $token) diff --git a/src/PHPCR/Util/CND/Scanner/Context/ScannerContext.php b/src/PHPCR/Util/CND/Scanner/Context/ScannerContext.php index a9ea48a9..f9855dd1 100644 --- a/src/PHPCR/Util/CND/Scanner/Context/ScannerContext.php +++ b/src/PHPCR/Util/CND/Scanner/Context/ScannerContext.php @@ -143,9 +143,6 @@ public function getWhitespaces() return $this->whitespaces; } - /** - * @param TokenFilterInterface $filter - */ public function addTokenFilter(TokenFilterInterface $filter) { $this->tokenFilters[] = $filter; diff --git a/src/PHPCR/Util/CND/Scanner/GenericScanner.php b/src/PHPCR/Util/CND/Scanner/GenericScanner.php index 76ccecd5..18608540 100644 --- a/src/PHPCR/Util/CND/Scanner/GenericScanner.php +++ b/src/PHPCR/Util/CND/Scanner/GenericScanner.php @@ -21,8 +21,6 @@ class GenericScanner extends AbstractScanner /** * Scan the given reader and construct a TokenQueue composed of GenericToken. * - * @param ReaderInterface $reader - * * @return TokenQueue */ public function scan(ReaderInterface $reader) @@ -55,8 +53,6 @@ public function scan(ReaderInterface $reader) /** * Detect and consume whitespaces. * - * @param ReaderInterface $reader - * * @return bool */ protected function consumeSpaces(ReaderInterface $reader) @@ -81,17 +77,15 @@ protected function consumeSpaces(ReaderInterface $reader) /** * Detect and consume newlines. * - * @param ReaderInterface $reader - * * @return bool */ protected function consumeNewLine(ReaderInterface $reader) { - if ($reader->currentChar() === "\n") { + if ("\n" === $reader->currentChar()) { $token = new GenericToken(GenericToken::TK_NEWLINE, "\n"); $this->addToken($reader, $token); - while ($reader->forward() === "\n") { + while ("\n" === $reader->forward()) { $reader->consume(); $reader->forward(); } @@ -106,11 +100,9 @@ protected function consumeNewLine(ReaderInterface $reader) /** * Detect and consume strings. * - * @param ReaderInterface $reader + * @return bool * * @throws ScannerException - * - * @return bool */ protected function consumeString(ReaderInterface $reader) { @@ -118,7 +110,7 @@ protected function consumeString(ReaderInterface $reader) if (in_array($curDelimiter, $this->context->getStringDelimiters())) { $char = $reader->forwardChar(); while ($char !== $curDelimiter) { - if ($char === "\n") { + if ("\n" === $char) { throw new ScannerException($reader, 'Newline detected in string'); } @@ -138,8 +130,6 @@ protected function consumeString(ReaderInterface $reader) /** * Detect and consume comments. * - * @param ReaderInterface $reader - * * @return bool */ protected function consumeComments(ReaderInterface $reader) @@ -154,11 +144,9 @@ protected function consumeComments(ReaderInterface $reader) /** * Detect and consume block comments. * - * @param ReaderInterface $reader + * @return bool * * @throws ScannerException - * - * @return bool */ protected function consumeBlockComments(ReaderInterface $reader) { @@ -166,7 +154,7 @@ protected function consumeBlockComments(ReaderInterface $reader) foreach ($this->context->getBlockCommentDelimiters() as $beginDelim => $endDelim) { if ($nextChar === $beginDelim[0]) { // Lookup the start delimiter - for ($i = 1; $i <= strlen($beginDelim); $i++) { + for ($i = 1; $i <= strlen($beginDelim); ++$i) { $reader->forward(); } if ($reader->current() === $beginDelim) { @@ -175,7 +163,7 @@ protected function consumeBlockComments(ReaderInterface $reader) while (!$reader->isEof()) { if ($nextChar === $endDelim[0]) { - for ($i = 1; $i <= strlen($endDelim); $i++) { + for ($i = 1; $i <= strlen($endDelim); ++$i) { $reader->forward(); } @@ -207,8 +195,6 @@ protected function consumeBlockComments(ReaderInterface $reader) /** * Detect and consume line comments. * - * @param ReaderInterface $reader - * * @return bool */ protected function consumeLineComments(ReaderInterface $reader) @@ -216,14 +202,14 @@ protected function consumeLineComments(ReaderInterface $reader) $nextChar = $reader->currentChar(); foreach ($this->context->getLineCommentDelimiters() as $delimiter) { if ($delimiter && $nextChar === $delimiter[0]) { - for ($i = 1; $i <= strlen($delimiter); $i++) { + for ($i = 1; $i <= strlen($delimiter); ++$i) { $reader->forward(); } if ($reader->current() === $delimiter) { // consume to end of line $char = $reader->currentChar(); - while (!$reader->isEof() && $char !== "\n") { + while (!$reader->isEof() && "\n" !== $char) { $char = $reader->forwardChar(); } $token = new GenericToken(GenericToken::TK_COMMENT, $reader->consume()); @@ -245,8 +231,6 @@ protected function consumeLineComments(ReaderInterface $reader) /** * Detect and consume identifiers. * - * @param ReaderInterface $reader - * * @return bool */ protected function consumeIdentifiers(ReaderInterface $reader) @@ -270,8 +254,6 @@ protected function consumeIdentifiers(ReaderInterface $reader) /** * Detect and consume symbols. * - * @param ReaderInterface $reader - * * @return bool */ protected function consumeSymbols(ReaderInterface $reader) diff --git a/src/PHPCR/Util/CND/Scanner/GenericToken.php b/src/PHPCR/Util/CND/Scanner/GenericToken.php index 735de8c7..6d7e7e52 100644 --- a/src/PHPCR/Util/CND/Scanner/GenericToken.php +++ b/src/PHPCR/Util/CND/Scanner/GenericToken.php @@ -9,14 +9,14 @@ */ class GenericToken extends Token { - const TK_WHITESPACE = 0; - const TK_NEWLINE = 1; - const TK_STRING = 2; - const TK_COMMENT = 3; - const TK_IDENTIFIER = 4; - const TK_KEYWORD = 5; - const TK_SYMBOL = 6; - const TK_UNKNOWN = 99; + public const TK_WHITESPACE = 0; + public const TK_NEWLINE = 1; + public const TK_STRING = 2; + public const TK_COMMENT = 3; + public const TK_IDENTIFIER = 4; + public const TK_KEYWORD = 5; + public const TK_SYMBOL = 6; + public const TK_UNKNOWN = 99; public static function getTypeName($type) { diff --git a/src/PHPCR/Util/CND/Scanner/TokenFilter/TokenFilterChain.php b/src/PHPCR/Util/CND/Scanner/TokenFilter/TokenFilterChain.php index f24fdb6b..04020596 100644 --- a/src/PHPCR/Util/CND/Scanner/TokenFilter/TokenFilterChain.php +++ b/src/PHPCR/Util/CND/Scanner/TokenFilter/TokenFilterChain.php @@ -22,9 +22,7 @@ public function addFilter(TokenFilterInterface $filter) } /** - * @param Token $token - * - * @return Token | null + * @return Token|null */ public function filter(Token $token) { diff --git a/src/PHPCR/Util/CND/Scanner/TokenFilter/TokenFilterInterface.php b/src/PHPCR/Util/CND/Scanner/TokenFilter/TokenFilterInterface.php index 6acf162f..d61a7a29 100644 --- a/src/PHPCR/Util/CND/Scanner/TokenFilter/TokenFilterInterface.php +++ b/src/PHPCR/Util/CND/Scanner/TokenFilter/TokenFilterInterface.php @@ -14,9 +14,7 @@ interface TokenFilterInterface /** * @abstract * - * @param Token $token - * - * @return Token | null + * @return Token|null */ public function filter(Token $token); } diff --git a/src/PHPCR/Util/CND/Scanner/TokenFilter/TokenTypeFilter.php b/src/PHPCR/Util/CND/Scanner/TokenFilter/TokenTypeFilter.php index 92683888..1bb953fa 100644 --- a/src/PHPCR/Util/CND/Scanner/TokenFilter/TokenTypeFilter.php +++ b/src/PHPCR/Util/CND/Scanner/TokenFilter/TokenTypeFilter.php @@ -24,9 +24,7 @@ public function __construct($tokenType) } /** - * @param Token $token - * - * @return Token | null + * @return Token|null */ public function filter(Token $token) { diff --git a/src/PHPCR/Util/CND/Scanner/TokenQueue.php b/src/PHPCR/Util/CND/Scanner/TokenQueue.php index d1424d16..0904e24b 100644 --- a/src/PHPCR/Util/CND/Scanner/TokenQueue.php +++ b/src/PHPCR/Util/CND/Scanner/TokenQueue.php @@ -31,7 +31,7 @@ public function reset() public function isEof() { - return current($this->tokens) === false; + return false === current($this->tokens); } public function peek($offset = 0) @@ -52,7 +52,7 @@ public function peek($offset = 0) public function get($count = 1) { $item = null; - for ($i = 1; $i <= $count; $i++) { + for ($i = 1; $i <= $count; ++$i) { $item = $this->peek(); $this->next(); } diff --git a/src/PHPCR/Util/CND/Writer/CndWriter.php b/src/PHPCR/Util/CND/Writer/CndWriter.php index 2ab75382..154d8bdc 100644 --- a/src/PHPCR/Util/CND/Writer/CndWriter.php +++ b/src/PHPCR/Util/CND/Writer/CndWriter.php @@ -44,7 +44,7 @@ public function __construct(NamespaceRegistryInterface $ns) * @param NodeTypeTemplateInterface[] $nodeTypes * * @return string with declarations for all non-system namespaces and for - * all node types in that array. + * all node types in that array */ public function writeString(array $nodeTypes) { diff --git a/src/PHPCR/Util/Console/Command/BaseCommand.php b/src/PHPCR/Util/Console/Command/BaseCommand.php index 5fdd56e7..d1ff179f 100644 --- a/src/PHPCR/Util/Console/Command/BaseCommand.php +++ b/src/PHPCR/Util/Console/Command/BaseCommand.php @@ -51,10 +51,8 @@ protected function getPhpcrConsoleDumperHelper() /** * Ask a question with the question helper or the dialog helper for symfony < 2.5 compatibility. * - * @param InputInterface $input - * @param OutputInterface $output - * @param string $questionText - * @param string $default + * @param string $questionText + * @param string $default * * @return string */ @@ -72,10 +70,8 @@ protected function ask(InputInterface $input, OutputInterface $output, $question /** * Ask for confirmation with the question helper or the dialog helper for symfony < 2.5 compatibility. * - * @param InputInterface $input - * @param OutputInterface $output - * @param string $questionText - * @param bool $default + * @param string $questionText + * @param bool $default * * @return string */ diff --git a/src/PHPCR/Util/Console/Command/NodeDumpCommand.php b/src/PHPCR/Util/Console/Command/NodeDumpCommand.php index dcfbd686..0f6f434c 100644 --- a/src/PHPCR/Util/Console/Command/NodeDumpCommand.php +++ b/src/PHPCR/Util/Console/Command/NodeDumpCommand.php @@ -2,7 +2,6 @@ namespace PHPCR\Util\Console\Command; -use Exception; use PHPCR\ItemNotFoundException; use PHPCR\PathNotFoundException; use PHPCR\RepositoryException; @@ -52,7 +51,7 @@ protected function configure(): void /** * @throws InvalidArgumentException - * @throws Exception + * @throws \Exception * @throws RepositoryException */ protected function execute(InputInterface $input, OutputInterface $output): int @@ -72,7 +71,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $options['max_line_length'] = $input->getOption('max_line_length'); if (null !== $options['ref_format'] && !in_array($options['ref_format'], ['uuid', 'path'])) { - throw new Exception('The ref-format option must be set to either "path" or "uuid"'); + throw new \Exception('The ref-format option must be set to either "path" or "uuid"'); } $walker = $dumperHelper->getTreeWalker($output, $options); diff --git a/src/PHPCR/Util/Console/Command/NodeRemoveCommand.php b/src/PHPCR/Util/Console/Command/NodeRemoveCommand.php index 0ee74319..a6083a1b 100644 --- a/src/PHPCR/Util/Console/Command/NodeRemoveCommand.php +++ b/src/PHPCR/Util/Console/Command/NodeRemoveCommand.php @@ -2,7 +2,6 @@ namespace PHPCR\Util\Console\Command; -use InvalidArgumentException; use PHPCR\NodeInterface; use Symfony\Component\Console\Exception\InvalidArgumentException as CliInvalidArgumentException; use Symfony\Component\Console\Input\InputArgument; @@ -49,7 +48,7 @@ protected function configure(): void /** * @throws CliInvalidArgumentException - * @throws InvalidArgumentException + * @throws \InvalidArgumentException */ protected function execute(InputInterface $input, OutputInterface $output): int { @@ -62,7 +61,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int if ('/' === $path) { // even if we have only children, this will not work as we would // try to remove system nodes. - throw new InvalidArgumentException( + throw new \InvalidArgumentException( 'Can not delete root node (path "/"), please use the '. 'workspace:purge command instead to purge the whole workspace.' ); diff --git a/src/PHPCR/Util/Console/Command/NodeTouchCommand.php b/src/PHPCR/Util/Console/Command/NodeTouchCommand.php index e3cd0f45..e4dca658 100644 --- a/src/PHPCR/Util/Console/Command/NodeTouchCommand.php +++ b/src/PHPCR/Util/Console/Command/NodeTouchCommand.php @@ -132,11 +132,11 @@ protected function execute(InputInterface $input, OutputInterface $output): int } $helper->processNode($output, $node, [ - 'setProp' => $setProp, - 'removeProp' => $removeProp, - 'addMixins' => $addMixins, + 'setProp' => $setProp, + 'removeProp' => $removeProp, + 'addMixins' => $addMixins, 'removeMixins' => $removeMixins, - 'dump' => $dump, + 'dump' => $dump, ]); $session->save(); diff --git a/src/PHPCR/Util/Console/Command/NodeTypeRegisterCommand.php b/src/PHPCR/Util/Console/Command/NodeTypeRegisterCommand.php index 0534b2cc..3e8485fe 100644 --- a/src/PHPCR/Util/Console/Command/NodeTypeRegisterCommand.php +++ b/src/PHPCR/Util/Console/Command/NodeTypeRegisterCommand.php @@ -2,7 +2,6 @@ namespace PHPCR\Util\Console\Command; -use InvalidArgumentException; use PHPCR\NodeType\NodeTypeExistsException; use PHPCR\RepositoryException; use PHPCR\SessionInterface; @@ -17,7 +16,7 @@ * * See the link below for the cnd definition. * - * @link http://jackrabbit.apache.org/node-type-notation.html + * @see http://jackrabbit.apache.org/node-type-notation.html * * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License @@ -59,14 +58,14 @@ protected function configure(): void } /** - * @throws InvalidArgumentException + * @throws \InvalidArgumentException */ protected function execute(InputInterface $input, OutputInterface $output): int { $definitions = $input->getArgument('cnd-file'); - if (count($definitions) == 0) { - throw new InvalidArgumentException('At least one definition (i.e. file or folder) must be specified'); + if (0 == count($definitions)) { + throw new \InvalidArgumentException('At least one definition (i.e. file or folder) must be specified'); } $allowUpdate = $input->getOption('allow-update'); @@ -79,7 +78,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $cnd = file_get_contents($filePath); $this->updateFromCnd($output, $session, $cnd, $allowUpdate); $output->writeln(sprintf('Node type definition: %s', $filePath)); - $count++; + ++$count; } $output->writeln(sprintf('%d node definition(s) registered', $count)); @@ -93,7 +92,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int * @param OutputInterface $output the console output stream * @param SessionInterface $session the PHPCR session to talk to * @param string $cnd the compact namespace and node type definition in string form - * @param bool $allowUpdate whether to allow updating existing node types. + * @param bool $allowUpdate whether to allow updating existing node types * * @throws RepositoryException on other errors */ @@ -120,9 +119,9 @@ protected function updateFromCnd(OutputInterface $output, SessionInterface $sess * * @param array $definitions List of files of folders * - * @throws InvalidArgumentException + * @return array array of full paths to all the type node definition files * - * @return array Array of full paths to all the type node definition files. + * @throws \InvalidArgumentException */ protected function getFilePaths($definitions) { @@ -140,7 +139,7 @@ protected function getFilePaths($definitions) $filePath = sprintf('%s/%s', $definition, $file); if (!is_readable($filePath)) { - throw new InvalidArgumentException( + throw new \InvalidArgumentException( sprintf("Node type definition file '%s' does not have read permissions.", $file) ); } @@ -149,7 +148,7 @@ protected function getFilePaths($definitions) } } else { if (!file_exists($definition)) { - throw new InvalidArgumentException( + throw new \InvalidArgumentException( sprintf("Node type definition file / folder '%s' does not exist.", $definition) ); } @@ -163,6 +162,6 @@ protected function getFilePaths($definitions) protected function fileIsNodeType($filename) { - return substr($filename, -4) === '.cnd'; + return '.cnd' === substr($filename, -4); } } diff --git a/src/PHPCR/Util/Console/Command/NodesUpdateCommand.php b/src/PHPCR/Util/Console/Command/NodesUpdateCommand.php index 6e29b1dd..dd8ca70c 100644 --- a/src/PHPCR/Util/Console/Command/NodesUpdateCommand.php +++ b/src/PHPCR/Util/Console/Command/NodesUpdateCommand.php @@ -2,7 +2,6 @@ namespace PHPCR\Util\Console\Command; -use InvalidArgumentException; use PHPCR\Query\QueryResultInterface; use PHPCR\Query\RowInterface; use Symfony\Component\Console\Exception\InvalidArgumentException as CliInvalidArgumentException; @@ -81,7 +80,7 @@ protected function configure(): void /** * @throws CliInvalidArgumentException - * @throws InvalidArgumentException + * @throws \InvalidArgumentException */ protected function execute(InputInterface $input, OutputInterface $output): int { @@ -98,13 +97,13 @@ protected function execute(InputInterface $input, OutputInterface $output): int $session = $this->getPhpcrSession(); if (!$query) { - throw new InvalidArgumentException( + throw new \InvalidArgumentException( 'You must provide a SELECT query, e.g. --query="SELECT * FROM [nt:unstructured]"' ); } - if (strtoupper(substr($query, 0, 6)) !== 'SELECT') { - throw new InvalidArgumentException("Query doesn't look like a SELECT query: '$query'"); + if ('SELECT' !== strtoupper(substr($query, 0, 6))) { + throw new \InvalidArgumentException("Query doesn't look like a SELECT query: '$query'"); } $query = $helper->createQuery($queryLanguage, $query); @@ -129,14 +128,14 @@ protected function execute(InputInterface $input, OutputInterface $output): int $node = $row->getNode(); $helper->processNode($output, $node, [ - 'setProp' => $setProp, - 'removeProp' => $removeProp, - 'addMixins' => $addMixins, - 'removeMixins' => $removeMixins, + 'setProp' => $setProp, + 'removeProp' => $removeProp, + 'addMixins' => $addMixins, + 'removeMixins' => $removeMixins, 'applyClosures' => $applyClosures, ]); - $persistIn--; + --$persistIn; if (0 === $persistIn) { $output->writeln('Saving nodes processed so far...'); $session->save(); @@ -152,7 +151,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int } /** - * @return bool Whether to execute the action or not. + * @return bool whether to execute the action or not */ private function shouldExecute(InputInterface $input, OutputInterface $output, QueryResultInterface $result) { @@ -161,7 +160,7 @@ private function shouldExecute(InputInterface $input, OutputInterface $output, Q count($result->getRows()) ))); - if ($response === 'L') { + if ('L' === $response) { /** @var RowInterface $row */ foreach ($result as $i => $row) { $output->writeln(sprintf(' - [%d] %s', $i, $row->getPath())); @@ -170,11 +169,11 @@ private function shouldExecute(InputInterface $input, OutputInterface $output, Q return $this->shouldExecute($input, $output, $result); } - if ($response === 'N') { + if ('N' === $response) { return false; } - if ($response === 'Y') { + if ('Y' === $response) { return true; } diff --git a/src/PHPCR/Util/Console/Command/WorkspaceExportCommand.php b/src/PHPCR/Util/Console/Command/WorkspaceExportCommand.php index c8e0f7b3..1487b4af 100644 --- a/src/PHPCR/Util/Console/Command/WorkspaceExportCommand.php +++ b/src/PHPCR/Util/Console/Command/WorkspaceExportCommand.php @@ -58,7 +58,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int return 2; } - $session->exportSystemView($path, $stream, $input->getOption('skip_binary') === 'yes', $input->getOption('recurse') === 'no'); + $session->exportSystemView($path, $stream, 'yes' === $input->getOption('skip_binary'), 'no' === $input->getOption('recurse')); $output->writeln(sprintf( 'Successfully exported workspace "%s", path "%s" to file "%s".', diff --git a/src/PHPCR/Util/Console/Command/WorkspaceImportCommand.php b/src/PHPCR/Util/Console/Command/WorkspaceImportCommand.php index 1641d7f5..109f3f96 100644 --- a/src/PHPCR/Util/Console/Command/WorkspaceImportCommand.php +++ b/src/PHPCR/Util/Console/Command/WorkspaceImportCommand.php @@ -17,11 +17,11 @@ */ class WorkspaceImportCommand extends BaseCommand { - const UUID_BEHAVIOR = [ - 'new' => ImportUUIDBehaviorInterface::IMPORT_UUID_CREATE_NEW, - 'remove' => ImportUUIDBehaviorInterface::IMPORT_UUID_COLLISION_REMOVE_EXISTING, + public const UUID_BEHAVIOR = [ + 'new' => ImportUUIDBehaviorInterface::IMPORT_UUID_CREATE_NEW, + 'remove' => ImportUUIDBehaviorInterface::IMPORT_UUID_COLLISION_REMOVE_EXISTING, 'replace' => ImportUUIDBehaviorInterface::IMPORT_UUID_COLLISION_REPLACE_EXISTING, - 'throw' => ImportUUIDBehaviorInterface::IMPORT_UUID_COLLISION_THROW, + 'throw' => ImportUUIDBehaviorInterface::IMPORT_UUID_COLLISION_THROW, ]; protected function configure(): void diff --git a/src/PHPCR/Util/Console/Helper/PhpcrConsoleDumperHelper.php b/src/PHPCR/Util/Console/Helper/PhpcrConsoleDumperHelper.php index 04c35226..f22c51b5 100644 --- a/src/PHPCR/Util/Console/Helper/PhpcrConsoleDumperHelper.php +++ b/src/PHPCR/Util/Console/Helper/PhpcrConsoleDumperHelper.php @@ -20,9 +20,9 @@ class PhpcrConsoleDumperHelper extends Helper public function getTreeWalker(OutputInterface $output, $options) { $options = array_merge([ - 'dump_uuids' => false, - 'ref_format' => 'uuid', - 'show_props' => false, + 'dump_uuids' => false, + 'ref_format' => 'uuid', + 'show_props' => false, 'show_sys_nodes' => false, ], $options); diff --git a/src/PHPCR/Util/Console/Helper/PhpcrHelper.php b/src/PHPCR/Util/Console/Helper/PhpcrHelper.php index 8e044dd5..68608c98 100644 --- a/src/PHPCR/Util/Console/Helper/PhpcrHelper.php +++ b/src/PHPCR/Util/Console/Helper/PhpcrHelper.php @@ -2,7 +2,6 @@ namespace PHPCR\Util\Console\Helper; -use Exception; use PHPCR\NodeInterface; use PHPCR\PropertyInterface; use PHPCR\SessionInterface; @@ -54,19 +53,19 @@ public function getName(): string * * Provides common processing for both touch and update commands. * - * @param OutputInterface $output used for status updates. - * @param NodeInterface $node the node to manipulate. - * @param array $operations to execute on that node. + * @param OutputInterface $output used for status updates + * @param NodeInterface $node the node to manipulate + * @param array $operations to execute on that node */ public function processNode(OutputInterface $output, NodeInterface $node, array $operations) { $operations = array_merge([ - 'setProp' => [], - 'removeProp' => [], - 'addMixins' => [], - 'removeMixins' => [], + 'setProp' => [], + 'removeProp' => [], + 'addMixins' => [], + 'removeMixins' => [], 'applyClosures' => [], - 'dump' => false, + 'dump' => false, ], $operations); foreach ($operations['setProp'] as $set) { @@ -164,9 +163,9 @@ public function createQuery($language, $sql) /** * Check if this is a supported query language. * - * @param string $language Language name. + * @param string $language language name * - * @throws \Exception if the language is not supported. + * @throws \Exception if the language is not supported */ protected function validateQueryLanguage($language) { @@ -178,7 +177,7 @@ protected function validateQueryLanguage($language) } } - throw new Exception(sprintf( + throw new \Exception(sprintf( 'Query language "%s" not supported, available query languages: %s', $language, implode(',', $langs) diff --git a/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperItemVisitor.php b/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperItemVisitor.php index ddd16233..fe334e17 100644 --- a/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperItemVisitor.php +++ b/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperItemVisitor.php @@ -28,8 +28,6 @@ abstract class ConsoleDumperItemVisitor implements ItemVisitorInterface /** * Instantiate the console dumper visitor. - * - * @param OutputInterface $output */ public function __construct(OutputInterface $output) { diff --git a/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperNodeVisitor.php b/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperNodeVisitor.php index c64438b3..3656b18e 100644 --- a/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperNodeVisitor.php +++ b/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperNodeVisitor.php @@ -2,7 +2,6 @@ namespace PHPCR\Util\Console\Helper\TreeDumper; -use Exception; use PHPCR\ItemInterface; use PHPCR\NodeInterface; use Symfony\Component\Console\Output\OutputInterface; @@ -29,8 +28,7 @@ class ConsoleDumperNodeVisitor extends ConsoleDumperItemVisitor /** * Instantiate the console dumper visitor. * - * @param OutputInterface $output - * @param bool $identifiers whether to output the node UUID + * @param bool $identifiers whether to output the node UUID */ public function __construct(OutputInterface $output, $identifiers = false) { @@ -53,15 +51,15 @@ public function setShowFullPath($showFullPath) * * @param ItemInterface $item the node to visit * - * @throws Exception + * @throws \Exception */ public function visit(ItemInterface $item) { if (!$item instanceof NodeInterface) { - throw new Exception('Internal error: did not expect to visit a non-node object: '.get_class($item)); + throw new \Exception('Internal error: did not expect to visit a non-node object: '.get_class($item)); } - if ($item->getDepth() === 0) { + if (0 === $item->getDepth()) { $name = 'ROOT'; } elseif ($this->showFullPath) { $name = $item->getPath(); diff --git a/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperPropertyVisitor.php b/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperPropertyVisitor.php index 63ccbc7b..6202b495 100644 --- a/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperPropertyVisitor.php +++ b/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperPropertyVisitor.php @@ -2,7 +2,6 @@ namespace PHPCR\Util\Console\Helper\TreeDumper; -use Exception; use PHPCR\ItemInterface; use PHPCR\PropertyInterface; use PHPCR\PropertyType; @@ -35,14 +34,13 @@ class ConsoleDumperPropertyVisitor extends ConsoleDumperItemVisitor /** * Instantiate property visitor. * - * @param OutputInterface $output - * @param array $options + * @param array $options */ public function __construct(OutputInterface $output, $options = []) { $options = array_merge([ 'max_line_length' => 120, - 'ref_format' => 'uuid', + 'ref_format' => 'uuid', ], $options); parent::__construct($output); @@ -56,12 +54,12 @@ public function __construct(OutputInterface $output, $options = []) * * @param ItemInterface $item the property to visit * - * @throws Exception + * @throws \Exception */ public function visit(ItemInterface $item) { if (!$item instanceof PropertyInterface) { - throw new Exception(sprintf('Internal error: did not expect to visit a non-property object: %s', is_object($item) ? get_class($item) : $item)); + throw new \Exception(sprintf('Internal error: did not expect to visit a non-property object: %s', is_object($item) ? get_class($item) : $item)); } $value = $item->getString(); diff --git a/src/PHPCR/Util/Console/Helper/TreeDumper/SystemNodeFilter.php b/src/PHPCR/Util/Console/Helper/TreeDumper/SystemNodeFilter.php index 51c1cf67..9c6e86c4 100644 --- a/src/PHPCR/Util/Console/Helper/TreeDumper/SystemNodeFilter.php +++ b/src/PHPCR/Util/Console/Helper/TreeDumper/SystemNodeFilter.php @@ -17,11 +17,9 @@ class SystemNodeFilter implements TreeWalkerFilterInterface /** * Checks whether this item is a system item. * - * @param ItemInterface $item + * @return bool * * @throws RepositoryException - * - * @return bool */ public function mustVisit(ItemInterface $item) { diff --git a/src/PHPCR/Util/NodeHelper.php b/src/PHPCR/Util/NodeHelper.php index fada226e..84e80900 100644 --- a/src/PHPCR/Util/NodeHelper.php +++ b/src/PHPCR/Util/NodeHelper.php @@ -2,7 +2,6 @@ namespace PHPCR\Util; -use InvalidArgumentException; use PHPCR\ItemExistsException; use PHPCR\ItemInterface; use PHPCR\ItemNotFoundException; @@ -39,15 +38,15 @@ private function __construct() * @param SessionInterface $session the PHPCR session to create the path * @param string $path full path, like /content/jobs/data * - * @throws InvalidArgumentException + * @return NodeInterface the last node of the path, i.e. data + * + * @throws \InvalidArgumentException * @throws RepositoryException * @throws PathNotFoundException * @throws ItemExistsException * @throws LockException * @throws ConstraintViolationException * @throws VersionException - * - * @return NodeInterface the last node of the path, i.e. data */ public static function createPath(SessionInterface $session, $path) { @@ -104,8 +103,6 @@ public static function purgeWorkspace(SessionInterface $session) /** * Kept as alias of purgeWorkspace for BC compatibility. * - * @param SessionInterface $session - * * @throws RepositoryException * * @deprecated @@ -120,11 +117,9 @@ public static function deleteAllNodes(SessionInterface $session) * usually want to hide and that should not be removed when purging the * repository. * - * @param ItemInterface $item + * @return bool true if $item is a system item, false otherwise * * @throws RepositoryException - * - * @return bool true if $item is a system item, false otherwise */ public static function isSystemItem(ItemInterface $item) { @@ -133,7 +128,7 @@ public static function isSystemItem(ItemInterface $item) } $name = $item->getName(); - return strpos($name, 'jcr:') === 0 || strpos($name, 'rep:') === 0; + return 0 === strpos($name, 'jcr:') || 0 === strpos($name, 'rep:'); } /** @@ -142,17 +137,17 @@ public static function isSystemItem(ItemInterface $item) * This method only checks for valid namespaces. All other exceptions must * be thrown by the addNodeAutoNamed implementation. * - * @param string[] $usedNames list of child names that is currently used and may not be chosen. - * @param string[] $namespaces namespace prefix to uri map of all currently known namespaces. - * @param string $defaultNamespace namespace prefix to use if the hint does not specify. + * @param string[] $usedNames list of child names that is currently used and may not be chosen + * @param string[] $namespaces namespace prefix to uri map of all currently known namespaces + * @param string $defaultNamespace namespace prefix to use if the hint does not specify * @param string $nameHint the name hint according to the API definition * + * @return string A valid node name for this node + * * @throws NamespaceException if a namespace prefix is provided in the * $nameHint which does not exist and this implementation performs - * this validation immediately. + * this validation immediately * @throws RepositoryException - * - * @return string A valid node name for this node */ public static function generateAutoNodeName($usedNames, $namespaces, $defaultNamespace, $nameHint = null) { @@ -179,7 +174,7 @@ public static function generateAutoNodeName($usedNames, $namespaces, $defaultNam * valid namespace prefix */ if (':' === $nameHint[strlen($nameHint) - 1] - && substr_count($nameHint, ':') === 1 + && 1 === substr_count($nameHint, ':') && preg_match('#^[a-zA-Z][a-zA-Z0-9]*:$#', $nameHint) ) { $prefix = substr($nameHint, 0, -1); @@ -288,13 +283,13 @@ private static function generateWithPrefix($usedNames, $prefix, $namepart = '') * @param array $new new order * * @return array the keys are elements to move, values the destination to - * move before or null to move to the end. + * move before or null to move to the end */ public static function calculateOrderBefore(array $old, array $new) { $reorders = []; - //check for deleted items + // check for deleted items $newIndex = array_flip($new); foreach ($old as $key => $value) { @@ -310,22 +305,22 @@ public static function calculateOrderBefore(array $old, array $new) $len = count($new) - 1; $oldIndex = array_flip($old); - //go backwards on the new node order and arrange them this way - for ($i = $len; $i >= 0; $i--) { - //get the name of the child node + // go backwards on the new node order and arrange them this way + for ($i = $len; $i >= 0; --$i) { + // get the name of the child node $current = $new[$i]; - //check if it's not the last node + // check if it's not the last node if (isset($new[$i + 1])) { // get the name of the next node $next = $new[$i + 1]; - //if in the old order $c and next are not neighbors already, do the reorder command + // if in the old order $c and next are not neighbors already, do the reorder command if ($oldIndex[$current] + 1 != $oldIndex[$next]) { $reorders[$current] = $next; $old = self::orderBeforeArray($current, $next, $old); $oldIndex = array_flip($old); } } else { - //check if it's not already at the end of the nodes + // check if it's not already at the end of the nodes if ($oldIndex[$current] != $len) { $reorders[$current] = null; $old = self::orderBeforeArray($current, null, $old); @@ -346,9 +341,9 @@ public static function calculateOrderBefore(array $old, array $new) * to be ordered before, null to move to the end * @param array $list the array of names * - * @throws ItemNotFoundException if $srcChildRelPath or $destChildRelPath are not found in $nodes - * * @return array The updated $nodes array with new order + * + * @throws ItemNotFoundException if $srcChildRelPath or $destChildRelPath are not found in $nodes */ public static function orderBeforeArray($name, $destination, $list) { @@ -360,19 +355,19 @@ public static function orderBeforeArray($name, $destination, $list) throw new ItemNotFoundException("$name is not a child of this node"); } - if ($destination == null) { + if (null == $destination) { // null means move to end unset($list[$oldpos]); $list[] = $name; } else { // insert before element $destination $newpos = array_search($destination, $list); - if ($newpos === false) { + if (false === $newpos) { throw new ItemNotFoundException("$destination is not a child of this node"); } if ($oldpos < $newpos) { // we first unset, the position will change by one - $newpos--; + --$newpos; } unset($list[$oldpos]); array_splice($list, $newpos, 0, $name); diff --git a/src/PHPCR/Util/PathHelper.php b/src/PHPCR/Util/PathHelper.php index 8fba4160..649ef73d 100644 --- a/src/PHPCR/Util/PathHelper.php +++ b/src/PHPCR/Util/PathHelper.php @@ -40,14 +40,14 @@ private function __construct() * @param array|bool $namespacePrefixes List of all known namespace prefixes. * If specified, this method validates that the path contains no unknown prefixes. * - * @throws RepositoryException if the path contains invalid characters and $throw is true - * * @return bool true if valid, false if not valid and $throw was false + * + * @throws RepositoryException if the path contains invalid characters and $throw is true */ public static function assertValidAbsolutePath($path, $destination = false, $throw = true, $namespacePrefixes = false) { if ((!is_string($path) && !is_numeric($path)) - || strlen($path) === 0 + || 0 === strlen($path) || '/' !== $path[0] || strlen($path) > 1 && '/' === $path[strlen($path) - 1] || preg_match('-//|/\./|/\.\./-', $path) @@ -85,12 +85,12 @@ public static function assertValidAbsolutePath($path, $destination = false, $thr * engine. * * @param string $name The name to check - * @param bool $throw whether to throw an exception on validation errors. - * - * @throws RepositoryException if the name is invalid and $throw is true + * @param bool $throw whether to throw an exception on validation errors * * @return bool true if valid, false if not valid and $throw was false * + * @throws RepositoryException if the name is invalid and $throw is true + * * @see http://www.day.com/specs/jcr/2.0/3_Repository_Model.html#3.2.2%20Local%20Names */ public static function assertValidLocalName($name, $throw = true) @@ -117,23 +117,23 @@ public static function assertValidLocalName($name, $throw = true) * * Note: A well-formed input path implies a well-formed and normalized path returned. * - * @param string $path The path to normalize. + * @param string $path the path to normalize * @param bool $destination whether this is a destination path (by copy or - * move), meaning [] is not allowed in validation. + * move), meaning [] is not allowed in validation * @param bool $throw whether to throw an exception if validation fails or - * just to return false. + * just to return false + * + * @return string The normalized path or false if $throw was false and the path invalid * * @throws RepositoryException if the path is not a valid absolute path and * $throw is true - * - * @return string The normalized path or false if $throw was false and the path invalid */ public static function normalizePath($path, $destination = false, $throw = true) { if (!is_string($path) && !is_numeric($path)) { return self::error('Expected string but got '.gettype($path), $throw); } - if (strlen($path) === 0) { + if (0 === strlen($path)) { return self::error('Path must not be of zero length', $throw); } @@ -181,15 +181,15 @@ public static function normalizePath($path, $destination = false, $throw = true) * @param string $path A relative or absolute path * @param string $context The absolute path context to make $path absolute if needed * @param bool $destination whether this is a destination path (by copy or - * move), meaning [] is not allowed in validation. + * move), meaning [] is not allowed in validation * @param bool $throw whether to throw an exception if validation fails or - * just to return false. - * - * @throws RepositoryException if the path can not be made into a valid - * absolute path and $throw is true + * just to return false * * @return string The normalized, absolute path or false if $throw was * false and the path invalid + * + * @throws RepositoryException if the path can not be made into a valid + * absolute path and $throw is true */ public static function absolutizePath($path, $context, $destination = false, $throw = true) { @@ -199,7 +199,7 @@ public static function absolutizePath($path, $context, $destination = false, $th if (!is_string($context)) { return self::error('Expected string context but got '.gettype($context), $throw); } - if (strlen($path) === 0) { + if (0 === strlen($path)) { return self::error('Path must not be of zero length', $throw); } @@ -219,7 +219,7 @@ public static function absolutizePath($path, $context, $destination = false, $th * * @param string $path The absolute path to a node * @param string $context The absolute path to an ancestor of $path - * @param bool $throw Whether to throw exceptions on invalid data. + * @param bool $throw whether to throw exceptions on invalid data * * @return string The relative path from $context to $path */ @@ -261,9 +261,9 @@ public static function getParentPath($path) * * @param string $path a valid absolute path, like /content/jobs/data * - * @throws RepositoryException - * * @return string the name, that is the string after the last "/" + * + * @throws RepositoryException */ public static function getNodeName($path) { @@ -285,9 +285,9 @@ public static function getNodeName($path) * * @param string $path a valid absolute path * - * @throws RepositoryException - * * @return string The localname + * + * @throws RepositoryException */ public static function getLocalNodeName($path) { @@ -320,9 +320,9 @@ public static function getPathDepth($path) * @param string $msg the exception message to use in case of throw being true * @param bool $throw whether to throw the exception or return false * - * @throws RepositoryException - * * @return bool false + * + * @throws RepositoryException */ private static function error($msg, $throw) { diff --git a/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php b/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php index b9f2801e..b74f1af4 100644 --- a/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php +++ b/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php @@ -2,7 +2,6 @@ namespace PHPCR\Util\QOM; -use InvalidArgumentException; use PHPCR\Query\QOM; use PHPCR\Query\QOM\StaticOperandInterface; @@ -23,8 +22,6 @@ abstract class BaseQomToSqlQueryConverter /** * Instantiate the converter. - * - * @param BaseSqlGenerator $generator */ public function __construct(BaseSqlGenerator $generator) { @@ -37,8 +34,6 @@ public function __construct(BaseSqlGenerator $generator) * ['WHERE' Constraint] * ['ORDER BY' orderings]. * - * @param QOM\QueryObjectModelInterface $query - * * @return string */ public function convert(QOM\QueryObjectModelInterface $query) @@ -48,7 +43,7 @@ public function convert(QOM\QueryObjectModelInterface $query) $constraint = ''; $orderings = ''; - if ($query->getConstraint() !== null) { + if (null !== $query->getConstraint()) { $constraint = $this->convertConstraint($query->getConstraint()); } @@ -62,8 +57,6 @@ public function convert(QOM\QueryObjectModelInterface $query) /** * Convert a source. This is different between SQL1 and SQL2. * - * @param QOM\SourceInterface $source - * * @return string */ abstract protected function convertSource(QOM\SourceInterface $source); @@ -71,18 +64,12 @@ abstract protected function convertSource(QOM\SourceInterface $source); /** * Convert a constraint. This is different between SQL1 and SQL2. * - * @param QOM\ConstraintInterface $constraint - * * @return string */ abstract protected function convertConstraint(QOM\ConstraintInterface $constraint); /** * Convert dynamic operand. This is different between SQL1 and SQL2. - * - * @param QOM\DynamicOperandInterface $operand - * - * @return mixed */ abstract protected function convertDynamicOperand(QOM\DynamicOperandInterface $operand); @@ -90,8 +77,6 @@ abstract protected function convertDynamicOperand(QOM\DynamicOperandInterface $o * Selector ::= nodeTypeName ['AS' selectorName] * nodeTypeName ::= Name. * - * @param QOM\SelectorInterface $selector - * * @return string */ protected function convertSelector(QOM\SelectorInterface $selector) @@ -113,8 +98,6 @@ protected function convertSelector(QOM\SelectorInterface $selector) * GreaterThanOrEqualTo ::= '>=' * Like ::= 'LIKE' * - * @param QOM\ComparisonInterface $comparison - * * @return string */ protected function convertComparison(QOM\ComparisonInterface $comparison) @@ -136,8 +119,6 @@ protected function convertComparison(QOM\ComparisonInterface $comparison) * Note: The negation, 'NOT x IS NOT NULL' * can be written 'x IS NULL' * - * @param QOM\PropertyExistenceInterface $constraint - * * @return string */ protected function convertPropertyExistence(QOM\PropertyExistenceInterface $constraint) @@ -157,8 +138,6 @@ protected function convertPropertyExistence(QOM\PropertyExistenceInterface $cons * explicit specification of the selectorName * preceding the propertyName is optional. * - * @param QOM\FullTextSearchInterface $constraint - * * @return string */ protected function convertFullTextSearch(QOM\FullTextSearchInterface $constraint) @@ -187,7 +166,7 @@ protected function convertFullTextSearchExpression($expr) // however, without type checks, jackalope 1.0 got this wrong and returned a string. $literal = $expr; } else { - throw new InvalidArgumentException('Unknown full text search expression type '.get_class($expr)); + throw new \InvalidArgumentException('Unknown full text search expression type '.get_class($expr)); } $literal = $this->generator->evalFullText($literal); @@ -210,11 +189,9 @@ protected function convertFullTextSearchExpression($expr) * BindVariableValue ::= '$'bindVariableName * bindVariableName ::= Prefix * - * @param QOM\StaticOperandInterface $operand - * - * @throws InvalidArgumentException - * * @return string + * + * @throws \InvalidArgumentException */ protected function convertStaticOperand(QOM\StaticOperandInterface $operand) { @@ -226,14 +203,12 @@ protected function convertStaticOperand(QOM\StaticOperandInterface $operand) } // This should not happen, but who knows... - throw new InvalidArgumentException('Invalid operand'); + throw new \InvalidArgumentException('Invalid operand'); } /** * PropertyValue ::= [selectorName'.'] propertyName // If only one selector exists. * - * @param QOM\PropertyValueInterface $value - * * @return string */ protected function convertPropertyValue(QOM\PropertyValueInterface $value) @@ -297,8 +272,6 @@ protected function convertBindVariable($var) /** * Literal ::= CastLiteral | UncastLiteral. * - * @param mixed $literal - * * @return string */ protected function convertLiteral($literal) diff --git a/src/PHPCR/Util/QOM/BaseSqlGenerator.php b/src/PHPCR/Util/QOM/BaseSqlGenerator.php index e023fbdc..5226cd4d 100644 --- a/src/PHPCR/Util/QOM/BaseSqlGenerator.php +++ b/src/PHPCR/Util/QOM/BaseSqlGenerator.php @@ -2,7 +2,6 @@ namespace PHPCR\Util\QOM; -use DateTime; use PHPCR\PropertyType; use PHPCR\Query\QOM\QueryObjectModelConstantsInterface as Constants; use PHPCR\Util\ValueConverter; @@ -163,8 +162,6 @@ public function evalUpper($operand) /** * orderings ::= Ordering {',' Ordering}. * - * @param $orderings - * * @return string */ public function evalOrderings($orderings) @@ -172,7 +169,7 @@ public function evalOrderings($orderings) $sql = ''; foreach ($orderings as $ordering) { - if ($sql !== '') { + if ('' !== $sql) { $sql .= ', '; } @@ -185,9 +182,6 @@ public function evalOrderings($orderings) /** * Ordering ::= DynamicOperand [Order]. * - * @param $operand - * @param $order - * * @return string */ public function evalOrdering($operand, $order) @@ -200,8 +194,6 @@ public function evalOrdering($operand, $order) * Ascending ::= 'ASC' * Descending ::= 'DESC'. * - * @param $order - * * @return string */ public function evalOrder($order) @@ -220,8 +212,6 @@ public function evalOrder($order) * BindVariableValue ::= '$'bindVariableName * bindVariableName ::= Prefix. * - * @param $var - * * @return string */ public function evalBindVariable($var) @@ -241,8 +231,8 @@ public function evalBindVariable($var) public function evalFullText($string) { $illegalCharacters = [ - '!' => '\\!', '(' => '\\(', ':' => '\\:', '^' => '\\^', - '[' => '\\[', ']' => '\\]', '{' => '\\{', '}' => '\\}', + '!' => '\\!', '(' => '\\(', ':' => '\\:', '^' => '\\^', + '[' => '\\[', ']' => '\\]', '{' => '\\{', '}' => '\\}', '\"' => '\\\"', '?' => '\\?', "'" => "''", ]; @@ -252,13 +242,11 @@ public function evalFullText($string) /** * Literal ::= CastLiteral | UncastLiteral. * - * @param mixed $literal - * * @return string */ public function evalLiteral($literal) { - if ($literal instanceof DateTime) { + if ($literal instanceof \DateTime) { $string = $this->valueConverter->convertType($literal, PropertyType::STRING); return $this->evalCastLiteral($string, 'DATE'); @@ -316,8 +304,6 @@ abstract public function evalPath($path); * * With empty columns, SQL1 is different from SQL2 * - * @param $columns - * * @return string */ abstract public function evalColumns($columns); @@ -332,9 +318,6 @@ abstract public function evalColumns($columns); abstract public function evalColumn($selectorName, $propertyName = null, $colname = null); /** - * @param $selectorName - * @param $propertyName - * * @return string */ abstract public function evalPropertyExistence($selectorName, $propertyName); diff --git a/src/PHPCR/Util/QOM/NotSupportedConstraintException.php b/src/PHPCR/Util/QOM/NotSupportedConstraintException.php index 223e8507..39a543d0 100644 --- a/src/PHPCR/Util/QOM/NotSupportedConstraintException.php +++ b/src/PHPCR/Util/QOM/NotSupportedConstraintException.php @@ -2,15 +2,13 @@ namespace PHPCR\Util\QOM; -use RuntimeException; - /** * A helper exception to report not yet implemented functionality. * * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License */ -class NotSupportedConstraintException extends RuntimeException +class NotSupportedConstraintException extends \RuntimeException { /** * Create the exception with an explaining message. diff --git a/src/PHPCR/Util/QOM/NotSupportedOperandException.php b/src/PHPCR/Util/QOM/NotSupportedOperandException.php index bc7f317e..af6457ea 100644 --- a/src/PHPCR/Util/QOM/NotSupportedOperandException.php +++ b/src/PHPCR/Util/QOM/NotSupportedOperandException.php @@ -2,15 +2,13 @@ namespace PHPCR\Util\QOM; -use RuntimeException; - /** * A helper exception to report not yet implemented functionality. * * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License */ -class NotSupportedOperandException extends RuntimeException +class NotSupportedOperandException extends \RuntimeException { /** * Create the exception with an explaining message. diff --git a/src/PHPCR/Util/QOM/QomToSql1QueryConverter.php b/src/PHPCR/Util/QOM/QomToSql1QueryConverter.php index ae591b59..4c75be44 100644 --- a/src/PHPCR/Util/QOM/QomToSql1QueryConverter.php +++ b/src/PHPCR/Util/QOM/QomToSql1QueryConverter.php @@ -2,7 +2,6 @@ namespace PHPCR\Util\QOM; -use InvalidArgumentException; use PHPCR\Query\QOM; /** @@ -16,11 +15,9 @@ class QomToSql1QueryConverter extends BaseQomToSqlQueryConverter /** * Source ::= Selector. * - * @param QOM\SourceInterface $source - * - * @throws InvalidArgumentException - * * @return string + * + * @throws \InvalidArgumentException */ protected function convertSource(QOM\SourceInterface $source) { @@ -28,7 +25,7 @@ protected function convertSource(QOM\SourceInterface $source) return $this->convertSelector($source); } - throw new InvalidArgumentException('Invalid Source'); + throw new \InvalidArgumentException('Invalid Source'); } /** @@ -40,12 +37,10 @@ protected function convertSource(QOM\SourceInterface $source) * Or ::= constraint1 'OR' constraint2 * Not ::= 'NOT' Constraint * - * @param QOM\ConstraintInterface $constraint + * @return string * - * @throws InvalidArgumentException + * @throws \InvalidArgumentException * @throws NotSupportedConstraintException - * - * @return string */ protected function convertConstraint(QOM\ConstraintInterface $constraint) { @@ -96,7 +91,7 @@ protected function convertConstraint(QOM\ConstraintInterface $constraint) // This should not happen, but who knows... $class = get_class($constraint); - throw new InvalidArgumentException("Invalid operand: $class"); + throw new \InvalidArgumentException("Invalid operand: $class"); } /** @@ -105,12 +100,10 @@ protected function convertConstraint(QOM\ConstraintInterface $constraint) * LowerCase ::= 'LOWER(' DynamicOperand ')' * UpperCase ::= 'UPPER(' DynamicOperand ')' * - * @param QOM\DynamicOperandInterface $operand + * @return string * * @throws NotSupportedOperandException - * @throws InvalidArgumentException - * - * @return string + * @throws \InvalidArgumentException */ protected function convertDynamicOperand(QOM\DynamicOperandInterface $operand) { @@ -147,6 +140,6 @@ protected function convertDynamicOperand(QOM\DynamicOperandInterface $operand) } // This should not happen, but who knows... - throw new InvalidArgumentException('Invalid operand'); + throw new \InvalidArgumentException('Invalid operand'); } } diff --git a/src/PHPCR/Util/QOM/QomToSql2QueryConverter.php b/src/PHPCR/Util/QOM/QomToSql2QueryConverter.php index fdef9c07..b5dd984c 100644 --- a/src/PHPCR/Util/QOM/QomToSql2QueryConverter.php +++ b/src/PHPCR/Util/QOM/QomToSql2QueryConverter.php @@ -2,7 +2,6 @@ namespace PHPCR\Util\QOM; -use InvalidArgumentException; use PHPCR\Query\QOM; /** @@ -16,11 +15,9 @@ class QomToSql2QueryConverter extends BaseQomToSqlQueryConverter /** * Source ::= Selector | Join. * - * @param QOM\SourceInterface $source - * - * @throws InvalidArgumentException - * * @return string + * + * @throws \InvalidArgumentException */ protected function convertSource(QOM\SourceInterface $source) { @@ -31,7 +28,7 @@ protected function convertSource(QOM\SourceInterface $source) return $this->convertJoin($source); } - throw new InvalidArgumentException('Invalid Source'); + throw new \InvalidArgumentException('Invalid Source'); } /** @@ -45,8 +42,6 @@ protected function convertSource(QOM\SourceInterface $source) * LeftOuter ::= 'LEFT OUTER' * RightOuter ::= 'RIGHT OUTER' * - * @param QOM\JoinInterface $join - * * @return string */ protected function convertJoin(QOM\JoinInterface $join) @@ -68,11 +63,9 @@ protected function convertJoin(QOM\JoinInterface $join) * ChildNodeJoinCondition | * DescendantNodeJoinCondition. * - * @param QOM\JoinConditionInterface $condition - * - * @throws InvalidArgumentException - * * @return string + * + * @throws \InvalidArgumentException */ protected function convertJoinCondition(QOM\JoinConditionInterface $condition) { @@ -90,7 +83,7 @@ protected function convertJoinCondition(QOM\JoinConditionInterface $condition) } // This should not happen, but who knows... - throw new InvalidArgumentException('Invalid operand'); + throw new \InvalidArgumentException('Invalid operand'); } /** @@ -101,8 +94,6 @@ protected function convertJoinCondition(QOM\JoinConditionInterface $condition) * property1Name ::= propertyName * property2Name ::= propertyName. * - * @param QOM\EquiJoinConditionInterface $condition - * * @return string */ protected function convertEquiJoinCondition(QOM\EquiJoinConditionInterface $condition) @@ -126,8 +117,6 @@ protected function convertEquiJoinCondition(QOM\EquiJoinConditionInterface $cond * [',' selector2Path] ')' * selector2Path ::= Path. * - * @param QOM\SameNodeJoinConditionInterface $condition - * * @return string */ protected function convertSameNodeJoinCondition(QOM\SameNodeJoinConditionInterface $condition) @@ -150,8 +139,6 @@ protected function convertSameNodeJoinCondition(QOM\SameNodeJoinConditionInterfa * childSelectorName ::= selectorName * parentSelectorName ::= selectorName. * - * @param QOM\ChildNodeJoinConditionInterface $condition - * * @return string */ protected function convertChildNodeJoinCondition(QOM\ChildNodeJoinConditionInterface $condition) @@ -173,8 +160,6 @@ protected function convertChildNodeJoinCondition(QOM\ChildNodeJoinConditionInter * descendantSelectorName ::= selectorName * ancestorSelectorName ::= selectorName. * - * @param QOM\DescendantNodeJoinConditionInterface $condition - * * @return string */ protected function convertDescendantNodeJoinCondition(QOM\DescendantNodeJoinConditionInterface $condition) @@ -210,11 +195,9 @@ protected function convertDescendantNodeJoinCondition(QOM\DescendantNodeJoinCond * // If only one selector exists in this query, explicit * specification of the selectorName is optional * - * @param QOM\ConstraintInterface $constraint - * - * @throws InvalidArgumentException - * * @return string + * + * @throws \InvalidArgumentException */ protected function convertConstraint(QOM\ConstraintInterface $constraint) { @@ -273,7 +256,7 @@ protected function convertConstraint(QOM\ConstraintInterface $constraint) } // This should not happen, but who knows... - throw new InvalidArgumentException('Invalid operand: '.get_class($constraint)); + throw new \InvalidArgumentException('Invalid operand: '.get_class($constraint)); } /** @@ -288,11 +271,9 @@ protected function convertConstraint(QOM\ConstraintInterface $constraint) * LowerCase ::= 'LOWER(' DynamicOperand ')' * UpperCase ::= 'UPPER(' DynamicOperand ')' * - * @param QOM\DynamicOperandInterface $operand - * - * @throws InvalidArgumentException - * * @return string + * + * @throws \InvalidArgumentException */ protected function convertDynamicOperand(QOM\DynamicOperandInterface $operand) { @@ -345,6 +326,6 @@ protected function convertDynamicOperand(QOM\DynamicOperandInterface $operand) } // This should not happen, but who knows... - throw new InvalidArgumentException('Invalid operand'); + throw new \InvalidArgumentException('Invalid operand'); } } diff --git a/src/PHPCR/Util/QOM/QueryBuilder.php b/src/PHPCR/Util/QOM/QueryBuilder.php index 23c6c125..eb6211b8 100644 --- a/src/PHPCR/Util/QOM/QueryBuilder.php +++ b/src/PHPCR/Util/QOM/QueryBuilder.php @@ -2,7 +2,6 @@ namespace PHPCR\Util\QOM; -use InvalidArgumentException; use PHPCR\Query\QOM\ColumnInterface; use PHPCR\Query\QOM\ConstraintInterface; use PHPCR\Query\QOM\DynamicOperandInterface; @@ -14,7 +13,6 @@ use PHPCR\Query\QOM\SourceInterface; use PHPCR\Query\QueryInterface; use PHPCR\Query\QueryResultInterface; -use RuntimeException; /** * QueryBuilder class is responsible for dynamically create QOM queries. @@ -28,8 +26,8 @@ class QueryBuilder { /** The builder states. */ - const STATE_DIRTY = 0; - const STATE_CLEAN = 1; + public const STATE_DIRTY = 0; + public const STATE_CLEAN = 1; /** * @var int The state of the query object. Can be dirty or clean. @@ -42,14 +40,14 @@ class QueryBuilder private $qomFactory; /** - * @var int The maximum number of results to retrieve. + * @var int the maximum number of results to retrieve */ - private $firstResult = null; + private $firstResult; /** - * @var int The maximum number of results to retrieve. + * @var int the maximum number of results to retrieve */ - private $maxResults = null; + private $maxResults; /** * @var array with the orderings that determine the order of the result @@ -57,36 +55,34 @@ class QueryBuilder private $orderings = []; /** - * @var ConstraintInterface to apply to the query. + * @var ConstraintInterface to apply to the query */ - private $constraint = null; + private $constraint; /** - * @var array with the columns to be selected. + * @var array with the columns to be selected */ private $columns = []; /** - * @var SourceInterface source of the query. + * @var SourceInterface source of the query */ - private $source = null; + private $source; /** * QOM tree. * * @var QueryObjectModelInterface */ - private $query = null; + private $query; /** - * @var array The query parameters. + * @var array the query parameters */ private $params = []; /** * Initializes a new QueryBuilder. - * - * @param QueryObjectModelFactoryInterface $qomFactory */ public function __construct(QueryObjectModelFactoryInterface $qomFactory) { @@ -99,9 +95,9 @@ public function __construct(QueryObjectModelFactoryInterface $qomFactory) * @param string $statement the statement in the specified language * @param string $language the query language * - * @throws InvalidArgumentException + * @return QueryBuilder this QueryBuilder instance * - * @return QueryBuilder This QueryBuilder instance. + * @throws \InvalidArgumentException */ public function setFromQuery($statement, $language) { @@ -111,7 +107,7 @@ public function setFromQuery($statement, $language) } if (!$statement instanceof QueryObjectModelInterface) { - throw new InvalidArgumentException("Language '$language' not supported"); + throw new \InvalidArgumentException("Language '$language' not supported"); } $this->state = self::STATE_DIRTY; @@ -144,9 +140,9 @@ public function qomf() /** * sets the position of the first result to retrieve (the "offset"). * - * @param int $firstResult The First result to return. + * @param int $firstResult the First result to return * - * @return QueryBuilder This QueryBuilder instance. + * @return QueryBuilder this QueryBuilder instance */ public function setFirstResult($firstResult) { @@ -159,7 +155,7 @@ public function setFirstResult($firstResult) * Gets the position of the first result the query object was set to retrieve (the "offset"). * Returns NULL if {@link setFirstResult} was not applied to this QueryBuilder. * - * @return int The position of the first result. + * @return int the position of the first result */ public function getFirstResult() { @@ -169,9 +165,9 @@ public function getFirstResult() /** * Sets the maximum number of results to retrieve (the "limit"). * - * @param int $maxResults The maximum number of results to retrieve. + * @param int $maxResults the maximum number of results to retrieve * - * @return QueryBuilder This QueryBuilder instance. + * @return QueryBuilder this QueryBuilder instance */ public function setMaxResults($maxResults) { @@ -184,7 +180,7 @@ public function setMaxResults($maxResults) * Gets the maximum number of results the query object was set to retrieve (the "limit"). * Returns NULL if {@link setMaxResults} was not applied to this query builder. * - * @return int Maximum number of results. + * @return int maximum number of results */ public function getMaxResults() { @@ -194,7 +190,7 @@ public function getMaxResults() /** * Gets the array of orderings. * - * @return OrderingInterface[] Orderings to apply. + * @return OrderingInterface[] orderings to apply */ public function getOrderings() { @@ -204,23 +200,23 @@ public function getOrderings() /** * Adds an ordering to the query results. * - * @param DynamicOperandInterface $sort The ordering expression. - * @param string $order The ordering direction. + * @param DynamicOperandInterface $sort the ordering expression + * @param string $order the ordering direction * - * @throws InvalidArgumentException + * @return QueryBuilder this QueryBuilder instance * - * @return QueryBuilder This QueryBuilder instance. + * @throws \InvalidArgumentException */ public function addOrderBy(DynamicOperandInterface $sort, $order = 'ASC') { $order = strtoupper($order); if (!in_array($order, ['ASC', 'DESC'])) { - throw new InvalidArgumentException('Order must be one of "ASC" or "DESC"'); + throw new \InvalidArgumentException('Order must be one of "ASC" or "DESC"'); } $this->state = self::STATE_DIRTY; - if ($order === 'DESC') { + if ('DESC' === $order) { $ordering = $this->qomFactory->descending($sort); } else { $ordering = $this->qomFactory->ascending($sort); @@ -234,10 +230,10 @@ public function addOrderBy(DynamicOperandInterface $sort, $order = 'ASC') * Specifies an ordering for the query results. * Replaces any previously specified orderings, if any. * - * @param DynamicOperandInterface $sort The ordering expression. - * @param string $order The ordering direction. + * @param DynamicOperandInterface $sort the ordering expression + * @param string $order the ordering direction * - * @return QueryBuilder This QueryBuilder instance. + * @return QueryBuilder this QueryBuilder instance */ public function orderBy(DynamicOperandInterface $sort, $order = 'ASC') { @@ -251,9 +247,7 @@ public function orderBy(DynamicOperandInterface $sort, $order = 'ASC') * Specifies one restriction (may be simple or composed). * Replaces any previously specified restrictions, if any. * - * @param ConstraintInterface $constraint - * - * @return QueryBuilder This QueryBuilder instance. + * @return QueryBuilder this QueryBuilder instance */ public function where(ConstraintInterface $constraint) { @@ -286,9 +280,7 @@ public function getConstraint() * If there is no previous constraint then it will simply store the * provided one * - * @param ConstraintInterface $constraint - * - * @return QueryBuilder This QueryBuilder instance. + * @return QueryBuilder this QueryBuilder instance */ public function andWhere(ConstraintInterface $constraint) { @@ -316,9 +308,7 @@ public function andWhere(ConstraintInterface $constraint) * If there is no previous constraint then it will simply store the * provided one * - * @param ConstraintInterface $constraint - * - * @return QueryBuilder This QueryBuilder instance. + * @return QueryBuilder this QueryBuilder instance */ public function orWhere(ConstraintInterface $constraint) { @@ -348,7 +338,7 @@ public function getColumns() * * @param ColumnInterface[] $columns The columns to be selected * - * @return QueryBuilder This QueryBuilder instance. + * @return QueryBuilder this QueryBuilder instance */ public function setColumns(array $columns) { @@ -365,7 +355,7 @@ public function setColumns(array $columns) * @param string $propertyName * @param string $columnName * - * @return QueryBuilder This QueryBuilder instance. + * @return QueryBuilder this QueryBuilder instance */ public function select($selectorName, $propertyName, $columnName = null) { @@ -382,7 +372,7 @@ public function select($selectorName, $propertyName, $columnName = null) * @param string $propertyName * @param string $columnName * - * @return QueryBuilder This QueryBuilder instance. + * @return QueryBuilder this QueryBuilder instance */ public function addSelect($selectorName, $propertyName, $columnName = null) { @@ -397,9 +387,7 @@ public function addSelect($selectorName, $propertyName, $columnName = null) * Sets the default Selector or the node-tuple Source. Can be a selector * or a join. * - * @param SourceInterface $source - * - * @return QueryBuilder This QueryBuilder instance. + * @return QueryBuilder this QueryBuilder instance */ public function from(SourceInterface $source) { @@ -412,7 +400,7 @@ public function from(SourceInterface $source) /** * Gets the default Selector. * - * @return SourceInterface The default selector. + * @return SourceInterface the default selector */ public function getSource() { @@ -422,12 +410,9 @@ public function getSource() /** * Performs an inner join between the stored source and the supplied source. * - * @param SourceInterface $rightSource - * @param JoinConditionInterface $joinCondition + * @return QueryBuilder this QueryBuilder instance * - * @throws RuntimeException if there is not an existing source. - * - * @return QueryBuilder This QueryBuilder instance. + * @throws \RuntimeException if there is not an existing source */ public function join(SourceInterface $rightSource, JoinConditionInterface $joinCondition) { @@ -437,12 +422,9 @@ public function join(SourceInterface $rightSource, JoinConditionInterface $joinC /** * Performs an inner join between the stored source and the supplied source. * - * @param SourceInterface $rightSource - * @param JoinConditionInterface $joinCondition - * - * @throws RuntimeException if there is not an existing source. + * @return QueryBuilder this QueryBuilder instance * - * @return QueryBuilder This QueryBuilder instance. + * @throws \RuntimeException if there is not an existing source */ public function innerJoin(SourceInterface $rightSource, JoinConditionInterface $joinCondition) { @@ -452,12 +434,9 @@ public function innerJoin(SourceInterface $rightSource, JoinConditionInterface $ /** * Performs an left outer join between the stored source and the supplied source. * - * @param SourceInterface $rightSource - * @param JoinConditionInterface $joinCondition + * @return QueryBuilder this QueryBuilder instance * - * @throws RuntimeException if there is not an existing source. - * - * @return QueryBuilder This QueryBuilder instance. + * @throws \RuntimeException if there is not an existing source */ public function leftJoin(SourceInterface $rightSource, JoinConditionInterface $joinCondition) { @@ -467,12 +446,9 @@ public function leftJoin(SourceInterface $rightSource, JoinConditionInterface $j /** * Performs a right outer join between the stored source and the supplied source. * - * @param SourceInterface $rightSource - * @param JoinConditionInterface $joinCondition - * - * @throws RuntimeException if there is not an existing source. + * @return QueryBuilder this QueryBuilder instance * - * @return QueryBuilder This QueryBuilder instance. + * @throws \RuntimeException if there is not an existing source */ public function rightJoin(SourceInterface $rightSource, JoinConditionInterface $joinCondition) { @@ -482,18 +458,16 @@ public function rightJoin(SourceInterface $rightSource, JoinConditionInterface $ /** * Performs an join between the stored source and the supplied source. * - * @param SourceInterface $rightSource - * @param string $joinType as specified in PHPCR\Query\QOM\QueryObjectModelConstantsInterface - * @param JoinConditionInterface $joinCondition + * @param string $joinType as specified in PHPCR\Query\QOM\QueryObjectModelConstantsInterface * - * @throws RuntimeException if there is not an existing source. + * @return QueryBuilder this QueryBuilder instance * - * @return QueryBuilder This QueryBuilder instance. + * @throws \RuntimeException if there is not an existing source */ public function joinWithType(SourceInterface $rightSource, $joinType, JoinConditionInterface $joinCondition) { if (!$this->source) { - throw new RuntimeException('Cannot perform a join without a previous call to from'); + throw new \RuntimeException('Cannot perform a join without a previous call to from'); } $this->state = self::STATE_DIRTY; @@ -509,7 +483,7 @@ public function joinWithType(SourceInterface $rightSource, $joinType, JoinCondit */ public function getQuery() { - if ($this->query !== null && $this->state === self::STATE_CLEAN) { + if (null !== $this->query && self::STATE_CLEAN === $this->state) { return $this->query; } @@ -534,7 +508,7 @@ public function getQuery() */ public function execute() { - if ($this->query === null || $this->state === self::STATE_DIRTY) { + if (null === $this->query || self::STATE_DIRTY === $this->state) { $this->query = $this->getQuery(); } @@ -548,10 +522,10 @@ public function execute() /** * Sets a query parameter for the query being constructed. * - * @param string $key The parameter name. - * @param mixed $value The parameter value. + * @param string $key the parameter name + * @param mixed $value the parameter value * - * @return QueryBuilder This QueryBuilder instance. + * @return QueryBuilder this QueryBuilder instance */ public function setParameter($key, $value) { @@ -563,9 +537,9 @@ public function setParameter($key, $value) /** * Gets a (previously set) query parameter of the query being constructed. * - * @param string $key The key (name) of the bound parameter. + * @param string $key the key (name) of the bound parameter * - * @return mixed The value of the bound parameter. + * @return mixed the value of the bound parameter */ public function getParameter($key) { @@ -575,9 +549,9 @@ public function getParameter($key) /** * Sets a collection of query parameters for the query being constructed. * - * @param array $params The query parameters to set. + * @param array $params the query parameters to set * - * @return QueryBuilder This QueryBuilder instance. + * @return QueryBuilder this QueryBuilder instance */ public function setParameters(array $params) { @@ -589,7 +563,7 @@ public function setParameters(array $params) /** * Gets all defined query parameters for the query being constructed. * - * @return array The currently defined query parameters. + * @return array the currently defined query parameters */ public function getParameters() { diff --git a/src/PHPCR/Util/QOM/Sql1Generator.php b/src/PHPCR/Util/QOM/Sql1Generator.php index 6c9927a2..bea5d88c 100644 --- a/src/PHPCR/Util/QOM/Sql1Generator.php +++ b/src/PHPCR/Util/QOM/Sql1Generator.php @@ -27,13 +27,11 @@ public function evalSelector($nodeTypeName, $selectorName = null) /** * Helper method to emulate descendant with LIKE query on path property. * - * @param $path - * * @return string */ protected function getPathForDescendantQuery($path) { - if ($path === '/') { + if ('/' === $path) { $sql1 = '/%'; } else { $path = trim($path, "\"'/"); @@ -81,7 +79,7 @@ public function evalDescendantNode($path, $selectorName = null) * propertyName 'IS NOT NULL'. * * @param string $selectorName declared to simplifiy interface - as there - * are no joins in SQL1 there is no need for a selector. + * are no joins in SQL1 there is no need for a selector * @param string $propertyName * * @return string @@ -117,21 +115,19 @@ public function evalFullTextSearch($selectorName, $searchExpression, $propertyNa /** * columns ::= (Column ',' {Column}) | '*'. * - * @param $columns - * * @return string */ public function evalColumns($columns) { if ((!is_array($columns) && !$columns instanceof \Countable) - || count($columns) === 0 + || 0 === count($columns) ) { return 's'; } $sql1 = ''; foreach ($columns as $column) { - if ($sql1 !== '') { + if ('' !== $sql1) { $sql1 .= ', '; } diff --git a/src/PHPCR/Util/QOM/Sql2Generator.php b/src/PHPCR/Util/QOM/Sql2Generator.php index 45fd7751..a819c6c5 100644 --- a/src/PHPCR/Util/QOM/Sql2Generator.php +++ b/src/PHPCR/Util/QOM/Sql2Generator.php @@ -220,9 +220,6 @@ public function evalDescendantNode($path, $selectorName = null) * selector exists in * this query. * - * @param $selectorName - * @param $propertyName - * * @return string */ public function evalPropertyExistence($selectorName, $propertyName) @@ -313,7 +310,7 @@ public function evalFullTextSearchScore($selectorValue = null) public function evalPropertyValue($propertyName, $selectorName = null) { $sql2 = null !== $selectorName ? $this->addBracketsIfNeeded($selectorName).'.' : ''; - if ('*' !== $propertyName && substr($propertyName, 0, 1) !== '[') { + if ('*' !== $propertyName && '[' !== substr($propertyName, 0, 1)) { $propertyName = "[$propertyName]"; } $sql2 .= $propertyName; @@ -324,21 +321,19 @@ public function evalPropertyValue($propertyName, $selectorName = null) /** * columns ::= (Column ',' {Column}) | '*'. * - * @param $columns - * * @return string */ public function evalColumns($columns) { if ((!is_array($columns) && !$columns instanceof \Countable) - || count($columns) === 0 + || 0 === count($columns) ) { return '*'; } $sql2 = ''; foreach ($columns as $column) { - if ($sql2 !== '') { + if ('' !== $sql2) { $sql2 .= ', '; } @@ -394,7 +389,7 @@ public function evalPath($path) } $sql2 = $path; // only ensure proper quoting if the user did not quote himself, we trust him to get it right if he did. - if (strpos($path, '[') !== 0 && substr($path, -1) !== ']') { + if (0 !== strpos($path, '[') && ']' !== substr($path, -1)) { if (false !== strpos($sql2, ' ') || false !== strpos($sql2, '.')) { $sql2 = '"'.$sql2.'"'; } @@ -423,8 +418,8 @@ public function evalCastLiteral($literal, $type) */ private function addBracketsIfNeeded($selector) { - if (substr($selector, 0, 1) !== '[' - && substr($selector, -1) !== ']' + if ('[' !== substr($selector, 0, 1) + && ']' !== substr($selector, -1) && false !== strpos($selector, ':') ) { return "[$selector]"; diff --git a/src/PHPCR/Util/QOM/Sql2Scanner.php b/src/PHPCR/Util/QOM/Sql2Scanner.php index a4c41078..2bc91f7d 100644 --- a/src/PHPCR/Util/QOM/Sql2Scanner.php +++ b/src/PHPCR/Util/QOM/Sql2Scanner.php @@ -70,8 +70,8 @@ public function lookupNextToken($offset = 0) public function fetchNextToken() { $token = $this->lookupNextToken(); - if ($token !== '') { - $this->curpos += 1; + if ('' !== $token) { + ++$this->curpos; } return trim($token); @@ -150,17 +150,17 @@ protected function scan($sql2) $isEscaped = false; $escapedQuotesCount = 0; $splitString = \str_split($sql2); - for ($index = 0; $index < count($splitString); $index++) { + for ($index = 0; $index < count($splitString); ++$index) { $character = $splitString[$index]; if (!$stringStartCharacter && in_array($character, [' ', "\t", "\n", "\r"], true)) { - if ($currentToken !== '') { + if ('' !== $currentToken) { $tokens[] = $currentToken; } $currentToken = ''; continue; } if (!$stringStartCharacter && in_array($character, $tokenEndChars, true)) { - if ($currentToken !== '') { + if ('' !== $currentToken) { $tokens[] = $currentToken; } $tokens[] = $character; @@ -169,8 +169,8 @@ protected function scan($sql2) } // Handling the squared brackets in queries - if (!$isEscaped && $character === '[') { - if ($currentToken !== '') { + if (!$isEscaped && '[' === $character) { + if ('' !== $currentToken) { $tokens[] = $currentToken; } $stringSize = $this->parseBrackets($sql2, $index); @@ -188,13 +188,13 @@ protected function scan($sql2) // Checking if the previous or next value is a ' to handle the weird SQL strings // This will not check if the amount of quotes is even $nextCharacter = $splitString[$index + 1] ?? ''; - if ($character === "'" && $nextCharacter === "'") { + if ("'" === $character && "'" === $nextCharacter) { $isEscaped = true; - $escapedQuotesCount++; + ++$escapedQuotesCount; continue; } // If the escaped quotes are not paired up. eg. "I'''m cool" would be a parsing error - if ($escapedQuotesCount % 2 == 1 && $stringStartCharacter !== "'") { + if (1 == $escapedQuotesCount % 2 && "'" !== $stringStartCharacter) { throw new InvalidQueryException("Syntax error: Number of single quotes to be even: $currentToken"); } if ($character === $stringStartCharacter) { @@ -213,9 +213,9 @@ protected function scan($sql2) } } } - $isEscaped = $character === '\\'; + $isEscaped = '\\' === $character; } - if ($currentToken !== '') { + if ('' !== $currentToken) { $tokens[] = $currentToken; } diff --git a/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php b/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php index 76aca66b..7e58eb0e 100644 --- a/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php +++ b/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php @@ -2,10 +2,6 @@ namespace PHPCR\Util\QOM; -use DateTime; -use Exception; -use InvalidArgumentException; -use LogicException; use PHPCR\PropertyType; use PHPCR\Query\InvalidQueryException; use PHPCR\Query\QOM\ChildNodeJoinConditionInterface; @@ -67,7 +63,7 @@ class Sql2ToQomQueryConverter * * @var string|array */ - protected $implicitSelectorName = null; + protected $implicitSelectorName; /** * @var ValueConverter @@ -77,8 +73,7 @@ class Sql2ToQomQueryConverter /** * Instantiate a converter. * - * @param QueryObjectModelFactoryInterface $factory - * @param ValueConverter $valueConverter To override default converter. + * @param ValueConverter $valueConverter to override default converter */ public function __construct(QueryObjectModelFactoryInterface $factory, ValueConverter $valueConverter = null) { @@ -92,9 +87,9 @@ public function __construct(QueryObjectModelFactoryInterface $factory, ValueConv * * @param string $sql2 * - * @throws InvalidQueryException - * * @return QueryObjectModelInterface + * + * @throws InvalidQueryException */ public function parse($sql2) { @@ -106,7 +101,7 @@ public function parse($sql2) $constraint = null; $orderings = []; - while ($this->scanner->lookupNextToken() !== '') { + while ('' !== $this->scanner->lookupNextToken()) { switch (strtoupper($this->scanner->lookupNextToken())) { case 'SELECT': $this->scanner->expectToken('SELECT'); @@ -213,9 +208,9 @@ protected function parseJoin(SourceInterface $leftSelector) /** * 6.7.6. Join type. * - * @throws InvalidQueryException - * * @return string + * + * @throws InvalidQueryException */ protected function parseJoinType() { @@ -352,18 +347,18 @@ protected function parseDescendantNodeJoinCondition() * @param ConstraintInterface $lhs Left hand side * @param int $minprec Precedence * - * @throws Exception - * * @return ConstraintInterface + * + * @throws \Exception */ protected function parseConstraint($lhs = null, $minprec = 0) { - if ($lhs === null) { + if (null === $lhs) { $lhs = $this->parsePrimaryConstraint(); } $opprec = [ - 'OR' => 1, + 'OR' => 1, 'AND' => 2, ]; @@ -391,7 +386,7 @@ protected function parseConstraint($lhs = null, $minprec = 0) // this only happens if the operator is // in the $opprec-array but there is no // "elseif"-branch here for this operator. - throw new Exception("Internal error: No action is defined for operator '$op'"); + throw new \Exception("Internal error: No action is defined for operator '$op'"); } $op = strtoupper($this->scanner->lookupNextToken()); @@ -442,14 +437,14 @@ protected function parsePrimaryConstraint() } } - if ($constraint === null) { + if (null === $constraint) { // It's not a property existence neither, then it's a comparison $constraint = $this->parseComparison(); } } // No constraint read, - if ($constraint === null) { + if (null === $constraint) { throw new InvalidQueryException("Syntax error: constraint expected in '{$this->sql2}'"); } @@ -471,9 +466,9 @@ protected function parseNot() /** * 6.7.16 Comparison. * - * @throws InvalidQueryException - * * @return ComparisonInterface + * + * @throws InvalidQueryException */ protected function parseComparison() { @@ -623,7 +618,7 @@ protected function parseDescendantNode() protected function parsePath() { $path = $this->parseLiteralValue(); - if (substr($path, 0, 1) === '[' && substr($path, -1) === ']') { + if ('[' === substr($path, 0, 1) && ']' === substr($path, -1)) { $path = substr($path, 1, -1); } @@ -640,7 +635,7 @@ protected function parsePath() protected function parseStaticOperand() { $token = $this->scanner->lookupNextToken(); - if (substr($token, 0, 1) === '$') { + if ('$' === substr($token, 0, 1)) { return $this->factory->bindVariable(substr($this->scanner->fetchNextToken(), 1)); } @@ -751,7 +746,7 @@ protected function parsePropertyValue() protected function parseCastLiteral($token) { if (!$this->scanner->tokenIs($token, 'CAST')) { - throw new LogicException('parseCastLiteral when not a CAST'); + throw new \LogicException('parseCastLiteral when not a CAST'); } $this->scanner->expectToken('('); @@ -772,7 +767,7 @@ protected function parseCastLiteral($token) try { $typeValue = PropertyType::valueFromName($type); - } catch (InvalidArgumentException $e) { + } catch (\InvalidArgumentException $e) { throw new InvalidQueryException("Syntax error: attempting to cast to an invalid type '$type'"); } @@ -780,7 +775,7 @@ protected function parseCastLiteral($token) try { $token = $this->valueConverter->convertType($token, $typeValue, PropertyType::STRING); - } catch (Exception $e) { + } catch (\Exception $e) { throw new InvalidQueryException("Syntax error: attempting to cast string '$token' to type '$type'"); } @@ -790,8 +785,6 @@ protected function parseCastLiteral($token) /** * 6.7.34 Literal * Parse an SQL2 literal value. - * - * @return mixed */ protected function parseLiteralValue() { @@ -812,13 +805,13 @@ protected function parseLiteralValue() if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $token)) { $token .= ' 00:00:00'; } - $token = DateTime::createFromFormat('Y-m-d H:i:s', $token); + $token = \DateTime::createFromFormat('Y-m-d H:i:s', $token); } } elseif (is_numeric($token)) { - $token = strpos($token, '.') === false ? (int) $token : (float) $token; - } elseif ($token === 'true') { + $token = false === strpos($token, '.') ? (int) $token : (float) $token; + } elseif ('true' === $token) { $token = true; - } elseif ($token === 'false') { + } elseif ('false' === $token) { $token = false; } @@ -883,7 +876,7 @@ protected function parseOrdering() protected function scanColumns() { // Wildcard - if ($this->scanner->lookupNextToken() === '*') { + if ('*' === $this->scanner->lookupNextToken()) { $this->scanner->fetchNextToken(); return []; @@ -896,7 +889,7 @@ protected function scanColumns() $columns[] = $this->scanColumn(); // Are there more columns? - if ($this->scanner->lookupNextToken() !== ',') { + if (',' !== $this->scanner->lookupNextToken()) { $hasNext = false; } else { $this->scanner->fetchNextToken(); @@ -933,7 +926,7 @@ private function fetchTokenWithoutBrackets() { $token = $this->scanner->fetchNextToken(); - if (substr($token, 0, 1) === '[' && substr($token, -1) === ']') { + if ('[' === substr($token, 0, 1) && ']' === substr($token, -1)) { // Remove brackets around the selector name $token = substr($token, 1, -1); } @@ -944,7 +937,7 @@ private function fetchTokenWithoutBrackets() /** * Parse something that is expected to be a property identifier. * - * @param bool $checkSelector whether we need to ensure a valid selector. + * @param bool $checkSelector whether we need to ensure a valid selector * * @return array with selectorName and propertyName. If no selectorName is * specified, defaults to $this->defaultSelectorName @@ -954,7 +947,7 @@ private function parseIdentifier($checkSelector = true) $token = $this->fetchTokenWithoutBrackets(); // selector.property - if ($this->scanner->lookupNextToken() === '.') { + if ('.' === $this->scanner->lookupNextToken()) { $selectorName = $token; $this->scanner->fetchNextToken(); $propertyName = $this->fetchTokenWithoutBrackets(); @@ -998,10 +991,10 @@ protected function updateImplicitSelectorName($selectorName) * * @param string|null $parsedName * - * @throws InvalidQueryException if there was no explicit selector and - * there is more than one selector available. - * * @return string the selector to use + * + * @throws InvalidQueryException if there was no explicit selector and + * there is more than one selector available */ protected function ensureSelectorName($parsedName) { @@ -1044,7 +1037,7 @@ protected function scanColumn() /** * Build a single SQL2 column definition. * - * @param array $data with selector name, property name and column name. + * @param array $data with selector name, property name and column name * * @return ColumnInterface */ diff --git a/src/PHPCR/Util/TraversingItemVisitor.php b/src/PHPCR/Util/TraversingItemVisitor.php index 713df4c8..2890c555 100644 --- a/src/PHPCR/Util/TraversingItemVisitor.php +++ b/src/PHPCR/Util/TraversingItemVisitor.php @@ -7,7 +7,6 @@ use PHPCR\NodeInterface; use PHPCR\PropertyInterface; use PHPCR\RepositoryException; -use SplQueue; /** * An implementation of ItemVisitor. @@ -51,14 +50,14 @@ abstract class TraversingItemVisitor implements ItemVisitorInterface /** * Queue used to implement breadth-first traversal. * - * @var SplQueue + * @var \SplQueue */ protected $currentQueue; /** * Queue used to implement breadth-first traversal. * - * @var SplQueue + * @var \SplQueue */ protected $nextQueue; @@ -74,11 +73,11 @@ abstract class TraversingItemVisitor implements ItemVisitorInterface * * @param bool $breadthFirst if $breadthFirst is true then traversal is * done in a breadth-first manner; otherwise it is done in a - * depth-first manner (which is the default behavior). + * depth-first manner (which is the default behavior) * @param int $maxDepth the 0-based depth relative to the root node up * to which the hierarchy should be traversed (if it's -1, the * hierarchy will be traversed until there are no more children of the - * current item). + * current item) * * @api */ @@ -87,9 +86,9 @@ public function __construct($breadthFirst = false, $maxDepth = -1) $this->breadthFirst = $breadthFirst; $this->maxDepth = $maxDepth; - if ($this->breadthFirst === true) { - $this->currentQueue = new SplQueue(); - $this->nextQueue = new SplQueue(); + if (true === $this->breadthFirst) { + $this->currentQueue = new \SplQueue(); + $this->nextQueue = new \SplQueue(); } $this->currentDepth = 0; } @@ -109,11 +108,11 @@ public function setLevel($level) * visited. * * @param ItemInterface $item the Item that is accepting this - * visitor. + * visitor * @param int $depth hierarchy level of this node (the root node starts - * at depth 0). + * at depth 0) * - * @throws RepositoryException if an error occurs. + * @throws RepositoryException if an error occurs * * @api */ @@ -124,11 +123,11 @@ abstract protected function entering(ItemInterface $item, $depth); * visited. * * @param ItemInterface $item the Item that is accepting this - * visitor. + * visitor * @param int $depth hierarchy level of this property (the root node - * starts at depth 0). + * starts at depth 0) * - * @throws RepositoryException if an error occurs. + * @throws RepositoryException if an error occurs * * @api */ @@ -144,15 +143,15 @@ abstract protected function leaving(ItemInterface $item, $depth); * If this method throws, the visiting process is aborted. * * @param ItemInterface $item the Node or Property that is accepting - * this visitor. + * this visitor * - * @throws RepositoryException if an error occurs. + * @throws RepositoryException if an error occurs * * @api */ public function visit(ItemInterface $item) { - if ($this->currentDepth === 0) { + if (0 === $this->currentDepth) { $this->currentDepth = $item->getDepth(); } if ($item instanceof PropertyInterface) { @@ -169,10 +168,10 @@ public function visit(ItemInterface $item) } try { - if ($this->breadthFirst === false) { + if (false === $this->breadthFirst) { $this->entering($item, $this->currentDepth); - if ($this->maxDepth === -1 || $this->currentDepth < $this->maxDepth) { - $this->currentDepth++; + if (-1 === $this->maxDepth || $this->currentDepth < $this->maxDepth) { + ++$this->currentDepth; foreach ($item->getProperties() as $property) { /* @var $property PropertyInterface */ $property->accept($this); @@ -181,14 +180,14 @@ public function visit(ItemInterface $item) /* @var $node NodeInterface */ $node->accept($this); } - $this->currentDepth--; + --$this->currentDepth; } $this->leaving($item, $this->currentDepth); } else { $this->entering($item, $this->currentDepth); $this->leaving($item, $this->currentDepth); - if ($this->maxDepth === -1 || $this->currentDepth < $this->maxDepth) { + if (-1 === $this->maxDepth || $this->currentDepth < $this->maxDepth) { foreach ($item->getProperties() as $property) { /* @var $property PropertyInterface */ $property->accept($this); @@ -201,9 +200,9 @@ public function visit(ItemInterface $item) while (!$this->currentQueue->isEmpty() || !$this->nextQueue->isEmpty()) { if ($this->currentQueue->isEmpty()) { - $this->currentDepth++; + ++$this->currentDepth; $this->currentQueue = $this->nextQueue; - $this->nextQueue = new SplQueue(); + $this->nextQueue = new \SplQueue(); } $item = $this->currentQueue->dequeue(); $item->accept($this); diff --git a/src/PHPCR/Util/TreeWalker.php b/src/PHPCR/Util/TreeWalker.php index 2eaf6e3c..d1539e82 100644 --- a/src/PHPCR/Util/TreeWalker.php +++ b/src/PHPCR/Util/TreeWalker.php @@ -57,8 +57,6 @@ public function __construct(ItemVisitorInterface $nodeVisitor, ItemVisitorInterf /** * Add a filter to select the nodes that will be traversed. - * - * @param TreeWalkerFilterInterface $filter */ public function addNodeFilter(TreeWalkerFilterInterface $filter) { @@ -69,8 +67,6 @@ public function addNodeFilter(TreeWalkerFilterInterface $filter) /** * Add a filter to select the properties that will be traversed. - * - * @param TreeWalkerFilterInterface $filter */ public function addPropertyFilter(TreeWalkerFilterInterface $filter) { @@ -82,8 +78,6 @@ public function addPropertyFilter(TreeWalkerFilterInterface $filter) /** * Return whether a node must be traversed or not. * - * @param NodeInterface $node - * * @return bool */ protected function mustVisitNode(NodeInterface $node) @@ -100,8 +94,6 @@ protected function mustVisitNode(NodeInterface $node) /** * Return whether a node property must be traversed or not. * - * @param PropertyInterface $property - * * @return bool */ protected function mustVisitProperty(PropertyInterface $property) @@ -118,9 +110,8 @@ protected function mustVisitProperty(PropertyInterface $property) /** * Traverse a node. * - * @param NodeInterface $node - * @param int $recurse Max recursion level - * @param int $level Recursion level + * @param int $recurse Max recursion level + * @param int $level Recursion level */ public function traverse(NodeInterface $node, $recurse = -1, $level = 0): void { @@ -135,7 +126,7 @@ public function traverse(NodeInterface $node, $recurse = -1, $level = 0): void $node->accept($this->nodeVisitor); // Visit properties - if ($this->propertyVisitor !== null) { + if (null !== $this->propertyVisitor) { foreach ($node->getProperties() as $prop) { if ($this->mustVisitProperty($prop)) { if (method_exists($this->propertyVisitor, 'setLevel')) { diff --git a/src/PHPCR/Util/TreeWalkerFilterInterface.php b/src/PHPCR/Util/TreeWalkerFilterInterface.php index 41272d79..1e326056 100644 --- a/src/PHPCR/Util/TreeWalkerFilterInterface.php +++ b/src/PHPCR/Util/TreeWalkerFilterInterface.php @@ -13,10 +13,6 @@ interface TreeWalkerFilterInterface { /** * Whether to visit the passed item. - * - * @param ItemInterface $item - * - * @return mixed */ public function mustVisit(ItemInterface $item); } diff --git a/src/PHPCR/Util/UUIDHelper.php b/src/PHPCR/Util/UUIDHelper.php index 546a71db..476c1369 100644 --- a/src/PHPCR/Util/UUIDHelper.php +++ b/src/PHPCR/Util/UUIDHelper.php @@ -17,7 +17,7 @@ class UUIDHelper * * @param string $id Possible uuid * - * @return bool True if the test was passed, else false. + * @return bool true if the test was passed, else false */ public static function isUUID($id) { diff --git a/src/PHPCR/Util/ValueConverter.php b/src/PHPCR/Util/ValueConverter.php index 859cdfec..ab116639 100644 --- a/src/PHPCR/Util/ValueConverter.php +++ b/src/PHPCR/Util/ValueConverter.php @@ -4,7 +4,6 @@ use DateTime; use Exception; -use InvalidArgumentException; use PHPCR\NodeInterface; use PHPCR\PropertyInterface; use PHPCR\PropertyType; @@ -42,12 +41,12 @@ class ValueConverter * http://www.day.com/specs/jcr/2.0/3_Repository_Model.html#3.6.4.3%20From%20DATE%20To * * @param mixed $value The variable we need to know the type of - * @param bool $weak When a Node is given as $value this can be given - * as true to create a WEAKREFERENCE. - * - * @throws ValueFormatException if the type can not be determined + * @param bool $weak when a Node is given as $value this can be given + * as true to create a WEAKREFERENCE * * @return int One of the type constants + * + * @throws ValueFormatException if the type can not be determined */ public function determineType($value, $weak = false) { @@ -107,12 +106,12 @@ public function determineType($value, $weak = false) * @param int $type Target type to convert into. One of the type constants in PropertyType * @param int $srcType Source type to convert from, if not specified this is automatically determined, which will miss the string based types that are not strings (DECIMAL, NAME, PATH, URI) * - * @throws ValueFormatException is thrown if the specified value cannot be converted to the specified type - * @throws RepositoryException if the specified Node is not referenceable, the current Session is no longer active, or another error occurs. - * @throws InvalidArgumentException if the specified DateTime value cannot be expressed in the ISO 8601-based format defined in the JCR 2.0 specification and the implementation does not support dates incompatible with that format. - * * @return mixed the value casted into the proper format (throws an exception if conversion is not possible) * + * @throws ValueFormatException is thrown if the specified value cannot be converted to the specified type + * @throws RepositoryException if the specified Node is not referenceable, the current Session is no longer active, or another error occurs + * @throws \InvalidArgumentException if the specified DateTime value cannot be expressed in the ISO 8601-based format defined in the JCR 2.0 specification and the implementation does not support dates incompatible with that format. + * * @see http://www.day.com/specs/jcr/2.0/3_Repository_Model.html#3.6.4%20Property%20Type%20Conversion */ public function convertType($value, $type, $srcType = PropertyType::UNDEFINED) @@ -154,9 +153,10 @@ public function convertType($value, $type, $srcType = PropertyType::UNDEFINED) case PropertyType::STRING: switch ($srcType) { case PropertyType::DATE: - if (!$value instanceof DateTime) { + if (!$value instanceof \DateTime) { throw new RepositoryException('Cannot convert a date that is not a \DateTime instance to string'); } + /* @var $value DateTime */ // Milliseconds formatting is not possible in PHP so we // construct it by cutting microseconds to 3 positions. @@ -175,10 +175,12 @@ public function convertType($value, $type, $srcType = PropertyType::UNDEFINED) if (is_resource($value)) { throw new ValueFormatException('Inconsistency: Non-binary property should not have resource stream value'); } + // TODO: how can we provide ValueFormatException on failure? invalid casting leads to 'catchable fatal error' instead of exception return (string) $value; } + // no break case PropertyType::BINARY: if (is_resource($value)) { return $value; @@ -201,7 +203,7 @@ public function convertType($value, $type, $srcType = PropertyType::UNDEFINED) case PropertyType::DECIMAL: return (int) $value; case PropertyType::DATE: - if (!$value instanceof DateTime) { + if (!$value instanceof \DateTime) { throw new RepositoryException('something weird'); } /* @var $value DateTime */ @@ -222,7 +224,7 @@ public function convertType($value, $type, $srcType = PropertyType::UNDEFINED) case PropertyType::DECIMAL: return (float) $value; case PropertyType::DATE: - if (!$value instanceof DateTime) { + if (!$value instanceof \DateTime) { throw new RepositoryException('something weird'); } @@ -239,19 +241,19 @@ public function convertType($value, $type, $srcType = PropertyType::UNDEFINED) switch ($srcType) { case PropertyType::STRING: case PropertyType::DATE: - if ($value instanceof DateTime) { + if ($value instanceof \DateTime) { return $value; } try { - return new DateTime($value); - } catch (Exception $e) { + return new \DateTime($value); + } catch (\Exception $e) { throw new ValueFormatException("String '$value' is not a valid date", 0, $e); } case PropertyType::LONG: case PropertyType::DOUBLE: case PropertyType::DECIMAL: - $datetime = new DateTime(); + $datetime = new \DateTime(); $datetime = $datetime->setTimestamp(round($value)); return $datetime; @@ -320,7 +322,7 @@ public function convertType($value, $type, $srcType = PropertyType::UNDEFINED) case PropertyType::REFERENCE: case PropertyType::WEAKREFERENCE: if (empty($value)) { - //TODO check if string is valid uuid + // TODO check if string is valid uuid throw new ValueFormatException('Value "'.var_export($value, true).'" is not a valid unique id'); } diff --git a/tests/PHPCR/Tests/Stubs/MockNode.php b/tests/PHPCR/Tests/Stubs/MockNode.php index e0249394..ea937214 100644 --- a/tests/PHPCR/Tests/Stubs/MockNode.php +++ b/tests/PHPCR/Tests/Stubs/MockNode.php @@ -2,9 +2,8 @@ namespace PHPCR\Tests\Stubs; -use Iterator; use PHPCR\NodeInterface; -abstract class MockNode implements Iterator, NodeInterface +abstract class MockNode implements \Iterator, NodeInterface { } diff --git a/tests/PHPCR/Tests/Stubs/MockNodeTypeManager.php b/tests/PHPCR/Tests/Stubs/MockNodeTypeManager.php index 7cd46605..97f696f0 100644 --- a/tests/PHPCR/Tests/Stubs/MockNodeTypeManager.php +++ b/tests/PHPCR/Tests/Stubs/MockNodeTypeManager.php @@ -2,9 +2,8 @@ namespace PHPCR\Tests\Stubs; -use Iterator; use PHPCR\NodeType\NodeTypeManagerInterface; -abstract class MockNodeTypeManager implements Iterator, NodeTypeManagerInterface +abstract class MockNodeTypeManager implements \Iterator, NodeTypeManagerInterface { } diff --git a/tests/PHPCR/Tests/Stubs/MockRow.php b/tests/PHPCR/Tests/Stubs/MockRow.php index 45077223..298e2bef 100644 --- a/tests/PHPCR/Tests/Stubs/MockRow.php +++ b/tests/PHPCR/Tests/Stubs/MockRow.php @@ -2,9 +2,8 @@ namespace PHPCR\Tests\Stubs; -use Iterator; use PHPCR\Query\RowInterface; -abstract class MockRow implements Iterator, RowInterface +abstract class MockRow implements \Iterator, RowInterface { } diff --git a/tests/PHPCR/Tests/Util/CND/Reader/BufferReaderTest.php b/tests/PHPCR/Tests/Util/CND/Reader/BufferReaderTest.php index 86fd7479..7741efe6 100644 --- a/tests/PHPCR/Tests/Util/CND/Reader/BufferReaderTest.php +++ b/tests/PHPCR/Tests/Util/CND/Reader/BufferReaderTest.php @@ -7,7 +7,7 @@ class BufferReaderTest extends TestCase { - public function test__construct(): void + public function testConstruct(): void { $buffer = "Some random\nor\r\nstring"; $reader = new BufferReader($buffer); @@ -92,7 +92,7 @@ public function test__construct(): void $this->assertEquals($reader->getEofMarker(), $reader->forward()); } - public function test__constructEmptyString() + public function testConstructEmptyString() { $reader = new BufferReader(''); diff --git a/tests/PHPCR/Tests/Util/CND/Reader/FileReaderTest.php b/tests/PHPCR/Tests/Util/CND/Reader/FileReaderTest.php index 5d3d1a2d..e7fed571 100644 --- a/tests/PHPCR/Tests/Util/CND/Reader/FileReaderTest.php +++ b/tests/PHPCR/Tests/Util/CND/Reader/FileReaderTest.php @@ -2,7 +2,6 @@ namespace PHPCR\Tests\Util\CND\Reader; -use InvalidArgumentException; use PHPCR\Util\CND\Reader\FileReader; use PHPUnit\Framework\TestCase; @@ -48,9 +47,9 @@ public function setUp(): void ); } - public function test__construct_fileNotFound() + public function testConstructFileNotFound() { - $this->expectException(InvalidArgumentException::class); + $this->expectException(\InvalidArgumentException::class); new FileReader('unexisting_file'); } @@ -65,7 +64,7 @@ public function testGetNextChar() $curLine = 1; $curCol = 1; - for ($i = 0; $i < count($this->chars); $i++) { + for ($i = 0; $i < count($this->chars); ++$i) { $peek = $this->reader->currentChar(); if ($peek === $this->reader->getEofMarker()) { @@ -80,11 +79,11 @@ public function testGetNextChar() $this->assertFalse($this->reader->isEof()); // Assert isEol is true at end of the lines - if ($peek === "\n") { - $curLine++; + if ("\n" === $peek) { + ++$curLine; $curCol = 1; } else { - $curCol++; + ++$curCol; } // Assert the next character is the expected one diff --git a/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php b/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php index 59f9377d..53c5212a 100644 --- a/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php +++ b/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php @@ -2,7 +2,6 @@ namespace PHPCR\Tests\Util\CND\Scanner; -use ArrayIterator; use PHPCR\Util\CND\Reader\FileReader; use PHPCR\Util\CND\Scanner\Context\DefaultScannerContext; use PHPCR\Util\CND\Scanner\GenericScanner; @@ -14,7 +13,6 @@ class GenericScannerTest extends TestCase { protected $expectedTokens = [ - // [Token::TK_SYMBOL, '<'], [Token::TK_SYMBOL, '?'], @@ -110,7 +108,7 @@ public function setUp(): void { $this->expectedTokensNoEmptyToken = []; foreach ($this->expectedTokens as $token) { - if ($token[0] !== Token::TK_NEWLINE && $token[0] !== Token::TK_WHITESPACE) { + if (Token::TK_NEWLINE !== $token[0] && Token::TK_WHITESPACE !== $token[0]) { $this->expectedTokensNoEmptyToken[] = $token; } } @@ -144,7 +142,7 @@ protected function assertTokens($tokens, TokenQueue $queue) { $queue->reset(); - $it = new ArrayIterator($tokens); + $it = new \ArrayIterator($tokens); $token = $queue->peek(); diff --git a/tests/PHPCR/Tests/Util/CND/Scanner/TokenTest.php b/tests/PHPCR/Tests/Util/CND/Scanner/TokenTest.php index 8f81190b..272ce1e4 100644 --- a/tests/PHPCR/Tests/Util/CND/Scanner/TokenTest.php +++ b/tests/PHPCR/Tests/Util/CND/Scanner/TokenTest.php @@ -17,7 +17,7 @@ public function setUp(): void $this->token = new Token(123, 'foobar'); } - public function test__construct() + public function testConstruct() { $this->assertSame(123, $this->token->type); $this->assertSame('foobar', $this->token->data); @@ -33,7 +33,7 @@ public function testGetType() $this->assertEquals(123, $this->token->getType()); } - public function test__toString() + public function testToString() { $this->assertEquals('TOKEN(123, \'foobar\', 0, 0)', $this->token->__toString()); } diff --git a/tests/PHPCR/Tests/Util/Console/Command/BaseCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/BaseCommandTest.php index f935b7df..26c13f6f 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/BaseCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/BaseCommandTest.php @@ -84,7 +84,7 @@ public function setUp(): void ->getMock(); $this->helperSet = new HelperSet([ - 'phpcr' => new PhpcrHelper($this->session), + 'phpcr' => new PhpcrHelper($this->session), 'phpcr_console_dumper' => $this->dumperHelper, ]); diff --git a/tests/PHPCR/Tests/Util/Console/Command/NodeDumpCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodeDumpCommandTest.php index 993d4864..c9aee706 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodeDumpCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodeDumpCommandTest.php @@ -2,7 +2,6 @@ namespace PHPCR\Tests\Util\Console\Command; -use Exception; use PHPCR\ItemNotFoundException; use PHPCR\Util\Console\Command\NodeDumpCommand; use PHPCR\Util\TreeWalker; @@ -71,7 +70,7 @@ public function testCommandIdentifier() public function testInvalidRefFormat() { - $this->expectException(Exception::class); + $this->expectException(\Exception::class); $this->executeCommand('phpcr:node:dump', ['--ref-format' => 'xy']); $this->fail('invalid ref-format did not produce exception'); diff --git a/tests/PHPCR/Tests/Util/Console/Command/NodeRemoveCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodeRemoveCommandTest.php index c103ee42..7edbd102 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodeRemoveCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodeRemoveCommandTest.php @@ -2,7 +2,6 @@ namespace PHPCR\Tests\Util\Console\Command; -use LogicException; use PHPCR\Util\Console\Command\NodeRemoveCommand; class NodeRemoveCommandTest extends BaseCommandTest @@ -22,17 +21,17 @@ public function testRemove() $this->executeCommand('phpcr:node:remove', [ '--force' => true, - 'path' => '/cms', + 'path' => '/cms', ]); } public function testRemoveRoot() { - $this->expectException(LogicException::class); + $this->expectException(\LogicException::class); $this->executeCommand('phpcr:node:remove', [ '--force' => true, - 'path' => '/', + 'path' => '/', ]); } } diff --git a/tests/PHPCR/Tests/Util/Console/Command/NodeTouchCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodeTouchCommandTest.php index 0bbb59ac..30cc7fae 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodeTouchCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodeTouchCommandTest.php @@ -2,7 +2,6 @@ namespace PHPCR\Tests\Util\Console\Command; -use Exception; use PHPCR\NodeType\NodeTypeInterface; use PHPCR\PathNotFoundException; use PHPCR\Tests\Stubs\MockNode; @@ -58,7 +57,7 @@ public function testTouch() throw new PathNotFoundException(); } - throw new Exception('Unexpected '.$path); + throw new \Exception('Unexpected '.$path); }); $this->node1->expects($this->once()) @@ -104,12 +103,12 @@ public function testUpdate() }); $this->executeCommand('phpcr:node:touch', [ - 'path' => '/cms', - '--set-prop' => ['foo=bar'], - '--remove-prop' => ['bar'], - '--add-mixin' => ['foo:bar'], + 'path' => '/cms', + '--set-prop' => ['foo=bar'], + '--remove-prop' => ['bar'], + '--add-mixin' => ['foo:bar'], '--remove-mixin' => ['bar:foo'], - '--dump' => true, + '--dump' => true, ]); } } diff --git a/tests/PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php index 542fe109..a05ea5a5 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php @@ -2,7 +2,6 @@ namespace PHPCR\Tests\Util\Console\Command; -use InvalidArgumentException; use PHPCR\Query\QueryInterface; use PHPCR\Util\Console\Command\NodesUpdateCommand; use PHPUnit\Framework\MockObject\MockObject; @@ -26,16 +25,16 @@ public function provideNodeUpdate() { return [ // No query specified - [['exception' => InvalidArgumentException::class]], + [['exception' => \InvalidArgumentException::class]], // Specify query [['query' => 'SELECT * FROM nt:unstructured WHERE foo="bar"']], // Set, remote properties and mixins [[ - 'setProp' => [['foo', 'bar']], - 'removeProp' => ['bar'], - 'addMixin' => ['mixin1'], + 'setProp' => [['foo', 'bar']], + 'removeProp' => ['bar'], + 'addMixin' => ['mixin1'], 'removeMixin' => ['mixin1'], - 'query' => 'SELECT * FROM nt:unstructured', + 'query' => 'SELECT * FROM nt:unstructured', ]], ]; } @@ -72,12 +71,12 @@ protected function setupQueryManager($options) public function testNodeUpdate($options) { $options = array_merge([ - 'query' => null, - 'setProp' => [], - 'removeProp' => [], - 'addMixin' => [], + 'query' => null, + 'setProp' => [], + 'removeProp' => [], + 'addMixin' => [], 'removeMixin' => [], - 'exception' => null, + 'exception' => null, ], $options); if ($options['exception']) { @@ -87,12 +86,12 @@ public function testNodeUpdate($options) $this->setupQueryManager($options); $args = [ - '--query' => $options['query'], + '--query' => $options['query'], '--no-interaction' => true, - '--set-prop' => [], - '--remove-prop' => [], - '--add-mixin' => [], - '--remove-mixin' => [], + '--set-prop' => [], + '--remove-prop' => [], + '--add-mixin' => [], + '--remove-mixin' => [], ]; $setPropertyArguments = []; @@ -133,9 +132,9 @@ public function testNodeUpdate($options) public function testApplyClosure() { $args = [ - '--query' => 'SELECT foo FROM bar', + '--query' => 'SELECT foo FROM bar', '--no-interaction' => true, - '--apply-closure' => [ + '--apply-closure' => [ '$session->getNodeByIdentifier("/foo"); $node->setProperty("foo", "bar");', function ($session, $node) { $node->setProperty('foo', 'bar'); diff --git a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceCreateCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceCreateCommandTest.php index 7df686b8..34f86086 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceCreateCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceCreateCommandTest.php @@ -75,7 +75,7 @@ public function testCreateExisting() $tester = $this->executeCommand( 'phpcr:workspace:create', [ - 'name' => 'test', + 'name' => 'test', '--ignore-existing' => true, ], 0 diff --git a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceDeleteCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceDeleteCommandTest.php index 9808db4b..ebd841fa 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceDeleteCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceDeleteCommandTest.php @@ -38,7 +38,7 @@ public function testDelete() ->with('test_workspace'); $ct = $this->executeCommand('phpcr:workspace:delete', [ - 'name' => 'test_workspace', + 'name' => 'test_workspace', '--force' => 'true', ]); @@ -56,7 +56,7 @@ public function testDeleteNonexistent() ->willReturn(['default', 'other']); $ct = $this->executeCommand('phpcr:workspace:delete', [ - 'name' => 'test_workspace', + 'name' => 'test_workspace', '--force' => 'true', ]); diff --git a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceImportCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceImportCommandTest.php index d2b5ebd9..5d2958c9 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceImportCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceImportCommandTest.php @@ -53,7 +53,7 @@ public function testImportUuidBehaviorThrow() ->with('/', 'test_import.xml', ImportUUIDBehaviorInterface::IMPORT_UUID_COLLISION_THROW); $ct = $this->executeCommand('phpcr:workspace:import', [ - 'filename' => 'test_import.xml', + 'filename' => 'test_import.xml', '--uuid-behavior' => 'throw', ]); diff --git a/tests/PHPCR/Tests/Util/Console/Helper/PhpcrConsoleDumperHelperTest.php b/tests/PHPCR/Tests/Util/Console/Helper/PhpcrConsoleDumperHelperTest.php index 057b3a6e..6c4b97dc 100644 --- a/tests/PHPCR/Tests/Util/Console/Helper/PhpcrConsoleDumperHelperTest.php +++ b/tests/PHPCR/Tests/Util/Console/Helper/PhpcrConsoleDumperHelperTest.php @@ -31,9 +31,9 @@ public function provideHelper() public function testGetTreeWalker($options) { $options = array_merge([ - 'dump_uuids' => false, - 'ref_format' => 'uuid', - 'show_props' => false, + 'dump_uuids' => false, + 'ref_format' => 'uuid', + 'show_props' => false, 'show_sys_nodes' => false, ], $options); @@ -45,7 +45,7 @@ public function testGetTreeWalker($options) $propVisitorProp->setAccessible(true); $propVisitor = $propVisitorProp->getValue($tw); - if ($options['show_props'] === true) { + if (true === $options['show_props']) { $this->assertInstanceOf(ConsoleDumperPropertyVisitor::class, $propVisitor); } else { $this->assertNull($propVisitor); diff --git a/tests/PHPCR/Tests/Util/NodeHelperTest.php b/tests/PHPCR/Tests/Util/NodeHelperTest.php index bebad5e2..a3659292 100644 --- a/tests/PHPCR/Tests/Util/NodeHelperTest.php +++ b/tests/PHPCR/Tests/Util/NodeHelperTest.php @@ -139,7 +139,7 @@ public function testCalculateOrderBeforeSwapLast() $expected = [ 'three' => null, - 'two' => 'four', // TODO: this is an unnecessary but harmless NOOP. we should try to eliminate + 'two' => 'four', // TODO: this is an unnecessary but harmless NOOP. we should try to eliminate ]; $this->assertEquals($expected, $reorders); @@ -154,7 +154,7 @@ public function testCalculateOrderBeforeSwap() $expected = [ 'three' => 'two', - 'two' => null, + 'two' => null, ]; $this->assertEquals($expected, $reorders); @@ -169,8 +169,8 @@ public function testCalculateOrderBeforeReverse() $expected = [ 'three' => 'two', - 'two' => 'one', - 'one' => null, + 'two' => 'one', + 'one' => null, ]; $this->assertEquals($expected, $reorders); } @@ -183,8 +183,8 @@ public function testCalculateOrderBeforeDeleted() $reorders = NodeHelper::calculateOrderBefore($old, $new); $expected = [ - 'two' => null, - 'one' => 'three', // TODO: this is an unnecessary but harmless NOOP. we should try to eliminate + 'two' => null, + 'one' => 'three', // TODO: this is an unnecessary but harmless NOOP. we should try to eliminate ]; $this->assertEquals($expected, $reorders); @@ -197,7 +197,7 @@ public function testBenchmarkOrderBeforeArray() { $nodes = []; - for ($i = 0; $i < 100000; $i++) { + for ($i = 0; $i < 100000; ++$i) { $nodes[] = 'test'.$i; } diff --git a/tests/PHPCR/Tests/Util/PathHelperTest.php b/tests/PHPCR/Tests/Util/PathHelperTest.php index 14d09116..cc7ec87c 100644 --- a/tests/PHPCR/Tests/Util/PathHelperTest.php +++ b/tests/PHPCR/Tests/Util/PathHelperTest.php @@ -6,7 +6,6 @@ use PHPCR\RepositoryException; use PHPCR\Util\PathHelper; use PHPUnit\Framework\TestCase; -use stdClass; class PathHelperTest extends TestCase { @@ -172,7 +171,7 @@ public static function dataproviderNormalizePathInvalid() ['bar'], ['/foo/bar/'], [''], - [new stdClass()], + [new \stdClass()], ]; } @@ -219,7 +218,7 @@ public static function dataproviderAbsolutizePathInvalid() ['', '/context', false], [null, '/context', false], ['foo', null, false], - [new stdClass(), '/context', false], + [new \stdClass(), '/context', false], ['foo[2]', '/bar', true], ]; } diff --git a/tests/PHPCR/Tests/Util/QOM/QueryBuilderTest.php b/tests/PHPCR/Tests/Util/QOM/QueryBuilderTest.php index a96ef099..7b50c429 100644 --- a/tests/PHPCR/Tests/Util/QOM/QueryBuilderTest.php +++ b/tests/PHPCR/Tests/Util/QOM/QueryBuilderTest.php @@ -2,7 +2,6 @@ namespace PHPCR\Tests\Util\QOM; -use InvalidArgumentException; use PHPCR\Query\QOM\ConstraintInterface; use PHPCR\Query\QOM\DynamicOperandInterface; use PHPCR\Query\QOM\QueryObjectModelConstantsInterface; @@ -13,7 +12,6 @@ use PHPCR\Util\QOM\QueryBuilder; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use RuntimeException; class QueryBuilderTest extends TestCase { @@ -82,7 +80,7 @@ public function testAddOrderByLowercase() public function testAddOrderByInvalid() { - $this->expectException(InvalidArgumentException::class); + $this->expectException(\InvalidArgumentException::class); $dynamicOperand = $this->createDynamicOperandMock(); @@ -244,7 +242,7 @@ private function createSameNodeJoinConditionMock() public function testInvalidJoin() { - $this->expectException(RuntimeException::class); + $this->expectException(\RuntimeException::class); $source = $this->createSourceMock(); $joinCondition = $this->createSameNodeJoinConditionMock(); diff --git a/tests/PHPCR/Tests/Util/QOM/Sql1GeneratorTest.php b/tests/PHPCR/Tests/Util/QOM/Sql1GeneratorTest.php index aa0a7aa9..b3f37199 100644 --- a/tests/PHPCR/Tests/Util/QOM/Sql1GeneratorTest.php +++ b/tests/PHPCR/Tests/Util/QOM/Sql1GeneratorTest.php @@ -2,7 +2,6 @@ namespace PHPCR\Tests\Util\QOM; -use DateTime; use PHPCR\Util\QOM\Sql1Generator; use PHPCR\Util\ValueConverter; use PHPUnit\Framework\TestCase; @@ -27,7 +26,7 @@ public function testLiteral() public function testDateTimeLiteral() { - $literal = $this->generator->evalLiteral(new DateTime('2011-12-23T00:00:00.000+00:00')); + $literal = $this->generator->evalLiteral(new \DateTime('2011-12-23T00:00:00.000+00:00')); $this->assertEquals("TIMESTAMP '2011-12-23T00:00:00.000+00:00'", $literal); } diff --git a/tests/PHPCR/Tests/Util/QOM/Sql2GeneratorTest.php b/tests/PHPCR/Tests/Util/QOM/Sql2GeneratorTest.php index f28dff48..1dac2525 100644 --- a/tests/PHPCR/Tests/Util/QOM/Sql2GeneratorTest.php +++ b/tests/PHPCR/Tests/Util/QOM/Sql2GeneratorTest.php @@ -2,7 +2,6 @@ namespace PHPCR\Tests\Util\QOM; -use DateTime; use PHPCR\Util\QOM\Sql2Generator; use PHPCR\Util\ValueConverter; @@ -26,7 +25,7 @@ public function testLiteral() public function testDateTimeLiteral() { - $literal = $this->generator->evalLiteral(new DateTime('2011-12-23T00:00:00.000+00:00')); + $literal = $this->generator->evalLiteral(new \DateTime('2011-12-23T00:00:00.000+00:00')); $this->assertEquals("CAST('2011-12-23T00:00:00.000+00:00' AS DATE)", $literal); } diff --git a/tests/PHPCR/Tests/Util/QOM/Sql2ScannerTest.php b/tests/PHPCR/Tests/Util/QOM/Sql2ScannerTest.php index 4fca5913..b4627bbb 100644 --- a/tests/PHPCR/Tests/Util/QOM/Sql2ScannerTest.php +++ b/tests/PHPCR/Tests/Util/QOM/Sql2ScannerTest.php @@ -185,7 +185,6 @@ public function testThrowingErrorOnUnclosedString() * Function to assert that the tokens the scanner finds match the expected output * and the entire expected output is consumed. * - * @param Sql2Scanner $scanner * @param array $expected */ private function expectTokensFromScanner(Sql2Scanner $scanner, array $expected) diff --git a/tests/PHPCR/Tests/Util/ValueConverterTest.php b/tests/PHPCR/Tests/Util/ValueConverterTest.php index 65002a7c..e69ed968 100644 --- a/tests/PHPCR/Tests/Util/ValueConverterTest.php +++ b/tests/PHPCR/Tests/Util/ValueConverterTest.php @@ -2,7 +2,6 @@ namespace PHPCR\Tests\Util; -use DateTime; use PHPCR\PropertyType; use PHPCR\RepositoryException; use PHPCR\Tests\Stubs\MockNode; @@ -49,7 +48,7 @@ public function dataConversionMatrix() fwrite($uuidStream, '38b7cf18-c417-477a-af0b-c1e92a290c9a'); rewind($uuidStream); - $datetimeLong = new DateTime(); + $datetimeLong = new \DateTime(); $datetimeLong->setTimestamp(123); $nodeMock = $this->createMock(MockNode::class); @@ -70,7 +69,7 @@ public function dataConversionMatrix() ['test string', PropertyType::STRING, 0.0, PropertyType::DOUBLE], ['249.39', PropertyType::STRING, 249.39, PropertyType::DOUBLE], ['test string', PropertyType::STRING, null, PropertyType::DATE], - ['17.12.2010 GMT', PropertyType::STRING, new DateTime('17.12.2010 GMT'), PropertyType::DATE], + ['17.12.2010 GMT', PropertyType::STRING, new \DateTime('17.12.2010 GMT'), PropertyType::DATE], ['test string', PropertyType::STRING, true, PropertyType::BOOLEAN], ['false', PropertyType::STRING, true, PropertyType::BOOLEAN], ['', PropertyType::STRING, false, PropertyType::BOOLEAN], @@ -91,7 +90,7 @@ public function dataConversionMatrix() [$stream, PropertyType::BINARY, 0.0, PropertyType::DOUBLE], [$numberStream, PropertyType::BINARY, 123.456, PropertyType::DOUBLE], [$stream, PropertyType::BINARY, null, PropertyType::DATE], - [$dateStream, PropertyType::BINARY, new DateTime('17.12.2010 GMT'), PropertyType::DATE], + [$dateStream, PropertyType::BINARY, new \DateTime('17.12.2010 GMT'), PropertyType::DATE], [$stream, PropertyType::BINARY, true, PropertyType::BOOLEAN], [$nameStream, PropertyType::BINARY, 'test', PropertyType::NAME], // TODO: should we move UUIDHelper to phpcr so we can check in PropertyType? [$stream, PropertyType::STRING, null, PropertyType::REFERENCE], @@ -268,10 +267,7 @@ public function dataConversionMatrix() /** * Skip binary target as its a special case. * - * @param mixed $value - * @param int $srcType PropertyType constant to convert from - * @param $expected - * @param $targetType + * @param int $srcType PropertyType constant to convert from * * @dataProvider dataConversionMatrix */ @@ -286,9 +282,9 @@ public function testConvertType($value, $srcType, $expected, $targetType) $this->assertTrue(true); // make it assert something } } else { - if ($expected instanceof DateTime) { + if ($expected instanceof \DateTime) { $result = $this->valueConverter->convertType($value, $targetType, $srcType); - $this->assertInstanceOf(DateTime::class, $result); + $this->assertInstanceOf(\DateTime::class, $result); $this->assertEquals($expected->getTimestamp(), $result->getTimestamp()); } else { $this->assertSame($expected, $this->valueConverter->convertType($value, $targetType, $srcType)); @@ -308,11 +304,11 @@ public function testConvertTypeToBinary() $string = stream_get_contents($stream); $this->assertEquals('test string', $string); - $date = new DateTime('20.12.2012'); + $date = new \DateTime('20.12.2012'); $stream = $this->valueConverter->convertType($date, PropertyType::BINARY); $this->assertIsResource($stream); $string = stream_get_contents($stream); - $readDate = new DateTime($string); + $readDate = new \DateTime($string); $this->assertEquals($date->getTimestamp(), $readDate->getTimestamp()); $stream = fopen('php://memory', '+rw'); @@ -335,8 +331,8 @@ public function testConvertTypeArray() $this->assertIsArray($result); $this->assertCount(2, $result); - $this->assertInstanceOf(DateTime::class, $result[0]); - $this->assertInstanceOf(DateTime::class, $result[1]); + $this->assertInstanceOf(\DateTime::class, $result[0]); + $this->assertInstanceOf(\DateTime::class, $result[1]); $this->assertEquals('2012-01-10', $result[0]->format('Y-m-d')); $this->assertEquals('2012-02-12', $result[1]->format('Y-m-d')); @@ -347,13 +343,13 @@ public function testConvertTypeArray() public function testConvertTypeAutodetect() { - $date = new DateTime('2012-10-10'); + $date = new \DateTime('2012-10-10'); $result = $this->valueConverter->convertType($date, PropertyType::STRING); - $result = new DateTime($result); + $result = new \DateTime($result); $this->assertEquals($date->getTimestamp(), $result->getTimestamp()); $result = $this->valueConverter->convertType('2012-03-13T21:00:55.000+01:00', PropertyType::DATE); - $this->assertInstanceOf(DateTime::class, $result); + $this->assertInstanceOf(\DateTime::class, $result); $this->assertEquals(1331668855, $result->getTimestamp()); } diff --git a/tests/bootstrap.php b/tests/bootstrap.php index cabe0864..ac7baf3d 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -5,7 +5,7 @@ * @author Nacho Martín * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Software License 2.0 * - * @link http://phpcr.github.io/ + * @see http://phpcr.github.io/ */ // $file2 for run tests if phpcr-utils lib inside of vendor directory. From 72406525786ee3e6bb1ed7671ffc3e5ea2430d60 Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Mon, 27 Nov 2023 15:38:27 +0100 Subject: [PATCH 03/13] drop workarounds for symfony 2 --- .github/workflows/test-application.yaml | 5 +- CHANGELOG.md | 4 +- composer.json | 4 +- phpstan.neon.dist | 5 -- .../Util/Console/Command/BaseCommand.php | 72 ++----------------- .../Console/Command/NodeRemoveCommand.php | 10 +-- .../Console/Command/NodesUpdateCommand.php | 13 ++-- .../Command/WorkspaceDeleteCommand.php | 4 +- .../Console/Command/WorkspacePurgeCommand.php | 4 +- 9 files changed, 27 insertions(+), 94 deletions(-) diff --git a/.github/workflows/test-application.yaml b/.github/workflows/test-application.yaml index a4226ab4..cc3ec50b 100644 --- a/.github/workflows/test-application.yaml +++ b/.github/workflows/test-application.yaml @@ -17,11 +17,8 @@ jobs: fail-fast: false matrix: include: - - php-version: '7.2' - dependencies: 'lowest' - - php-version: '7.3' - - php-version: '7.4' - php-version: '8.0' + dependencies: 'lowest' - php-version: '8.1' - php-version: '8.2' - php-version: '8.3' diff --git a/CHANGELOG.md b/CHANGELOG.md index 53f113a6..8fde3596 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,9 @@ Changelog ------------------ * Support Symfony 7 -* Test with PHP 8.3 +* Drop support for Symfony 2 +* Remove deprecated code, clean up workarounds for Symfony 2. +* Drop support for PHP 7, test with PHP 8.3 * Adjusted commands to have the return type declarations. 1.x diff --git a/composer.json b/composer.json index d76537da..843324f6 100644 --- a/composer.json +++ b/composer.json @@ -27,9 +27,9 @@ } ], "require": { - "php": "^7.2 || ^8.0", + "php": "^8.0", "phpcr/phpcr": "~2.1.0", - "symfony/console": "^2.3 || ^3.0 || ^4.0 || ^5.0 || ^6.0 || ^7.0" + "symfony/console": "^3.0 || ^4.0 || ^5.0 || ^6.0 || ^7.0" }, "require-dev": { "ramsey/uuid": "^3.5", diff --git a/phpstan.neon.dist b/phpstan.neon.dist index bc5b3efe..093e8156 100644 --- a/phpstan.neon.dist +++ b/phpstan.neon.dist @@ -2,8 +2,3 @@ parameters: level: 2 paths: - src - ignoreErrors: - - - message: "#Symfony\\\\Component\\\\Console\\\\Helper\\\\DialogHelper#" - count: 3 - path: src/PHPCR/Util/Console/Command/BaseCommand.php diff --git a/src/PHPCR/Util/Console/Command/BaseCommand.php b/src/PHPCR/Util/Console/Command/BaseCommand.php index d1ff179f..71822c68 100644 --- a/src/PHPCR/Util/Console/Command/BaseCommand.php +++ b/src/PHPCR/Util/Console/Command/BaseCommand.php @@ -6,12 +6,7 @@ use PHPCR\Util\Console\Helper\PhpcrConsoleDumperHelper; use PHPCR\Util\Console\Helper\PhpcrHelper; use Symfony\Component\Console\Command\Command; -use Symfony\Component\Console\Helper\DialogHelper; use Symfony\Component\Console\Helper\QuestionHelper; -use Symfony\Component\Console\Input\InputInterface; -use Symfony\Component\Console\Output\OutputInterface; -use Symfony\Component\Console\Question\ConfirmationQuestion; -use Symfony\Component\Console\Question\Question; /** * Common base class to help with the helpers. @@ -21,78 +16,23 @@ */ abstract class BaseCommand extends Command { - protected $phpcrCliHelper; - protected $phpcrConsoleDumperHelper; - - /** - * @return SessionInterface - */ - protected function getPhpcrSession() + protected function getPhpcrSession(): SessionInterface { return $this->getPhpcrHelper()->getSession(); } - /** - * @return PhpcrHelper - */ - protected function getPhpcrHelper() - { - return $this->getHelperSet()->get('phpcr'); - } - - /** - * @return PhpcrConsoleDumperHelper - */ - protected function getPhpcrConsoleDumperHelper() - { - return $this->getHelperSet()->get('phpcr_console_dumper'); - } - - /** - * Ask a question with the question helper or the dialog helper for symfony < 2.5 compatibility. - * - * @param string $questionText - * @param string $default - * - * @return string - */ - protected function ask(InputInterface $input, OutputInterface $output, $questionText, $default = null) + protected function getPhpcrHelper(): PhpcrHelper { - if ($this->getHelperSet()->has('question')) { - $question = new Question($questionText, $default); - - return $this->getQuestionHelper()->ask($input, $output, $question); - } - - return $this->getDialogHelper()->ask($output, $questionText, $default); + return $this->getHelper('phpcr'); } - /** - * Ask for confirmation with the question helper or the dialog helper for symfony < 2.5 compatibility. - * - * @param string $questionText - * @param bool $default - * - * @return string - */ - protected function askConfirmation(InputInterface $input, OutputInterface $output, $questionText, $default = true) + protected function getPhpcrConsoleDumperHelper(): PhpcrConsoleDumperHelper { - if ($this->getHelperSet()->has('question')) { - $question = new ConfirmationQuestion($questionText, $default); - - return $this->getQuestionHelper()->ask($input, $output, $question); - } - - return $this->getDialogHelper()->askConfirmation($output, $questionText, $default); + return $this->getHelper('phpcr_console_dumper'); } - private function getQuestionHelper(): QuestionHelper + protected function getQuestionHelper(): QuestionHelper { return $this->getHelper('question'); } - - private function getDialogHelper(): DialogHelper - { - return $this->getHelper('dialog'); - } } diff --git a/src/PHPCR/Util/Console/Command/NodeRemoveCommand.php b/src/PHPCR/Util/Console/Command/NodeRemoveCommand.php index a6083a1b..bbf0071c 100644 --- a/src/PHPCR/Util/Console/Command/NodeRemoveCommand.php +++ b/src/PHPCR/Util/Console/Command/NodeRemoveCommand.php @@ -8,6 +8,7 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Question\ConfirmationQuestion; /** * Command to remove all nodes from a path in the workspace of the configured @@ -79,13 +80,8 @@ protected function execute(InputInterface $input, OutputInterface $output): int 'Are you sure you want to recursively delete the path "%s" '. 'from workspace "%s"'; } - - $force = $this->askConfirmation( - $input, - $output, - sprintf(''.$question.' Y/N ?', $path, $workspaceName), - false - ); + $confirmationQuestion = new ConfirmationQuestion(sprintf(''.$question.' Y/N ?', $path, $workspaceName), false); + $force = $this->getQuestionHelper()->ask($input, $output, $confirmationQuestion); } if (!$force) { diff --git a/src/PHPCR/Util/Console/Command/NodesUpdateCommand.php b/src/PHPCR/Util/Console/Command/NodesUpdateCommand.php index dd8ca70c..fd49f99a 100644 --- a/src/PHPCR/Util/Console/Command/NodesUpdateCommand.php +++ b/src/PHPCR/Util/Console/Command/NodesUpdateCommand.php @@ -8,6 +8,7 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Question\ConfirmationQuestion; /** * Command which can update the properties of nodes found @@ -102,7 +103,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int ); } - if ('SELECT' !== strtoupper(substr($query, 0, 6))) { + if (0 !== stripos($query, 'SELECT')) { throw new \InvalidArgumentException("Query doesn't look like a SELECT query: '$query'"); } @@ -150,16 +151,14 @@ protected function execute(InputInterface $input, OutputInterface $output): int return 0; } - /** - * @return bool whether to execute the action or not - */ - private function shouldExecute(InputInterface $input, OutputInterface $output, QueryResultInterface $result) + private function shouldExecute(InputInterface $input, OutputInterface $output, QueryResultInterface $result): bool { - $response = strtoupper($this->ask($input, $output, sprintf( + $question = new ConfirmationQuestion(sprintf( 'About to update %d nodes. Enter "Y" to continue, "N" to cancel or "L" to list.', count($result->getRows()) - ))); + )); + $response = $this->getQuestionHelper()->ask($input, $output, $question); if ('L' === $response) { /** @var RowInterface $row */ foreach ($result as $i => $row) { diff --git a/src/PHPCR/Util/Console/Command/WorkspaceDeleteCommand.php b/src/PHPCR/Util/Console/Command/WorkspaceDeleteCommand.php index fd63d406..8a6bee19 100644 --- a/src/PHPCR/Util/Console/Command/WorkspaceDeleteCommand.php +++ b/src/PHPCR/Util/Console/Command/WorkspaceDeleteCommand.php @@ -7,6 +7,7 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Question\ConfirmationQuestion; /** * A command to delete a workspace in the PHPCR repository. @@ -61,10 +62,11 @@ protected function execute(InputInterface $input, OutputInterface $output): int $force = $input->getOption('force'); if (!$force) { - $force = $this->askConfirmation($input, $output, sprintf( + $confirmationQuestion = new ConfirmationQuestion(sprintf( 'Are you sure you want to delete workspace "%s" Y/N ?', $workspaceName ), false); + $force = $this->getQuestionHelper()->ask($input, $output, $confirmationQuestion); } if (!$force) { $output->writeln('Aborted'); diff --git a/src/PHPCR/Util/Console/Command/WorkspacePurgeCommand.php b/src/PHPCR/Util/Console/Command/WorkspacePurgeCommand.php index c33baa92..c9112bb9 100644 --- a/src/PHPCR/Util/Console/Command/WorkspacePurgeCommand.php +++ b/src/PHPCR/Util/Console/Command/WorkspacePurgeCommand.php @@ -6,6 +6,7 @@ use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Question\ConfirmationQuestion; /** * Command to remove all non-system nodes and properties in the workspace of @@ -40,10 +41,11 @@ protected function execute(InputInterface $input, OutputInterface $output): int $workspaceName = $session->getWorkspace()->getName(); if (!$force) { - $force = $this->askConfirmation($input, $output, sprintf( + $confirmationQuestion = new ConfirmationQuestion(sprintf( 'Are you sure you want to purge workspace "%s" Y/N ?', $workspaceName ), false); + $force = $this->getQuestionHelper()->ask($input, $output, $confirmationQuestion); } if (!$force) { From b358af369c41fdbcdb69f29f4955f22b0ea7d48d Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Tue, 28 Nov 2023 07:53:24 +0100 Subject: [PATCH 04/13] strict typing --- .../Util/CND/Exception/ParserException.php | 2 +- .../Util/CND/Exception/ScannerException.php | 2 +- src/PHPCR/Util/CND/Parser/AbstractParser.php | 22 +-- src/PHPCR/Util/CND/Parser/CndParser.php | 101 +++++----- src/PHPCR/Util/CND/Reader/BufferReader.php | 83 ++------ src/PHPCR/Util/CND/Reader/FileReader.php | 16 +- src/PHPCR/Util/CND/Reader/ReaderInterface.php | 44 ++--- .../Util/CND/Scanner/AbstractScanner.php | 18 +- .../CND/Scanner/Context/ScannerContext.php | 78 +++----- src/PHPCR/Util/CND/Scanner/GenericScanner.php | 46 ++--- src/PHPCR/Util/CND/Scanner/GenericToken.php | 23 ++- src/PHPCR/Util/CND/Scanner/Token.php | 53 ++--- .../Scanner/TokenFilter/TokenFilterChain.php | 11 +- .../TokenFilter/TokenFilterInterface.php | 7 +- .../Scanner/TokenFilter/TokenTypeFilter.php | 13 +- src/PHPCR/Util/CND/Scanner/TokenQueue.php | 26 +-- src/PHPCR/Util/CND/Writer/CndWriter.php | 33 ++-- .../Command/BaseNodeManipulationCommand.php | 2 +- .../Util/Console/Command/NodeTouchCommand.php | 2 +- .../Command/NodeTypeRegisterCommand.php | 14 +- .../Command/WorkspaceCreateCommand.php | 2 +- .../Helper/PhpcrConsoleDumperHelper.php | 2 +- src/PHPCR/Util/Console/Helper/PhpcrHelper.php | 28 ++- .../TreeDumper/ConsoleDumperItemVisitor.php | 12 +- .../TreeDumper/ConsoleDumperNodeVisitor.php | 14 +- .../ConsoleDumperPropertyVisitor.php | 19 +- .../Helper/TreeDumper/SystemNodeFilter.php | 4 +- src/PHPCR/Util/NodeHelper.php | 61 +++--- src/PHPCR/Util/PathHelper.php | 43 ++-- .../Util/QOM/BaseQomToSqlQueryConverter.php | 73 ++----- src/PHPCR/Util/QOM/BaseSqlGenerator.php | 165 +++------------- .../QOM/NotSupportedConstraintException.php | 7 +- .../Util/QOM/NotSupportedOperandException.php | 7 +- .../Util/QOM/QomToSql1QueryConverter.php | 33 ++-- .../Util/QOM/QomToSql2QueryConverter.php | 36 +--- src/PHPCR/Util/QOM/QueryBuilder.php | 184 +++++------------- src/PHPCR/Util/QOM/Sql1Generator.php | 65 ++----- src/PHPCR/Util/QOM/Sql2Generator.php | 166 ++++------------ src/PHPCR/Util/QOM/Sql2Scanner.php | 49 ++--- .../Util/QOM/Sql2ToQomQueryConverter.php | 150 +++++--------- src/PHPCR/Util/TraversingItemVisitor.php | 32 +-- src/PHPCR/Util/TreeWalker.php | 32 ++- src/PHPCR/Util/TreeWalkerFilterInterface.php | 2 +- src/PHPCR/Util/UUIDHelper.php | 24 ++- src/PHPCR/Util/ValueConverter.php | 13 +- tests/PHPCR/Tests/Util/PathHelperTest.php | 11 +- .../PHPCR/Tests/Util/QOM/QueryBuilderTest.php | 27 ++- .../Tests/Util/QOM/Sql1GeneratorTest.php | 6 +- .../Tests/Util/QOM/Sql2GeneratorTest.php | 2 +- tests/PHPCR/Tests/Util/ValueConverterTest.php | 40 ++-- 50 files changed, 615 insertions(+), 1290 deletions(-) diff --git a/src/PHPCR/Util/CND/Exception/ParserException.php b/src/PHPCR/Util/CND/Exception/ParserException.php index 5652ee1f..8be90b32 100644 --- a/src/PHPCR/Util/CND/Exception/ParserException.php +++ b/src/PHPCR/Util/CND/Exception/ParserException.php @@ -12,7 +12,7 @@ */ class ParserException extends \Exception { - public function __construct(TokenQueue $queue, $msg) + public function __construct(TokenQueue $queue, string $msg) { $token = $queue->peek(); $msg = sprintf("PARSER ERROR: %s. Current token is [%s, '%s'] at line %s, column %s", $msg, GenericToken::getTypeName($token->getType()), $token->getData(), $token->getLine(), $token->getRow()); diff --git a/src/PHPCR/Util/CND/Exception/ScannerException.php b/src/PHPCR/Util/CND/Exception/ScannerException.php index 8f201514..f68f409b 100644 --- a/src/PHPCR/Util/CND/Exception/ScannerException.php +++ b/src/PHPCR/Util/CND/Exception/ScannerException.php @@ -11,7 +11,7 @@ */ class ScannerException extends \Exception { - public function __construct(ReaderInterface $reader, $msg) + public function __construct(ReaderInterface $reader, string $msg) { $msg = sprintf( "SCANNER ERROR: %s at line %s, column %s.\nCurrent buffer \"%s\"", diff --git a/src/PHPCR/Util/CND/Parser/AbstractParser.php b/src/PHPCR/Util/CND/Parser/AbstractParser.php index a7f3aba3..8954f1d1 100644 --- a/src/PHPCR/Util/CND/Parser/AbstractParser.php +++ b/src/PHPCR/Util/CND/Parser/AbstractParser.php @@ -23,10 +23,8 @@ abstract class AbstractParser { /** * The token queue. - * - * @var TokenQueue */ - protected $tokenQueue; + protected TokenQueue $tokenQueue; /** * Check the next token without consuming it and return true if it matches the given type and data. @@ -36,10 +34,8 @@ abstract class AbstractParser * @param int $type The expected token type * @param string|null $data The expected data or null * @param bool $ignoreCase whether to do string comparisons case insensitive or sensitive - * - * @return bool */ - protected function checkToken($type, $data = null, $ignoreCase = false) + protected function checkToken($type, string $data = null, bool $ignoreCase = false): bool { if ($this->tokenQueue->isEof()) { return false; @@ -65,11 +61,9 @@ protected function checkToken($type, $data = null, $ignoreCase = false) /** * Check if the token data is one of the elements of the data array. * - * @param int $type - * - * @return bool + * @param string[] $data */ - protected function checkTokenIn($type, array $data, $ignoreCase = false) + protected function checkTokenIn(int $type, array $data, bool $ignoreCase = false): bool { foreach ($data as $d) { if ($this->checkToken($type, $d, $ignoreCase)) { @@ -87,11 +81,9 @@ protected function checkTokenIn($type, array $data, $ignoreCase = false) * @param int $type The expected token type * @param string|null $data The expected token data or null * - * @return Token - * * @throws ParserException */ - protected function expectToken($type, $data = null) + protected function expectToken(int $type, string $data = null): Token { $token = $this->tokenQueue->peek(); @@ -110,10 +102,8 @@ protected function expectToken($type, $data = null) * * @param int $type The expected token type * @param string|null $data The expected token data or null - * - * @return bool|Token */ - protected function checkAndExpectToken($type, $data = null) + protected function checkAndExpectToken(int $type, string $data = null): bool|Token { if ($this->checkToken($type, $data)) { $token = $this->tokenQueue->peek(); diff --git a/src/PHPCR/Util/CND/Parser/CndParser.php b/src/PHPCR/Util/CND/Parser/CndParser.php index 59249d78..0aa43545 100644 --- a/src/PHPCR/Util/CND/Parser/CndParser.php +++ b/src/PHPCR/Util/CND/Parser/CndParser.php @@ -3,6 +3,7 @@ namespace PHPCR\Util\CND\Parser; use PHPCR\NodeType\NodeDefinitionTemplateInterface; +use PHPCR\NodeType\NodeTypeDefinitionInterface; use PHPCR\NodeType\NodeTypeManagerInterface; use PHPCR\NodeType\NodeTypeTemplateInterface; use PHPCR\NodeType\PropertyDefinitionTemplateInterface; @@ -32,48 +33,45 @@ * @author Daniel Barsotti * @author David Buchmann */ -class CndParser extends AbstractParser +final class CndParser extends AbstractParser { // node type attributes - private $ORDERABLE = ['o', 'ord', 'orderable']; // , 'variant' => true); - private $MIXIN = ['m', 'mix', 'mixin']; // , 'variant' => true); - private $ABSTRACT = ['a', 'abs', 'abstract']; // , 'variant' => true); - private $NOQUERY = ['noquery', 'nq']; // , 'variant' => false); - private $QUERY = ['query', 'q']; // , 'variant' => false); - private $PRIMARYITEM = ['primaryitem', '!']; // , 'variant' => false); + private array $ORDERABLE = ['o', 'ord', 'orderable']; // , 'variant' => true); + private array $MIXIN = ['m', 'mix', 'mixin']; // , 'variant' => true); + private array $ABSTRACT = ['a', 'abs', 'abstract']; // , 'variant' => true); + private array $NOQUERY = ['noquery', 'nq']; // , 'variant' => false); + private array $QUERY = ['query', 'q']; // , 'variant' => false); + private array $PRIMARYITEM = ['primaryitem', '!']; // , 'variant' => false); // common for properties and child definitions - private $PRIMARY = ['!', 'pri', 'primary']; // , 'variant' => true), - private $AUTOCREATED = ['a', 'aut', 'autocreated']; // , 'variant' => true), - private $MANDATORY = ['m', 'man', 'mandatory']; // , 'variant' => true), - private $PROTECTED = ['p', 'pro', 'protected']; // , 'variant' => true), - private $OPV = ['COPY', 'VERSION', 'INITIALIZE', 'COMPUTE', 'IGNORE', 'ABORT']; + private array $PRIMARY = ['!', 'pri', 'primary']; // , 'variant' => true), + private array $AUTOCREATED = ['a', 'aut', 'autocreated']; // , 'variant' => true), + private array $MANDATORY = ['m', 'man', 'mandatory']; // , 'variant' => true), + private array $PROTECTED = ['p', 'pro', 'protected']; // , 'variant' => true), + private array $OPV = ['COPY', 'VERSION', 'INITIALIZE', 'COMPUTE', 'IGNORE', 'ABORT']; // property type attributes - private $MULTIPLE = ['*', 'mul', 'multiple']; // , 'variant' => true), - private $QUERYOPS = ['qop', 'queryops']; // , 'variant' => true), // Needs special handling ! - private $NOFULLTEXT = ['nof', 'nofulltext']; // , 'variant' => true), - private $NOQUERYORDER = ['nqord', 'noqueryorder']; // , 'variant' => true), + private array $MULTIPLE = ['*', 'mul', 'multiple']; // , 'variant' => true), + private array $QUERYOPS = ['qop', 'queryops']; // , 'variant' => true), // Needs special handling ! + private array $NOFULLTEXT = ['nof', 'nofulltext']; // , 'variant' => true), + private array $NOQUERYORDER = ['nqord', 'noqueryorder']; // , 'variant' => true), // child node attributes // multiple is actually a jackrabbit specific synonym for sns // http://www.mail-archive.com/users@jackrabbit.apache.org/msg19268.html - private $SNS = ['*', 'sns', 'multiple']; // , 'variant' => true), + private array $SNS = ['*', 'sns', 'multiple']; // , 'variant' => true), - /** - * @var NodeTypeManagerInterface - */ - private $ntm; + private NodeTypeManagerInterface $ntm; /** - * @var array + * @var string[] */ - protected $namespaces = []; + protected array $namespaces = []; /** - * @var array + * @var string[] */ - protected $nodeTypes = []; + protected array $nodeTypes = []; public function __construct(NodeTypeManagerInterface $ntm) { @@ -85,10 +83,9 @@ public function __construct(NodeTypeManagerInterface $ntm) * * @param string $filename absolute path to the CND file to read * - * @return array with the namespaces map and the nodeTypes which is a - * hashmap of typename = > NodeTypeDefinitionInterface + * @return array{namespaces: string[], nodeTypes: array} */ - public function parseFile($filename) + public function parseFile(string $filename): array { $reader = new FileReader($filename); @@ -100,17 +97,19 @@ public function parseFile($filename) * * @param string $cnd string with CND content * - * @return array with the namespaces map and the nodeTypes which is a - * hashmap of typename = > NodeTypeDefinitionInterface + * @return array{namespaces: string[], nodeTypes: array} */ - public function parseString($cnd) + public function parseString(string $cnd): array { $reader = new BufferReader($cnd); return $this->parse($reader); } - private function parse(ReaderInterface $reader) + /** + * @return array{namespaces: string[], nodeTypes: array} + */ + private function parse(ReaderInterface $reader): array { $scanner = new GenericScanner(new DefaultScannerContextWithoutSpacesAndComments()); $this->tokenQueue = $scanner->scan($reader); @@ -141,7 +140,7 @@ private function parse(ReaderInterface $reader) * Prefix ::= String * Uri ::= String */ - protected function parseNamespaceMapping() + protected function parseNamespaceMapping(): void { $this->expectToken(Token::TK_SYMBOL, '<'); $prefix = $this->parseCndString(); @@ -161,7 +160,7 @@ protected function parseNamespaceMapping() * [NodeTypeAttribute {NodeTypeAttribute}] * {PropertyDef | ChildNodeDef} */ - protected function parseNodeType() + protected function parseNodeType(): void { $nodeType = $this->ntm->createNodeTypeTemplate(); $this->parseNodeTypeName($nodeType); @@ -182,7 +181,7 @@ protected function parseNodeType() * * NodeTypeName ::= '[' String ']' */ - protected function parseNodeTypeName(NodeTypeTemplateInterface $nodeType) + protected function parseNodeTypeName(NodeTypeTemplateInterface $nodeType): void { $this->expectToken(Token::TK_SYMBOL, '['); $name = $this->parseCndString(); @@ -199,7 +198,7 @@ protected function parseNodeTypeName(NodeTypeTemplateInterface $nodeType) * * Supertypes ::= '>' (StringList | '?') */ - protected function parseSupertypes(NodeTypeTemplateInterface $nodeType) + protected function parseSupertypes(NodeTypeTemplateInterface $nodeType): void { $this->expectToken(Token::TK_SYMBOL, '>'); @@ -242,7 +241,7 @@ protected function parseSupertypes(NodeTypeTemplateInterface $nodeType) * Query ::= ('noquery' | 'nq') | ('query' | 'q' ) * PrimaryItem ::= ('primaryitem'| '!')(String | '?') */ - protected function parseNodeTypeAttributes(NodeTypeTemplateInterface $nodeType) + protected function parseNodeTypeAttributes(NodeTypeTemplateInterface $nodeType): void { while (true) { if ($this->checkTokenIn(Token::TK_IDENTIFIER, $this->ORDERABLE)) { @@ -283,7 +282,7 @@ protected function parseNodeTypeAttributes(NodeTypeTemplateInterface $nodeType) * * {PropertyDef | ChildNodeDef} */ - protected function parseChildrenAndAttributes(NodeTypeTemplateInterface $nodeType) + protected function parseChildrenAndAttributes(NodeTypeTemplateInterface $nodeType): void { while (true) { if ($this->checkToken(Token::TK_SYMBOL, '-')) { @@ -309,7 +308,7 @@ protected function parseChildrenAndAttributes(NodeTypeTemplateInterface $nodeTyp * [ValueConstraints] * PropertyName ::= '-' String */ - protected function parsePropDef(NodeTypeTemplateInterface $nodeType) + protected function parsePropDef(NodeTypeTemplateInterface $nodeType): void { $this->expectToken(Token::TK_SYMBOL, '-'); @@ -363,7 +362,7 @@ protected function parsePropDef(NodeTypeTemplateInterface $nodeType) * 'DECIMAL' | 'URI' | 'UNDEFINED' | '*' | * '?') ')' */ - protected function parsePropertyType(PropertyDefinitionTemplateInterface $property) + protected function parsePropertyType(PropertyDefinitionTemplateInterface $property): void { $types = ['STRING', 'BINARY', 'LONG', 'DOUBLE', 'BOOLEAN', 'DATE', 'NAME', 'PATH', 'REFERENCE', 'WEAKREFERENCE', 'DECIMAL', 'URI', 'UNDEFINED', '*', '?', ]; @@ -387,7 +386,7 @@ protected function parsePropertyType(PropertyDefinitionTemplateInterface $proper * * DefaultValues ::= '=' (StringList | '?') */ - protected function parseDefaultValue(PropertyDefinitionTemplateInterface $property) + protected function parseDefaultValue(PropertyDefinitionTemplateInterface $property): void { if ($this->checkAndExpectToken(Token::TK_SYMBOL, '?')) { $list = ['?']; @@ -405,7 +404,7 @@ protected function parseDefaultValue(PropertyDefinitionTemplateInterface $proper * * ValueConstraints ::= '<' (StringList | '?') */ - protected function parseValueConstraints(PropertyDefinitionTemplateInterface $property) + protected function parseValueConstraints(PropertyDefinitionTemplateInterface $property): void { $this->expectToken(Token::TK_SYMBOL, '<'); @@ -472,7 +471,7 @@ protected function parseValueConstraints(PropertyDefinitionTemplateInterface $pr * NoFullText ::= ('nofulltext' | 'nof') ['?'] * NoQueryOrder ::= ('noqueryorder' | 'nqord') ['?'] */ - protected function parsePropertyAttributes(NodeTypeTemplateInterface $parentType, PropertyDefinitionTemplateInterface $property) + protected function parsePropertyAttributes(NodeTypeTemplateInterface $parentType, PropertyDefinitionTemplateInterface $property): void { $opvSeen = false; while (true) { @@ -526,7 +525,7 @@ protected function parsePropertyAttributes(NodeTypeTemplateInterface $parentType * RequiredTypes ::= '(' (StringList | '?') ')' * DefaultType ::= '=' (String | '?') */ - protected function parseChildNodeDef(NodeTypeTemplateInterface $nodeType) + protected function parseChildNodeDef(NodeTypeTemplateInterface $nodeType): void { $this->expectToken(Token::TK_SYMBOL, '+'); $childType = $this->ntm->createNodeDefinitionTemplate(); @@ -595,7 +594,7 @@ protected function parseChildNodeDef(NodeTypeTemplateInterface $nodeType) protected function parseChildNodeAttributes( NodeTypeTemplateInterface $parentType, NodeDefinitionTemplateInterface $childType - ) { + ): void { while (true) { if ($this->checkTokenIn(Token::TK_IDENTIFIER, $this->PRIMARY)) { $parentType->setPrimaryItemName($childType->getName()); @@ -624,9 +623,9 @@ protected function parseChildNodeAttributes( * * StringList ::= String {',' String} * - * @return array + * @return string[] */ - protected function parseCndStringList() + protected function parseCndStringList(): array { $strings = []; @@ -656,10 +655,8 @@ protected function parseCndStringList() * Char ::= "\t" | "\r" | "\n" | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] * * TODO: check \n, \r, \t are valid in CND strings! - * - * @return string */ - protected function parseCndString() + protected function parseCndString(): string { $string = ''; $lastType = null; @@ -735,10 +732,8 @@ protected function parseQueryOpsAttribute() /** * Parse a query operator. - * - * @return bool|string */ - protected function parseQueryOperator() + protected function parseQueryOperator(): bool|string { $token = $this->tokenQueue->peek(); $data = $token->getData(); diff --git a/src/PHPCR/Util/CND/Reader/BufferReader.php b/src/PHPCR/Util/CND/Reader/BufferReader.php index 20db884d..2e380311 100644 --- a/src/PHPCR/Util/CND/Reader/BufferReader.php +++ b/src/PHPCR/Util/CND/Reader/BufferReader.php @@ -10,50 +10,23 @@ */ class BufferReader implements ReaderInterface { - /** - * @var string - */ - protected $eofMarker; + private string $eofMarker; - /** - * @var string - */ - protected $buffer; + protected string $buffer; - /** - * @var int - */ - protected $startPos; + protected int $startPos; - /** - * @var int - */ - protected $forwardPos; + protected int $forwardPos; - /** - * @var int - */ - protected $curLine; + protected int $curLine; - /** - * @var int - */ - protected $curCol; + protected int $curCol; - /** - * @var int - */ - protected $nextCurLine; + protected int $nextCurLine; - /** - * @var int - */ - protected $nextCurCol; + protected int $nextCurCol; - /** - * @param string $buffer - */ - public function __construct($buffer) + public function __construct(string $buffer) { $this->eofMarker = chr(1); $this->buffer = str_replace("\r\n", "\n", $buffer).$this->eofMarker; @@ -61,7 +34,7 @@ public function __construct($buffer) $this->reset(); } - public function reset() + public function reset(): void { $this->startPos = 0; @@ -70,49 +43,35 @@ public function reset() $this->nextCurLine = $this->nextCurCol = 1; } - /** - * @return string - */ - public function getEofMarker() + public function getEofMarker(): string { return $this->eofMarker; } - /** - * @return int - */ - public function getCurrentLine() + public function getCurrentLine(): int { return $this->curLine; } - /** - * @return int - */ - public function getCurrentColumn() + public function getCurrentColumn(): int { return $this->curCol; } /** * Return the literal delimited by start and end position. - * - * @return string */ - public function current() + public function current(): string { return substr($this->buffer, $this->startPos, $this->forwardPos - $this->startPos); } - public function currentChar() + public function currentChar(): string { return substr($this->buffer, $this->forwardPos, 1); } - /** - * @return bool - */ - public function isEof() + public function isEof(): bool { $currentChar = $this->currentChar(); @@ -124,10 +83,8 @@ public function isEof() /** * Advance the forward position and return the literal delimited by start and end position. - * - * @return string */ - public function forward() + public function forward(): string { if ($this->forwardPos < strlen($this->buffer)) { ++$this->forwardPos; @@ -142,21 +99,21 @@ public function forward() return $this->current(); } - public function forwardChar() + public function forwardChar(): string { $this->forward(); return $this->currentChar(); } - public function rewind() + public function rewind(): void { $this->forwardPos = $this->startPos; $this->nextCurLine = $this->curLine; $this->nextCurCol = $this->curCol; } - public function consume() + public function consume(): string { $current = $this->current(); diff --git a/src/PHPCR/Util/CND/Reader/FileReader.php b/src/PHPCR/Util/CND/Reader/FileReader.php index 353594d3..30daeb3b 100644 --- a/src/PHPCR/Util/CND/Reader/FileReader.php +++ b/src/PHPCR/Util/CND/Reader/FileReader.php @@ -8,19 +8,14 @@ * @author Daniel Barsotti * @author Nikola Petkanski */ -class FileReader extends BufferReader +final class FileReader extends BufferReader { - /** - * @var string - */ - protected $path; + private string $path; /** - * @param string $path - * * @throws \InvalidArgumentException */ - public function __construct($path) + public function __construct(string $path) { if (!file_exists($path)) { throw new \InvalidArgumentException(sprintf("Invalid file '%s'", $path)); @@ -31,10 +26,7 @@ public function __construct($path) parent::__construct(file_get_contents($path)); } - /** - * @return string - */ - public function getPath() + public function getPath(): string { return $this->path; } diff --git a/src/PHPCR/Util/CND/Reader/ReaderInterface.php b/src/PHPCR/Util/CND/Reader/ReaderInterface.php index 0f8b73eb..614b43c8 100644 --- a/src/PHPCR/Util/CND/Reader/ReaderInterface.php +++ b/src/PHPCR/Util/CND/Reader/ReaderInterface.php @@ -9,57 +9,39 @@ */ interface ReaderInterface { - /** - * @return string - */ - public function getEofMarker(); + public function getEofMarker(): string; - /** - * @return string with just one character - */ - public function currentChar(); + public function currentChar(): string; - /** - * @return bool - */ - public function isEof(); + public function isEof(): bool; - /** - * @return int - */ - public function getCurrentLine(); + public function getCurrentLine(): int; - /** - * @return int - */ - public function getCurrentColumn(); + public function getCurrentColumn(): int; /** * Return the literal delimited by start and end position. - * - * @return string */ - public function current(); + public function current(): string; /** * Advance the forward position and return the literal delimited by start and end position. - * - * @return string */ - public function forward(); + public function forward(): string; - public function forwardChar(); + /** + * Forward one character and return the character at the new position. + */ + public function forwardChar(): string; /** * Rewind the forward position to the start position. */ - public function rewind(); + public function rewind(): void; /** * Return the literal delimited by start and end position, then set the * start position to the end position. - * - * @return string */ - public function consume(); + public function consume(): string; } diff --git a/src/PHPCR/Util/CND/Scanner/AbstractScanner.php b/src/PHPCR/Util/CND/Scanner/AbstractScanner.php index 35eb208f..3d1ae4c2 100644 --- a/src/PHPCR/Util/CND/Scanner/AbstractScanner.php +++ b/src/PHPCR/Util/CND/Scanner/AbstractScanner.php @@ -11,12 +11,9 @@ */ abstract class AbstractScanner { - /** - * @var TokenQueue - */ - private $queue; + private TokenQueue $queue; - protected $context; + protected Context\ScannerContext $context; public function __construct(Context\ScannerContext $context) { @@ -24,15 +21,12 @@ public function __construct(Context\ScannerContext $context) $this->context = $context; } - public function resetQueue() + public function resetQueue(): void { $this->queue = new TokenQueue(); } - /** - * @return Token|void - */ - public function applyFilters(Token $token) + public function applyFilters(Token $token): ?Token { foreach ($this->context->getTokenFilters() as $filter) { $token = $filter->filter($token); @@ -45,12 +39,12 @@ public function applyFilters(Token $token) return $token; } - protected function getQueue() + protected function getQueue(): TokenQueue { return $this->queue; } - protected function addToken(ReaderInterface $reader, Token $token) + protected function addToken(ReaderInterface $reader, Token $token): void { $token->setLine($reader->getCurrentLine()); $token->setRow($reader->getCurrentColumn()); diff --git a/src/PHPCR/Util/CND/Scanner/Context/ScannerContext.php b/src/PHPCR/Util/CND/Scanner/Context/ScannerContext.php index f9855dd1..3befd7c7 100644 --- a/src/PHPCR/Util/CND/Scanner/Context/ScannerContext.php +++ b/src/PHPCR/Util/CND/Scanner/Context/ScannerContext.php @@ -14,9 +14,9 @@ class ScannerContext /** * Characters to be considered as white spaces. * - * @var array + * @var string[] */ - protected $whitespaces = []; + protected array $whitespaces = []; /** * Characters to be considered as paired string delimiters. @@ -24,126 +24,110 @@ class ScannerContext * These characters will not be used as symbols, thus if you remove any from this list, * you must add it to the $symbols array to be taken in account as a symbol. * - * @var array + * @var string[] */ - protected $stringDelimiters = []; + protected array $stringDelimiters = []; /** * Line comments start. * - * @var array + * @var string[] */ - protected $lineCommentDelimiters = []; + protected array $lineCommentDelimiters = []; /** * Block comments delimiters. * - * @var array + * @var string[] */ - protected $blockCommentDelimiters = []; + protected array $blockCommentDelimiters = []; /** * Characters to be considered as symbols. * * String delimiters must not appear in this array. * - * @var array + * @var string[] */ - protected $symbols = []; + protected array $symbols = []; /** * @var TokenFilterInterface[] */ - protected $tokenFilters = []; + protected array $tokenFilters = []; - /** - * @param string $startDelim - * @param string $endDelim - */ - public function addBlockCommentDelimiter($startDelim, $endDelim) + public function addBlockCommentDelimiter(string $startDelim, string $endDelim): void { $this->blockCommentDelimiters[$startDelim] = $endDelim; } /** - * @return array + * @return string[] */ - public function getBlockCommentDelimiters() + public function getBlockCommentDelimiters(): array { return $this->blockCommentDelimiters; } - /** - * @param string $delim - */ - public function addLineCommentDelimiter($delim) + public function addLineCommentDelimiter(string $delim): void { $this->lineCommentDelimiters[] = $delim; } /** - * @return array + * @return string[] */ - public function getLineCommentDelimiters() + public function getLineCommentDelimiters(): array { return $this->lineCommentDelimiters; } - /** - * @param string $delim - */ - public function addStringDelimiter($delim) + public function addStringDelimiter(string $delim): void { - if (!in_array($delim, $this->stringDelimiters)) { + if (!in_array($delim, $this->stringDelimiters, true)) { $this->stringDelimiters[] = $delim; } } /** - * @return array + * @return string[] */ - public function getStringDelimiters() + public function getStringDelimiters(): array { return $this->stringDelimiters; } - /** - * @param string $symbol - */ - public function addSymbol($symbol) + public function addSymbol(string $symbol): void { - if (!in_array($symbol, $this->symbols)) { + if (!in_array($symbol, $this->symbols, true)) { $this->symbols[] = $symbol; } } /** - * @return array + * @return string[] */ - public function getSymbols() + public function getSymbols(): array { return $this->symbols; } - /** - * @param array $whitespace - */ - public function addWhitespace($whitespace) + public function addWhitespace(string $whitespace): void { - if (!in_array($whitespace, $this->whitespaces)) { + if (!in_array($whitespace, $this->whitespaces, true)) { $this->whitespaces[] = $whitespace; } } /** - * @return array + * @return string[] */ - public function getWhitespaces() + public function getWhitespaces(): array { return $this->whitespaces; } - public function addTokenFilter(TokenFilterInterface $filter) + public function addTokenFilter(TokenFilterInterface $filter): void { $this->tokenFilters[] = $filter; } @@ -151,7 +135,7 @@ public function addTokenFilter(TokenFilterInterface $filter) /** * @return TokenFilterInterface[] */ - public function getTokenFilters() + public function getTokenFilters(): array { return $this->tokenFilters; } diff --git a/src/PHPCR/Util/CND/Scanner/GenericScanner.php b/src/PHPCR/Util/CND/Scanner/GenericScanner.php index 18608540..3f324c4d 100644 --- a/src/PHPCR/Util/CND/Scanner/GenericScanner.php +++ b/src/PHPCR/Util/CND/Scanner/GenericScanner.php @@ -20,10 +20,8 @@ class GenericScanner extends AbstractScanner { /** * Scan the given reader and construct a TokenQueue composed of GenericToken. - * - * @return TokenQueue */ - public function scan(ReaderInterface $reader) + public function scan(ReaderInterface $reader): TokenQueue { $this->resetQueue(); @@ -52,10 +50,8 @@ public function scan(ReaderInterface $reader) /** * Detect and consume whitespaces. - * - * @return bool */ - protected function consumeSpaces(ReaderInterface $reader) + protected function consumeSpaces(ReaderInterface $reader): bool { if (in_array($reader->currentChar(), $this->context->getWhitespaces())) { $char = $reader->forwardChar(); @@ -76,10 +72,8 @@ protected function consumeSpaces(ReaderInterface $reader) /** * Detect and consume newlines. - * - * @return bool */ - protected function consumeNewLine(ReaderInterface $reader) + protected function consumeNewLine(ReaderInterface $reader): bool { if ("\n" === $reader->currentChar()) { $token = new GenericToken(GenericToken::TK_NEWLINE, "\n"); @@ -100,14 +94,12 @@ protected function consumeNewLine(ReaderInterface $reader) /** * Detect and consume strings. * - * @return bool - * * @throws ScannerException */ - protected function consumeString(ReaderInterface $reader) + protected function consumeString(ReaderInterface $reader): bool { $curDelimiter = $reader->currentChar(); - if (in_array($curDelimiter, $this->context->getStringDelimiters())) { + if (in_array($curDelimiter, $this->context->getStringDelimiters(), true)) { $char = $reader->forwardChar(); while ($char !== $curDelimiter) { if ("\n" === $char) { @@ -129,10 +121,8 @@ protected function consumeString(ReaderInterface $reader) /** * Detect and consume comments. - * - * @return bool */ - protected function consumeComments(ReaderInterface $reader) + protected function consumeComments(ReaderInterface $reader): bool { if ($this->consumeBlockComments($reader)) { return true; @@ -144,17 +134,16 @@ protected function consumeComments(ReaderInterface $reader) /** * Detect and consume block comments. * - * @return bool - * * @throws ScannerException */ - protected function consumeBlockComments(ReaderInterface $reader) + protected function consumeBlockComments(ReaderInterface $reader): bool { $nextChar = $reader->currentChar(); foreach ($this->context->getBlockCommentDelimiters() as $beginDelim => $endDelim) { if ($nextChar === $beginDelim[0]) { + $beginDelimLength = strlen($beginDelim); // Lookup the start delimiter - for ($i = 1; $i <= strlen($beginDelim); ++$i) { + for ($i = 1; $i <= $beginDelimLength; ++$i) { $reader->forward(); } if ($reader->current() === $beginDelim) { @@ -163,7 +152,8 @@ protected function consumeBlockComments(ReaderInterface $reader) while (!$reader->isEof()) { if ($nextChar === $endDelim[0]) { - for ($i = 1; $i <= strlen($endDelim); ++$i) { + $endDelimLength = strlen($endDelim); + for ($i = 1; $i <= $endDelimLength; ++$i) { $reader->forward(); } @@ -194,10 +184,8 @@ protected function consumeBlockComments(ReaderInterface $reader) /** * Detect and consume line comments. - * - * @return bool */ - protected function consumeLineComments(ReaderInterface $reader) + protected function consumeLineComments(ReaderInterface $reader): bool { $nextChar = $reader->currentChar(); foreach ($this->context->getLineCommentDelimiters() as $delimiter) { @@ -230,10 +218,8 @@ protected function consumeLineComments(ReaderInterface $reader) /** * Detect and consume identifiers. - * - * @return bool */ - protected function consumeIdentifiers(ReaderInterface $reader) + protected function consumeIdentifiers(ReaderInterface $reader): bool { $nextChar = $reader->currentChar(); @@ -253,14 +239,12 @@ protected function consumeIdentifiers(ReaderInterface $reader) /** * Detect and consume symbols. - * - * @return bool */ - protected function consumeSymbols(ReaderInterface $reader) + protected function consumeSymbols(ReaderInterface $reader): bool { $found = false; $nextChar = $reader->currentChar(); - while (in_array($nextChar, $this->context->getSymbols())) { + while (in_array($nextChar, $this->context->getSymbols(), true)) { $found = true; $token = new GenericToken(GenericToken::TK_SYMBOL, $nextChar); $this->addToken($reader, $token); diff --git a/src/PHPCR/Util/CND/Scanner/GenericToken.php b/src/PHPCR/Util/CND/Scanner/GenericToken.php index 6d7e7e52..b2785559 100644 --- a/src/PHPCR/Util/CND/Scanner/GenericToken.php +++ b/src/PHPCR/Util/CND/Scanner/GenericToken.php @@ -18,19 +18,18 @@ class GenericToken extends Token public const TK_SYMBOL = 6; public const TK_UNKNOWN = 99; - public static function getTypeName($type) + public static function getTypeName(int $type): string { - switch ($type) { - case self::TK_WHITESPACE: return 'Whitespace'; - case self::TK_NEWLINE: return 'Newline'; - case self::TK_STRING: return 'String'; - case self::TK_COMMENT: return 'Comment'; - case self::TK_IDENTIFIER: return 'Identifier'; - case self::TK_KEYWORD: return 'Keyword'; - case self::TK_SYMBOL: return 'Symbol'; - } - - return 'Unknown'; + return match ($type) { + self::TK_WHITESPACE => 'Whitespace', + self::TK_NEWLINE => 'Newline', + self::TK_STRING => 'String', + self::TK_COMMENT => 'Comment', + self::TK_IDENTIFIER => 'Identifier', + self::TK_KEYWORD => 'Keyword', + self::TK_SYMBOL => 'Symbol', + default => 'Unknown', + }; } public function __toString() diff --git a/src/PHPCR/Util/CND/Scanner/Token.php b/src/PHPCR/Util/CND/Scanner/Token.php index 80aebe61..4ae91e45 100644 --- a/src/PHPCR/Util/CND/Scanner/Token.php +++ b/src/PHPCR/Util/CND/Scanner/Token.php @@ -15,41 +15,28 @@ class Token { /** * The type of token. - * - * @var int */ - public $type; + public int $type; /** * The token raw data. - * - * @var string */ - public $data; + public string $data; /** * The line where the token appears. - * - * @var int */ - protected $line; + protected int $line; /** * The column where the token appears. - * - * @var int */ - protected $row; + protected int $row; /** * Constructor. - * - * @param int $type - * @param string $data - * @param int $line - * @param int $row */ - public function __construct($type = 0, $data = '', $line = 0, $row = 0) + public function __construct(int $type = 0, string $data = '', int $line = 0, int $row = 0) { $this->type = $type; $this->data = $data; @@ -57,18 +44,12 @@ public function __construct($type = 0, $data = '', $line = 0, $row = 0) $this->row = $row; } - /** - * @return string - */ - public function getData() + public function getData(): string { return $this->data; } - /** - * @return int - */ - public function getType() + public function getType(): int { return $this->type; } @@ -78,34 +59,22 @@ public function __toString() return sprintf("TOKEN(%s, '%s', %s, %s)", $this->type, trim($this->data), $this->line, $this->row); } - /** - * @param int $line - */ - public function setLine($line) + public function setLine(int $line): void { $this->line = $line; } - /** - * @return int - */ - public function getLine() + public function getLine(): int { return $this->line; } - /** - * @param int $row - */ - public function setRow($row) + public function setRow(int $row): void { $this->row = $row; } - /** - * @return int - */ - public function getRow() + public function getRow(): int { return $this->row; } diff --git a/src/PHPCR/Util/CND/Scanner/TokenFilter/TokenFilterChain.php b/src/PHPCR/Util/CND/Scanner/TokenFilter/TokenFilterChain.php index 04020596..0d5a8ba5 100644 --- a/src/PHPCR/Util/CND/Scanner/TokenFilter/TokenFilterChain.php +++ b/src/PHPCR/Util/CND/Scanner/TokenFilter/TokenFilterChain.php @@ -14,23 +14,20 @@ class TokenFilterChain implements TokenFilterInterface /** * @var TokenFilterInterface[] */ - protected $filters; + protected array $filters; - public function addFilter(TokenFilterInterface $filter) + public function addFilter(TokenFilterInterface $filter): void { $this->filters[] = $filter; } - /** - * @return Token|null - */ - public function filter(Token $token) + public function filter(Token $token): ?Token { foreach ($this->filters as $filter) { $token = $filter->filter($token); if (!$token) { - return; + return null; } } diff --git a/src/PHPCR/Util/CND/Scanner/TokenFilter/TokenFilterInterface.php b/src/PHPCR/Util/CND/Scanner/TokenFilter/TokenFilterInterface.php index d61a7a29..24fa0822 100644 --- a/src/PHPCR/Util/CND/Scanner/TokenFilter/TokenFilterInterface.php +++ b/src/PHPCR/Util/CND/Scanner/TokenFilter/TokenFilterInterface.php @@ -11,10 +11,5 @@ */ interface TokenFilterInterface { - /** - * @abstract - * - * @return Token|null - */ - public function filter(Token $token); + public function filter(Token $token): ?Token; } diff --git a/src/PHPCR/Util/CND/Scanner/TokenFilter/TokenTypeFilter.php b/src/PHPCR/Util/CND/Scanner/TokenFilter/TokenTypeFilter.php index 1bb953fa..c38d3d32 100644 --- a/src/PHPCR/Util/CND/Scanner/TokenFilter/TokenTypeFilter.php +++ b/src/PHPCR/Util/CND/Scanner/TokenFilter/TokenTypeFilter.php @@ -13,23 +13,18 @@ class TokenTypeFilter implements TokenFilterInterface { /** * The filtered out token type. - * - * @var int */ - protected $type; + protected int $type; - public function __construct($tokenType) + public function __construct(int $tokenType) { $this->type = $tokenType; } - /** - * @return Token|null - */ - public function filter(Token $token) + public function filter(Token $token): ?Token { if ($token->getType() === $this->type) { - return; + return null; } return $token; diff --git a/src/PHPCR/Util/CND/Scanner/TokenQueue.php b/src/PHPCR/Util/CND/Scanner/TokenQueue.php index 0904e24b..a25db191 100644 --- a/src/PHPCR/Util/CND/Scanner/TokenQueue.php +++ b/src/PHPCR/Util/CND/Scanner/TokenQueue.php @@ -10,31 +10,34 @@ class TokenQueue implements \IteratorAggregate { /** - * @var array + * @var Token[] */ - protected $tokens; + protected mixed $tokens; - public function __construct($tokens = []) + /** + * @param Token[] $tokens + */ + public function __construct(array $tokens = []) { $this->tokens = $tokens; } - public function add(Token $token) + public function add(Token $token): void { $this->tokens[] = $token; } - public function reset() + public function reset(): Token { return reset($this->tokens); } - public function isEof() + public function isEof(): bool { return false === current($this->tokens); } - public function peek($offset = 0) + public function peek($offset = 0): Token|false { if (!$offset) { return current($this->tokens); @@ -49,7 +52,7 @@ public function peek($offset = 0) return $this->tokens[key($this->tokens) + $offset]; } - public function get($count = 1) + public function get($count = 1): Token|null { $item = null; for ($i = 1; $i <= $count; ++$i) { @@ -57,16 +60,15 @@ public function get($count = 1) $this->next(); } - return $item; + return $item ?: null; } - public function next() + public function next(): Token|false { return next($this->tokens); } - #[\ReturnTypeWillChange] - public function getIterator() + public function getIterator(): \ArrayIterator { return new \ArrayIterator($this->tokens); } diff --git a/src/PHPCR/Util/CND/Writer/CndWriter.php b/src/PHPCR/Util/CND/Writer/CndWriter.php index 154d8bdc..c1f21a5b 100644 --- a/src/PHPCR/Util/CND/Writer/CndWriter.php +++ b/src/PHPCR/Util/CND/Writer/CndWriter.php @@ -25,13 +25,10 @@ */ class CndWriter { - /** - * @var NamespaceRegistryInterface - */ - private $ns; + private NamespaceRegistryInterface $ns; - /** @var array hashmap of prefix => namespace uri */ - private $namespaces = []; + /** @var array hashmap of prefix => namespace uri */ + private array $namespaces = []; public function __construct(NamespaceRegistryInterface $ns) { @@ -46,7 +43,7 @@ public function __construct(NamespaceRegistryInterface $ns) * @return string with declarations for all non-system namespaces and for * all node types in that array */ - public function writeString(array $nodeTypes) + public function writeString(array $nodeTypes): string { $cnd = ''; foreach ($nodeTypes as $nodeType) { @@ -63,7 +60,7 @@ public function writeString(array $nodeTypes) * Prefix ::= String * Uri ::= String */ - protected function writeNamespaces() + protected function writeNamespaces(): string { $ns = ''; foreach ($this->namespaces as $prefix => $uri) { @@ -73,12 +70,12 @@ protected function writeNamespaces() return $ns; } - private function checkNamespace($name) + private function checkNamespace($name): void { - if (false === strpos($name, ':')) { + if (!str_contains($name, ':')) { return; } - list($prefix) = explode(':', $name); + [$prefix] = explode(':', $name); // namespace registry will throw exception if namespace prefix not found $this->namespaces[$prefix] = "'".$this->ns->getURI($prefix)."'"; @@ -93,7 +90,7 @@ private function checkNamespace($name) * [NodeTypeAttribute {NodeTypeAttribute}] * {PropertyDef | ChildNodeDef} */ - protected function writeNodeType(NodeTypeDefinitionInterface $nodeType) + protected function writeNodeType(NodeTypeDefinitionInterface $nodeType): string { $this->checkNamespace($nodeType->getName()); $s = '['.$nodeType->getName().']'; @@ -132,11 +129,9 @@ protected function writeNodeType(NodeTypeDefinitionInterface $nodeType) } /** - * @param PropertyDefinitionInterface[] $properties - * - * @return string + * @param PropertyDefinitionInterface[]|null $properties */ - private function writeProperties($properties) + private function writeProperties(?array $properties): string { if (null === $properties) { // getDeclaredPropertyDefinitions is allowed to return null on @@ -197,11 +192,9 @@ private function writeProperties($properties) } /** - * @param NodeDefinitionInterface[] $children - * - * @return string + * @param NodeDefinitionInterface[]|null $children */ - private function writeChildren($children) + private function writeChildren(?array $children): string { if (null === $children) { // getDeclaredChildNodeDefinitions is allowed to return null on diff --git a/src/PHPCR/Util/Console/Command/BaseNodeManipulationCommand.php b/src/PHPCR/Util/Console/Command/BaseNodeManipulationCommand.php index 9633e457..bb995e93 100644 --- a/src/PHPCR/Util/Console/Command/BaseNodeManipulationCommand.php +++ b/src/PHPCR/Util/Console/Command/BaseNodeManipulationCommand.php @@ -15,7 +15,7 @@ abstract class BaseNodeManipulationCommand extends BaseCommand /** * Set up the options to manipulate nodes. */ - protected function configureNodeManipulationInput() + protected function configureNodeManipulationInput(): void { $this->addOption( 'set-prop', diff --git a/src/PHPCR/Util/Console/Command/NodeTouchCommand.php b/src/PHPCR/Util/Console/Command/NodeTouchCommand.php index e4dca658..f397e4b6 100644 --- a/src/PHPCR/Util/Console/Command/NodeTouchCommand.php +++ b/src/PHPCR/Util/Console/Command/NodeTouchCommand.php @@ -98,7 +98,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $nodeType )); - if ($nodeType != $type) { + if ($nodeType !== $type) { $output->writeln(sprintf( 'You have specified node type "%s" but the existing node is of type "%s"', $type, diff --git a/src/PHPCR/Util/Console/Command/NodeTypeRegisterCommand.php b/src/PHPCR/Util/Console/Command/NodeTypeRegisterCommand.php index 3e8485fe..3fc5c9dd 100644 --- a/src/PHPCR/Util/Console/Command/NodeTypeRegisterCommand.php +++ b/src/PHPCR/Util/Console/Command/NodeTypeRegisterCommand.php @@ -64,7 +64,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int { $definitions = $input->getArgument('cnd-file'); - if (0 == count($definitions)) { + if (0 === count($definitions)) { throw new \InvalidArgumentException('At least one definition (i.e. file or folder) must be specified'); } @@ -96,7 +96,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int * * @throws RepositoryException on other errors */ - protected function updateFromCnd(OutputInterface $output, SessionInterface $session, $cnd, $allowUpdate) + protected function updateFromCnd(OutputInterface $output, SessionInterface $session, string $cnd, bool $allowUpdate): void { $ntm = $session->getWorkspace()->getNodeTypeManager(); @@ -117,13 +117,13 @@ protected function updateFromCnd(OutputInterface $output, SessionInterface $sess * Return a list of node type definition file paths from * the given definition files or folders. * - * @param array $definitions List of files of folders + * @param string[] $definitions List of files or folders * - * @return array array of full paths to all the type node definition files + * @return string[] list of available node type definition files * * @throws \InvalidArgumentException */ - protected function getFilePaths($definitions) + protected function getFilePaths(array $definitions): array { $filePaths = []; @@ -160,8 +160,8 @@ protected function getFilePaths($definitions) return $filePaths; } - protected function fileIsNodeType($filename) + protected function fileIsNodeType(string $filename): bool { - return '.cnd' === substr($filename, -4); + return str_ends_with($filename, '.cnd'); } } diff --git a/src/PHPCR/Util/Console/Command/WorkspaceCreateCommand.php b/src/PHPCR/Util/Console/Command/WorkspaceCreateCommand.php index b9c14012..90ce44a9 100644 --- a/src/PHPCR/Util/Console/Command/WorkspaceCreateCommand.php +++ b/src/PHPCR/Util/Console/Command/WorkspaceCreateCommand.php @@ -58,7 +58,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int return 1; } - if (in_array($workspaceName, $workspace->getAccessibleWorkspaceNames())) { + if (in_array($workspaceName, $workspace->getAccessibleWorkspaceNames(), true)) { $output->writeln( sprintf('This repository already has a workspace called "%s"', $workspaceName) ); diff --git a/src/PHPCR/Util/Console/Helper/PhpcrConsoleDumperHelper.php b/src/PHPCR/Util/Console/Helper/PhpcrConsoleDumperHelper.php index f22c51b5..32b640e4 100644 --- a/src/PHPCR/Util/Console/Helper/PhpcrConsoleDumperHelper.php +++ b/src/PHPCR/Util/Console/Helper/PhpcrConsoleDumperHelper.php @@ -17,7 +17,7 @@ */ class PhpcrConsoleDumperHelper extends Helper { - public function getTreeWalker(OutputInterface $output, $options) + public function getTreeWalker(OutputInterface $output, $options): TreeWalker { $options = array_merge([ 'dump_uuids' => false, diff --git a/src/PHPCR/Util/Console/Helper/PhpcrHelper.php b/src/PHPCR/Util/Console/Helper/PhpcrHelper.php index 68608c98..5bb5a1b9 100644 --- a/src/PHPCR/Util/Console/Helper/PhpcrHelper.php +++ b/src/PHPCR/Util/Console/Helper/PhpcrHelper.php @@ -4,6 +4,7 @@ use PHPCR\NodeInterface; use PHPCR\PropertyInterface; +use PHPCR\Query\QueryInterface; use PHPCR\SessionInterface; use Symfony\Component\Console\Helper\Helper; use Symfony\Component\Console\Output\OutputInterface; @@ -18,10 +19,8 @@ class PhpcrHelper extends Helper { /** * The session bound to this helper. - * - * @var SessionInterface */ - protected $session; + protected SessionInterface $session; /** * Constructor. @@ -35,10 +34,8 @@ public function __construct(SessionInterface $session) /** * Get the session. - * - * @return SessionInterface */ - public function getSession() + public function getSession(): SessionInterface { return $this->session; } @@ -53,11 +50,11 @@ public function getName(): string * * Provides common processing for both touch and update commands. * - * @param OutputInterface $output used for status updates - * @param NodeInterface $node the node to manipulate - * @param array $operations to execute on that node + * @param OutputInterface $output used for status updates + * @param NodeInterface $node the node to manipulate + * @param array $operations to execute on that node */ - public function processNode(OutputInterface $output, NodeInterface $node, array $operations) + public function processNode(OutputInterface $output, NodeInterface $node, array $operations): void { $operations = array_merge([ 'setProp' => [], @@ -146,18 +143,15 @@ public function processNode(OutputInterface $output, NodeInterface $node, array * * @param string $language Language type - SQL, SQL2 * @param string $sql JCR Query string - * - * @return \PHPCR\Query\QueryInterface */ - public function createQuery($language, $sql) + public function createQuery(string $language, string $sql): QueryInterface { $language = $this->validateQueryLanguage($language); $session = $this->getSession(); $qm = $session->getWorkspace()->getQueryManager(); - $query = $qm->createQuery($sql, $language); - return $query; + return $qm->createQuery($sql, $language); } /** @@ -167,12 +161,12 @@ public function createQuery($language, $sql) * * @throws \Exception if the language is not supported */ - protected function validateQueryLanguage($language) + protected function validateQueryLanguage(string $language) { $qm = $this->getSession()->getWorkspace()->getQueryManager(); $langs = $qm->getSupportedQueryLanguages(); foreach ($langs as $lang) { - if (strtoupper($lang) === strtoupper($language)) { + if (0 === strcasecmp($lang, $language)) { return $lang; } } diff --git a/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperItemVisitor.php b/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperItemVisitor.php index fe334e17..a28551e7 100644 --- a/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperItemVisitor.php +++ b/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperItemVisitor.php @@ -14,17 +14,13 @@ abstract class ConsoleDumperItemVisitor implements ItemVisitorInterface { /** * Target for printing information. - * - * @var OutputInterface */ - protected $output; + protected OutputInterface $output; /** * Current depth in the tree. - * - * @var int */ - protected $level = 0; + protected int $level = 0; /** * Instantiate the console dumper visitor. @@ -36,10 +32,8 @@ public function __construct(OutputInterface $output) /** * Set the current depth level for indention. - * - * @param int $level */ - public function setLevel($level) + public function setLevel(int $level): void { $this->level = $level; } diff --git a/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperNodeVisitor.php b/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperNodeVisitor.php index 3656b18e..925cdc8c 100644 --- a/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperNodeVisitor.php +++ b/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperNodeVisitor.php @@ -15,22 +15,20 @@ class ConsoleDumperNodeVisitor extends ConsoleDumperItemVisitor { /** * Whether to print the UUIDs or not. - * - * @var bool */ - protected $identifiers; + protected bool $identifiers; /** * Show the full path for the node. */ - protected $showFullPath; + protected bool $showFullPath = false; /** * Instantiate the console dumper visitor. * * @param bool $identifiers whether to output the node UUID */ - public function __construct(OutputInterface $output, $identifiers = false) + public function __construct(OutputInterface $output, bool $identifiers = false) { parent::__construct($output); $this->identifiers = $identifiers; @@ -38,10 +36,8 @@ public function __construct(OutputInterface $output, $identifiers = false) /** * If to show the full path or not. - * - * @param bool $showFullPath */ - public function setShowFullPath($showFullPath) + public function setShowFullPath(bool $showFullPath): void { $this->showFullPath = $showFullPath; } @@ -53,7 +49,7 @@ public function setShowFullPath($showFullPath) * * @throws \Exception */ - public function visit(ItemInterface $item) + public function visit(ItemInterface $item): void { if (!$item instanceof NodeInterface) { throw new \Exception('Internal error: did not expect to visit a non-node object: '.get_class($item)); diff --git a/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperPropertyVisitor.php b/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperPropertyVisitor.php index 6202b495..55ddc74a 100644 --- a/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperPropertyVisitor.php +++ b/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperPropertyVisitor.php @@ -19,24 +19,19 @@ class ConsoleDumperPropertyVisitor extends ConsoleDumperItemVisitor * * @var int */ - protected $maxLineLength; - - /** - * Show the full path for each reference. - */ - protected $expandReferences; + protected mixed $maxLineLength; /** * @var string */ - private $refFormat; + private mixed $refFormat; /** * Instantiate property visitor. * - * @param array $options + * @param array $options */ - public function __construct(OutputInterface $output, $options = []) + public function __construct(OutputInterface $output, array $options = []) { $options = array_merge([ 'max_line_length' => 120, @@ -56,7 +51,7 @@ public function __construct(OutputInterface $output, $options = []) * * @throws \Exception */ - public function visit(ItemInterface $item) + public function visit(ItemInterface $item): void { if (!$item instanceof PropertyInterface) { throw new \Exception(sprintf('Internal error: did not expect to visit a non-property object: %s', is_object($item) ? get_class($item) : $item)); @@ -77,10 +72,10 @@ public function visit(ItemInterface $item) if (in_array($item->getType(), [ PropertyType::WEAKREFERENCE, PropertyType::REFERENCE, - ])) { + ], true)) { $referenceStrings = []; - if ('path' == $this->refFormat) { + if ('path' === $this->refFormat) { $references = (array) $item->getValue(); foreach ($references as $reference) { diff --git a/src/PHPCR/Util/Console/Helper/TreeDumper/SystemNodeFilter.php b/src/PHPCR/Util/Console/Helper/TreeDumper/SystemNodeFilter.php index 9c6e86c4..cffc9b88 100644 --- a/src/PHPCR/Util/Console/Helper/TreeDumper/SystemNodeFilter.php +++ b/src/PHPCR/Util/Console/Helper/TreeDumper/SystemNodeFilter.php @@ -17,11 +17,9 @@ class SystemNodeFilter implements TreeWalkerFilterInterface /** * Checks whether this item is a system item. * - * @return bool - * * @throws RepositoryException */ - public function mustVisit(ItemInterface $item) + public function mustVisit(ItemInterface $item): bool { return !NodeHelper::isSystemItem($item); } diff --git a/src/PHPCR/Util/NodeHelper.php b/src/PHPCR/Util/NodeHelper.php index 84e80900..6f2e1211 100644 --- a/src/PHPCR/Util/NodeHelper.php +++ b/src/PHPCR/Util/NodeHelper.php @@ -48,7 +48,7 @@ private function __construct() * @throws ConstraintViolationException * @throws VersionException */ - public static function createPath(SessionInterface $session, $path) + public static function createPath(SessionInterface $session, string $path): NodeInterface { $current = $session->getRootNode(); @@ -81,7 +81,7 @@ public static function createPath(SessionInterface $session, $path) * * @see isSystemItem */ - public static function purgeWorkspace(SessionInterface $session) + public static function purgeWorkspace(SessionInterface $session): void { $root = $session->getRootNode(); @@ -100,18 +100,6 @@ public static function purgeWorkspace(SessionInterface $session) } } - /** - * Kept as alias of purgeWorkspace for BC compatibility. - * - * @throws RepositoryException - * - * @deprecated - */ - public static function deleteAllNodes(SessionInterface $session) - { - self::purgeWorkspace($session); - } - /** * Determine whether this item is to be considered a system item that you * usually want to hide and that should not be removed when purging the @@ -121,14 +109,14 @@ public static function deleteAllNodes(SessionInterface $session) * * @throws RepositoryException */ - public static function isSystemItem(ItemInterface $item) + public static function isSystemItem(ItemInterface $item): bool { if ($item->getDepth() > 1) { return false; } $name = $item->getName(); - return 0 === strpos($name, 'jcr:') || 0 === strpos($name, 'rep:'); + return str_starts_with($name, 'jcr:') || str_starts_with($name, 'rep:'); } /** @@ -137,19 +125,20 @@ public static function isSystemItem(ItemInterface $item) * This method only checks for valid namespaces. All other exceptions must * be thrown by the addNodeAutoNamed implementation. * - * @param string[] $usedNames list of child names that is currently used and may not be chosen - * @param string[] $namespaces namespace prefix to uri map of all currently known namespaces - * @param string $defaultNamespace namespace prefix to use if the hint does not specify - * @param string $nameHint the name hint according to the API definition + * @param string[] $usedNames list of child names that is currently used and may not be chosen + * @param string[] $namespaces namespace prefix to uri map of all currently known namespaces + * @param string $defaultNamespace namespace prefix to use if the hint does not specify + * @param string|null $nameHint the name hint according to the API definition * * @return string A valid node name for this node + * @return string A valid node name for this node * + * @throws RepositoryException * @throws NamespaceException if a namespace prefix is provided in the * $nameHint which does not exist and this implementation performs * this validation immediately - * @throws RepositoryException */ - public static function generateAutoNodeName($usedNames, $namespaces, $defaultNamespace, $nameHint = null) + public static function generateAutoNodeName(array $usedNames, array $namespaces, string $defaultNamespace, string $nameHint = null): string { $usedNames = array_flip($usedNames); @@ -238,7 +227,7 @@ public static function generateAutoNodeName($usedNames, $namespaces, $defaultNam $ns = $matches[1]; $name = $matches[2]; - $prefix = array_search($ns, $namespaces); + $prefix = array_search($ns, $namespaces, true); if (!$prefix) { throw new NamespaceException("Invalid nameHint '$nameHint'"); } @@ -256,10 +245,8 @@ public static function generateAutoNodeName($usedNames, $namespaces, $defaultNam * @param string[] $usedNames names that are forbidden * @param string $prefix the prefix including the colon at the end * @param string $namepart start for the localname - * - * @return string */ - private static function generateWithPrefix($usedNames, $prefix, $namepart = '') + private static function generateWithPrefix(array $usedNames, string $prefix, string $namepart = ''): string { do { $name = $prefix.$namepart.mt_rand(); @@ -285,7 +272,7 @@ private static function generateWithPrefix($usedNames, $prefix, $namepart = '') * @return array the keys are elements to move, values the destination to * move before or null to move to the end */ - public static function calculateOrderBefore(array $old, array $new) + public static function calculateOrderBefore(array $old, array $new): array { $reorders = []; @@ -314,14 +301,14 @@ public static function calculateOrderBefore(array $old, array $new) // get the name of the next node $next = $new[$i + 1]; // if in the old order $c and next are not neighbors already, do the reorder command - if ($oldIndex[$current] + 1 != $oldIndex[$next]) { + if ($oldIndex[$current] + 1 !== $oldIndex[$next]) { $reorders[$current] = $next; $old = self::orderBeforeArray($current, $next, $old); $oldIndex = array_flip($old); } } else { // check if it's not already at the end of the nodes - if ($oldIndex[$current] != $len) { + if ($oldIndex[$current] !== $len) { $reorders[$current] = null; $old = self::orderBeforeArray($current, null, $old); $oldIndex = array_flip($old); @@ -336,32 +323,32 @@ public static function calculateOrderBefore(array $old, array $new) * Move the element $name of $list to right before $destination, * validating existence of all elements. * - * @param string $name name of the element to move - * @param string $destination name of the element $srcChildRelPath has - * to be ordered before, null to move to the end - * @param array $list the array of names + * @param string $name name of the element to move + * @param string|null $destination name of the element $srcChildRelPath has + * to be ordered before, null to move to the end + * @param array $list the array of names * * @return array The updated $nodes array with new order * * @throws ItemNotFoundException if $srcChildRelPath or $destChildRelPath are not found in $nodes */ - public static function orderBeforeArray($name, $destination, $list) + public static function orderBeforeArray(string $name, ?string $destination, array $list): array { // reindex the array so there are no gaps $list = array_values($list); - $oldpos = array_search($name, $list); + $oldpos = array_search($name, $list, true); if (false === $oldpos) { throw new ItemNotFoundException("$name is not a child of this node"); } - if (null == $destination) { + if (null === $destination) { // null means move to end unset($list[$oldpos]); $list[] = $name; } else { // insert before element $destination - $newpos = array_search($destination, $list); + $newpos = array_search($destination, $list, true); if (false === $newpos) { throw new ItemNotFoundException("$destination is not a child of this node"); } diff --git a/src/PHPCR/Util/PathHelper.php b/src/PHPCR/Util/PathHelper.php index 649ef73d..43c289bb 100644 --- a/src/PHPCR/Util/PathHelper.php +++ b/src/PHPCR/Util/PathHelper.php @@ -37,20 +37,19 @@ private function __construct() * move), meaning [] is not allowed. If your implementation does not * support same name siblings, just always pass true for this * @param bool $throw whether to throw an exception on validation errors - * @param array|bool $namespacePrefixes List of all known namespace prefixes. + * @param bool|array $namespacePrefixes List of all known namespace prefixes. * If specified, this method validates that the path contains no unknown prefixes. * * @return bool true if valid, false if not valid and $throw was false * * @throws RepositoryException if the path contains invalid characters and $throw is true */ - public static function assertValidAbsolutePath($path, $destination = false, $throw = true, $namespacePrefixes = false) + public static function assertValidAbsolutePath(string $path, bool $destination = false, bool $throw = true, bool|array $namespacePrefixes = false): bool { - if ((!is_string($path) && !is_numeric($path)) - || 0 === strlen($path) + if ('' === $path || '/' !== $path[0] - || strlen($path) > 1 && '/' === $path[strlen($path) - 1] || preg_match('-//|/\./|/\.\./-', $path) + || (strlen($path) > 1 && '/' === $path[strlen($path) - 1]) ) { return self::error("Invalid path '$path'", $throw); } @@ -93,7 +92,7 @@ public static function assertValidAbsolutePath($path, $destination = false, $thr * * @see http://www.day.com/specs/jcr/2.0/3_Repository_Model.html#3.2.2%20Local%20Names */ - public static function assertValidLocalName($name, $throw = true) + public static function assertValidLocalName(string $name, bool $throw = true): bool { if ('.' === $name || '..' === $name) { return self::error("Name may not be parent or self identifier: $name", $throw); @@ -124,16 +123,14 @@ public static function assertValidLocalName($name, $throw = true) * just to return false * * @return string The normalized path or false if $throw was false and the path invalid + * @return string The normalized path or false if $throw was false and the path invalid * * @throws RepositoryException if the path is not a valid absolute path and * $throw is true */ - public static function normalizePath($path, $destination = false, $throw = true) + public static function normalizePath(string $path, bool $destination = false, bool $throw = true): bool|string { - if (!is_string($path) && !is_numeric($path)) { - return self::error('Expected string but got '.gettype($path), $throw); - } - if (0 === strlen($path)) { + if ('' === $path) { return self::error('Path must not be of zero length', $throw); } @@ -191,15 +188,9 @@ public static function normalizePath($path, $destination = false, $throw = true) * @throws RepositoryException if the path can not be made into a valid * absolute path and $throw is true */ - public static function absolutizePath($path, $context, $destination = false, $throw = true) + public static function absolutizePath(string $path, string $context, bool $destination = false, bool $throw = true): bool|string { - if (!is_string($path) && !is_numeric($path)) { - return self::error('Expected string path but got '.gettype($path), $throw); - } - if (!is_string($context)) { - return self::error('Expected string context but got '.gettype($context), $throw); - } - if (0 === strlen($path)) { + if ('' === $path) { return self::error('Path must not be of zero length', $throw); } @@ -223,9 +214,9 @@ public static function absolutizePath($path, $context, $destination = false, $th * * @return string The relative path from $context to $path */ - public static function relativizePath($path, $context, $throw = true) + public static function relativizePath(string $path, string $context, bool $throw = true): bool|string { - if ($context !== substr($path, 0, strlen($context))) { + if (!str_starts_with($path, $context)) { return self::error("$path is not within $context", $throw); } @@ -239,7 +230,7 @@ public static function relativizePath($path, $context, $throw = true) * * @return string the path with the last segment removed */ - public static function getParentPath($path) + public static function getParentPath(string $path): string { if ('/' === $path) { return '/'; @@ -265,7 +256,7 @@ public static function getParentPath($path) * * @throws RepositoryException */ - public static function getNodeName($path) + public static function getNodeName(string $path): string { $strrpos = strrpos($path, '/'); @@ -289,7 +280,7 @@ public static function getNodeName($path) * * @throws RepositoryException */ - public static function getLocalNodeName($path) + public static function getLocalNodeName(string $path): string { $nodeName = self::getNodeName($path); $localName = strstr($nodeName, ':'); @@ -308,7 +299,7 @@ public static function getLocalNodeName($path) * * @return int with the path depth */ - public static function getPathDepth($path) + public static function getPathDepth(string $path): int { return substr_count(rtrim($path, '/'), '/'); } @@ -324,7 +315,7 @@ public static function getPathDepth($path) * * @throws RepositoryException */ - private static function error($msg, $throw) + private static function error(string $msg, bool $throw): bool { if ($throw) { throw new RepositoryException($msg); diff --git a/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php b/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php index b74f1af4..67506999 100644 --- a/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php +++ b/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php @@ -13,12 +13,7 @@ */ abstract class BaseQomToSqlQueryConverter { - /** - * The generator to use. - * - * @var BaseSqlGenerator - */ - protected $generator; + protected BaseSqlGenerator $generator; /** * Instantiate the converter. @@ -33,10 +28,8 @@ public function __construct(BaseSqlGenerator $generator) * 'FROM' Source * ['WHERE' Constraint] * ['ORDER BY' orderings]. - * - * @return string */ - public function convert(QOM\QueryObjectModelInterface $query) + public function convert(QOM\QueryObjectModelInterface $query): string { $columns = $this->convertColumns($query->getColumns()); $source = $this->convertSource($query->getSource()); @@ -56,30 +49,24 @@ public function convert(QOM\QueryObjectModelInterface $query) /** * Convert a source. This is different between SQL1 and SQL2. - * - * @return string */ - abstract protected function convertSource(QOM\SourceInterface $source); + abstract protected function convertSource(QOM\SourceInterface $source): string; /** * Convert a constraint. This is different between SQL1 and SQL2. - * - * @return string */ - abstract protected function convertConstraint(QOM\ConstraintInterface $constraint); + abstract protected function convertConstraint(QOM\ConstraintInterface $constraint): string; /** * Convert dynamic operand. This is different between SQL1 and SQL2. */ - abstract protected function convertDynamicOperand(QOM\DynamicOperandInterface $operand); + abstract protected function convertDynamicOperand(QOM\DynamicOperandInterface $operand): mixed; /** * Selector ::= nodeTypeName ['AS' selectorName] * nodeTypeName ::= Name. - * - * @return string */ - protected function convertSelector(QOM\SelectorInterface $selector) + protected function convertSelector(QOM\SelectorInterface $selector): string { return $this->generator->evalSelector($selector->getNodeTypeName(), $selector->getSelectorName()); } @@ -97,10 +84,8 @@ protected function convertSelector(QOM\SelectorInterface $selector) * GreaterThan ::= '>' * GreaterThanOrEqualTo ::= '>=' * Like ::= 'LIKE' - * - * @return string */ - protected function convertComparison(QOM\ComparisonInterface $comparison) + protected function convertComparison(QOM\ComparisonInterface $comparison): string { $operand1 = $this->convertDynamicOperand($comparison->getOperand1()); $operand2 = $this->convertStaticOperand($comparison->getOperand2()); @@ -118,10 +103,8 @@ protected function convertComparison(QOM\ComparisonInterface $comparison) * * Note: The negation, 'NOT x IS NOT NULL' * can be written 'x IS NULL' - * - * @return string */ - protected function convertPropertyExistence(QOM\PropertyExistenceInterface $constraint) + protected function convertPropertyExistence(QOM\PropertyExistenceInterface $constraint): string { return $this->generator->evalPropertyExistence( $constraint->getSelectorName(), @@ -137,10 +120,8 @@ protected function convertPropertyExistence(QOM\PropertyExistenceInterface $cons * // If only one selector exists in this query, * explicit specification of the selectorName * preceding the propertyName is optional. - * - * @return string */ - protected function convertFullTextSearch(QOM\FullTextSearchInterface $constraint) + protected function convertFullTextSearch(QOM\FullTextSearchInterface $constraint): string { $searchExpression = $this->convertFullTextSearchExpression($constraint->getFullTextSearchExpression()); @@ -151,10 +132,8 @@ protected function convertFullTextSearch(QOM\FullTextSearchInterface $constraint * FullTextSearchExpression ::= BindVariable | ''' FullTextSearchLiteral '''. * * @param string|QOM\StaticOperandInterface $expr - * - * @return string */ - protected function convertFullTextSearchExpression($expr) + protected function convertFullTextSearchExpression($expr): string { if ($expr instanceof QOM\BindVariableValueInterface) { return $this->convertBindVariable($expr->getBindVariableName()); @@ -189,11 +168,9 @@ protected function convertFullTextSearchExpression($expr) * BindVariableValue ::= '$'bindVariableName * bindVariableName ::= Prefix * - * @return string - * * @throws \InvalidArgumentException */ - protected function convertStaticOperand(QOM\StaticOperandInterface $operand) + protected function convertStaticOperand(QOM\StaticOperandInterface $operand): string { if ($operand instanceof QOM\BindVariableValueInterface) { return $this->convertBindVariable($operand->getBindVariableName()); @@ -208,10 +185,8 @@ protected function convertStaticOperand(QOM\StaticOperandInterface $operand) /** * PropertyValue ::= [selectorName'.'] propertyName // If only one selector exists. - * - * @return string */ - protected function convertPropertyValue(QOM\PropertyValueInterface $value) + protected function convertPropertyValue(QOM\PropertyValueInterface $value): string { return $this->generator->evalPropertyValue( $value->getPropertyName(), @@ -227,10 +202,8 @@ protected function convertPropertyValue(QOM\PropertyValueInterface $value) * Descending ::= 'DESC'. * * @param QOM\OrderingInterface[] $orderings - * - * @return string */ - protected function convertOrderings(array $orderings) + protected function convertOrderings(array $orderings): string { $list = []; foreach ($orderings as $ordering) { @@ -246,12 +219,8 @@ protected function convertOrderings(array $orderings) * Path ::= '[' quotedPath ']' | '[' simplePath ']' | simplePath * quotedPath ::= A JCR Path that contains non-SQL-legal characters * simplePath ::= A JCR Name that contains only SQL-legal characters. - * - * @param string $path - * - * @return string */ - protected function convertPath($path) + protected function convertPath(string $path): string { return $this->generator->evalPath($path); } @@ -259,22 +228,16 @@ protected function convertPath($path) /** * BindVariableValue ::= '$'bindVariableName * bindVariableName ::= Prefix. - * - * @param string $var - * - * @return string */ - protected function convertBindVariable($var) + protected function convertBindVariable(string $var): string { return $this->generator->evalBindVariable($var); } /** * Literal ::= CastLiteral | UncastLiteral. - * - * @return string */ - protected function convertLiteral($literal) + protected function convertLiteral(mixed $literal): string { return $this->generator->evalLiteral($literal); } @@ -289,10 +252,8 @@ protected function convertLiteral($literal) * columnName ::= Name. * * @param QOM\ColumnInterface[] $columns - * - * @return string */ - protected function convertColumns(array $columns) + protected function convertColumns(array $columns): string { $list = []; diff --git a/src/PHPCR/Util/QOM/BaseSqlGenerator.php b/src/PHPCR/Util/QOM/BaseSqlGenerator.php index 5226cd4d..f1b43f1c 100644 --- a/src/PHPCR/Util/QOM/BaseSqlGenerator.php +++ b/src/PHPCR/Util/QOM/BaseSqlGenerator.php @@ -14,10 +14,7 @@ */ abstract class BaseSqlGenerator { - /** - * @var ValueConverter - */ - protected $valueConverter; + protected ValueConverter $valueConverter; public function __construct(ValueConverter $valueConverter) { @@ -29,15 +26,8 @@ public function __construct(ValueConverter $valueConverter) * 'FROM' Source * ['WHERE' Constraint] * ['ORDER BY' orderings]. - * - * @param string $source - * @param string $columns - * @param string $constraint - * @param string $orderings - * - * @return string */ - public function evalQuery($source, $columns, $constraint = '', $orderings = '') + public function evalQuery(string $source, string $columns, string $constraint = '', string $orderings = ''): string { $sql = "SELECT $columns FROM $source"; @@ -54,52 +44,32 @@ public function evalQuery($source, $columns, $constraint = '', $orderings = '') /** * And ::= constraint1 'AND' constraint2. - * - * @param string $constraint1 - * @param string $constraint2 - * - * @return string */ - public function evalAnd($constraint1, $constraint2) + public function evalAnd(string $constraint1, string $constraint2): string { return "($constraint1 AND $constraint2)"; } /** * Or ::= constraint1 'OR' constraint2. - * - * @param string $constraint1 - * @param string $constraint2 - * - * @return string */ - public function evalOr($constraint1, $constraint2) + public function evalOr(string $constraint1, string $constraint2): string { return "($constraint1 OR $constraint2)"; } /** * Not ::= 'NOT' Constraint. - * - * @param string $constraint - * - * @return string */ - public function evalNot($constraint) + public function evalNot(string $constraint): string { return "(NOT $constraint)"; } /** * Comparison ::= DynamicOperand Operator StaticOperand. - * - * @param string $operand1 - * @param string $operator - * @param string $operand2 - * - * @return string */ - public function evalComparison($operand1, $operator, $operand2) + public function evalComparison(string $operand1, string $operator, string $operand2): string { return "$operand1 $operator $operand2"; } @@ -108,12 +78,8 @@ public function evalComparison($operand1, $operator, $operand2) * Operator ::= EqualTo | NotEqualTo | LessThan | * LessThanOrEqualTo | GreaterThan | * GreaterThanOrEqualTo | Like. - * - * @param string $operator - * - * @return string */ - public function evalOperator($operator) + public function evalOperator(string $operator): string { switch ($operator) { case Constants::JCR_OPERATOR_EQUAL_TO: @@ -137,24 +103,16 @@ public function evalOperator($operator) /** * LowerCase ::= 'LOWER(' DynamicOperand ')'. - * - * @param string $operand - * - * @return string */ - public function evalLower($operand) + public function evalLower(string $operand): string { return "LOWER($operand)"; } /** * LowerCase ::= 'UPPER(' DynamicOperand ')'. - * - * @param string $operand - * - * @return string */ - public function evalUpper($operand) + public function evalUpper(string $operand): string { return "UPPER($operand)"; } @@ -162,9 +120,9 @@ public function evalUpper($operand) /** * orderings ::= Ordering {',' Ordering}. * - * @return string + * @param string[] $orderings */ - public function evalOrderings($orderings) + public function evalOrderings(array $orderings): string { $sql = ''; @@ -181,10 +139,8 @@ public function evalOrderings($orderings) /** * Ordering ::= DynamicOperand [Order]. - * - * @return string */ - public function evalOrdering($operand, $order) + public function evalOrdering(string $operand, string $order): string { return "$operand $order"; } @@ -193,28 +149,21 @@ public function evalOrdering($operand, $order) * Order ::= Ascending | Descending * Ascending ::= 'ASC' * Descending ::= 'DESC'. - * - * @return string */ - public function evalOrder($order) + public function evalOrder($order): string { - switch ($order) { - case Constants::JCR_ORDER_ASCENDING: - return 'ASC'; - case Constants::JCR_ORDER_DESCENDING: - return 'DESC'; - } - - return ''; + return match ($order) { + Constants::JCR_ORDER_ASCENDING => 'ASC', + Constants::JCR_ORDER_DESCENDING => 'DESC', + default => '', + }; } /** * BindVariableValue ::= '$'bindVariableName * bindVariableName ::= Prefix. - * - * @return string */ - public function evalBindVariable($var) + public function evalBindVariable(string $var): string { return '$'.$var; } @@ -222,13 +171,11 @@ public function evalBindVariable($var) /** * Escape the illegal characters for inclusion in a fulltext statement. Escape Character is \\. * - * @param string $string - * * @return string Escaped String * * @see http://jackrabbit.apache.org/api/1.4/org/apache/jackrabbit/util/Text.html #escapeIllegalJcrChars */ - public function evalFullText($string) + public function evalFullText(string $string): string { $illegalCharacters = [ '!' => '\\!', '(' => '\\(', ':' => '\\:', '^' => '\\^', @@ -241,10 +188,8 @@ public function evalFullText($string) /** * Literal ::= CastLiteral | UncastLiteral. - * - * @return string */ - public function evalLiteral($literal) + public function evalLiteral(mixed $literal): string { if ($literal instanceof \DateTime) { $string = $this->valueConverter->convertType($literal, PropertyType::STRING); @@ -272,86 +217,40 @@ public function evalLiteral($literal) /** * Cast a literal. This is different between SQL1 and SQL2. - * - * @param string $literal - * @param string $type - * - * @return string */ - abstract public function evalCastLiteral($literal, $type); + abstract public function evalCastLiteral(string $literal, string $type): string; /** * @param string $nodeTypeName The node type of the selector. If it does not contain starting and ending * brackets ([]), they will be added automatically. * @param string|null $selectorName The selector name. If it is different than the nodeTypeName, the alias is * declared if supported by the SQL dialect. - * - * @return string */ - abstract public function evalSelector($nodeTypeName, $selectorName = null); + abstract public function evalSelector(string $nodeTypeName, string $selectorName = null): string; /** * Evaluate a path. This is different between SQL1 and SQL2. - * - * @param string $path - * - * @return string|null */ - abstract public function evalPath($path); + abstract public function evalPath(string $path): string; /** * columns ::= (Column ',' {Column}) | '*'. * * With empty columns, SQL1 is different from SQL2 * - * @return string + * @param iterable $columns */ - abstract public function evalColumns($columns); + abstract public function evalColumns(iterable $columns): string; - /** - * @param string $selectorName - * @param string $propertyName - * @param string $colname - * - * @return string - */ - abstract public function evalColumn($selectorName, $propertyName = null, $colname = null); + abstract public function evalColumn(string $selectorName, string $propertyName = null, string $colname = null): string; - /** - * @return string - */ - abstract public function evalPropertyExistence($selectorName, $propertyName); + abstract public function evalPropertyExistence(?string $selectorName, string $propertyName): string; - /** - * @param string $propertyName - * @param string $selectorName - * - * @return string - */ - abstract public function evalPropertyValue($propertyName, $selectorName = null); + abstract public function evalPropertyValue(string $propertyName, string $selectorName = null); - /** - * @param string $path - * @param string $selectorName - * - * @return string - */ - abstract public function evalChildNode($path, $selectorName = null); + abstract public function evalChildNode(string $path, string $selectorName = null); - /** - * @param string $path - * @param string $selectorName - * - * @return string - */ - abstract public function evalDescendantNode($path, $selectorName = null); + abstract public function evalDescendantNode(string $path, string $selectorName = null): string; - /** - * @param string $selectorName - * @param string $searchExpression - * @param string $propertyName - * - * @return string - */ - abstract public function evalFullTextSearch($selectorName, $searchExpression, $propertyName = null); + abstract public function evalFullTextSearch(string $selectorName, string $searchExpression, string $propertyName = null): string; } diff --git a/src/PHPCR/Util/QOM/NotSupportedConstraintException.php b/src/PHPCR/Util/QOM/NotSupportedConstraintException.php index 39a543d0..3d14c257 100644 --- a/src/PHPCR/Util/QOM/NotSupportedConstraintException.php +++ b/src/PHPCR/Util/QOM/NotSupportedConstraintException.php @@ -13,11 +13,12 @@ class NotSupportedConstraintException extends \RuntimeException /** * Create the exception with an explaining message. * - * @param string $constraint the constraint expression that is not supported + * @param object $constraint the constraint expression that is not supported */ - public function __construct($constraint) + public static function fromConstraint(object $constraint): self { $class = get_class($constraint); - parent::__construct("$class is not supported by this query language"); + + return new self("$class is not supported by this query language"); } } diff --git a/src/PHPCR/Util/QOM/NotSupportedOperandException.php b/src/PHPCR/Util/QOM/NotSupportedOperandException.php index af6457ea..e9824888 100644 --- a/src/PHPCR/Util/QOM/NotSupportedOperandException.php +++ b/src/PHPCR/Util/QOM/NotSupportedOperandException.php @@ -13,11 +13,12 @@ class NotSupportedOperandException extends \RuntimeException /** * Create the exception with an explaining message. * - * @param string $operand the constraint expression that is not supported + * @param object $operand the constraint expression that is not supported */ - public function __construct($operand) + public static function fromOperand(object $operand): self { $class = get_class($operand); - parent::__construct("$class is not supported by this query language"); + + return new self("$class is not supported by this query language"); } } diff --git a/src/PHPCR/Util/QOM/QomToSql1QueryConverter.php b/src/PHPCR/Util/QOM/QomToSql1QueryConverter.php index 4c75be44..cb89b152 100644 --- a/src/PHPCR/Util/QOM/QomToSql1QueryConverter.php +++ b/src/PHPCR/Util/QOM/QomToSql1QueryConverter.php @@ -15,11 +15,9 @@ class QomToSql1QueryConverter extends BaseQomToSqlQueryConverter /** * Source ::= Selector. * - * @return string - * * @throws \InvalidArgumentException */ - protected function convertSource(QOM\SourceInterface $source) + protected function convertSource(QOM\SourceInterface $source): string { if ($source instanceof QOM\SelectorInterface) { return $this->convertSelector($source); @@ -37,12 +35,10 @@ protected function convertSource(QOM\SourceInterface $source) * Or ::= constraint1 'OR' constraint2 * Not ::= 'NOT' Constraint * - * @return string - * * @throws \InvalidArgumentException * @throws NotSupportedConstraintException */ - protected function convertConstraint(QOM\ConstraintInterface $constraint) + protected function convertConstraint(QOM\ConstraintInterface $constraint): string { if ($constraint instanceof QOM\AndInterface) { return $this->generator->evalAnd( @@ -68,12 +64,13 @@ protected function convertConstraint(QOM\ConstraintInterface $constraint) if ($constraint instanceof QOM\PropertyExistenceInterface) { return $this->convertPropertyExistence($constraint); - } elseif ($constraint instanceof QOM\FullTextSearchInterface) { + } + if ($constraint instanceof QOM\FullTextSearchInterface) { return $this->convertFullTextSearch($constraint); } if ($constraint instanceof QOM\SameNodeInterface) { - throw new NotSupportedConstraintException($constraint); + throw NotSupportedConstraintException::fromConstraint($constraint); } if ($constraint instanceof QOM\ChildNodeInterface) { @@ -100,43 +97,41 @@ protected function convertConstraint(QOM\ConstraintInterface $constraint) * LowerCase ::= 'LOWER(' DynamicOperand ')' * UpperCase ::= 'UPPER(' DynamicOperand ')' * - * @return string - * * @throws NotSupportedOperandException * @throws \InvalidArgumentException */ - protected function convertDynamicOperand(QOM\DynamicOperandInterface $operand) + protected function convertDynamicOperand(QOM\DynamicOperandInterface $operand): string { if ($operand instanceof QOM\PropertyValueInterface) { return $this->convertPropertyValue($operand); } if ($operand instanceof QOM\LengthInterface) { - throw new NotSupportedOperandException($operand); + throw NotSupportedOperandException::fromOperand($operand); } if ($operand instanceof QOM\NodeNameInterface) { - throw new NotSupportedOperandException($operand); + throw NotSupportedOperandException::fromOperand($operand); } if ($operand instanceof QOM\NodeLocalNameInterface) { - throw new NotSupportedOperandException($operand); + throw NotSupportedOperandException::fromOperand($operand); } if ($operand instanceof QOM\FullTextSearchScoreInterface) { - throw new NotSupportedOperandException($operand); + throw NotSupportedOperandException::fromOperand($operand); } if ($operand instanceof QOM\LowerCaseInterface) { - $operand = $this->convertDynamicOperand($operand->getOperand()); + $operandText = $this->convertDynamicOperand($operand->getOperand()); - return $this->generator->evalLower($operand); + return $this->generator->evalLower($operandText); } if ($operand instanceof QOM\UpperCaseInterface) { - $operand = $this->convertDynamicOperand($operand->getOperand()); + $operandText = $this->convertDynamicOperand($operand->getOperand()); - return $this->generator->evalUpper($operand); + return $this->generator->evalUpper($operandText); } // This should not happen, but who knows... diff --git a/src/PHPCR/Util/QOM/QomToSql2QueryConverter.php b/src/PHPCR/Util/QOM/QomToSql2QueryConverter.php index b5dd984c..09d63ebb 100644 --- a/src/PHPCR/Util/QOM/QomToSql2QueryConverter.php +++ b/src/PHPCR/Util/QOM/QomToSql2QueryConverter.php @@ -15,11 +15,9 @@ class QomToSql2QueryConverter extends BaseQomToSqlQueryConverter /** * Source ::= Selector | Join. * - * @return string - * * @throws \InvalidArgumentException */ - protected function convertSource(QOM\SourceInterface $source) + protected function convertSource(QOM\SourceInterface $source): string { if ($source instanceof QOM\SelectorInterface) { return $this->convertSelector($source); @@ -41,10 +39,8 @@ protected function convertSource(QOM\SourceInterface $source) * Inner ::= 'INNER' * LeftOuter ::= 'LEFT OUTER' * RightOuter ::= 'RIGHT OUTER' - * - * @return string */ - protected function convertJoin(QOM\JoinInterface $join) + protected function convertJoin(QOM\JoinInterface $join): string { if (!$this->generator instanceof Sql2Generator) { throw new NotSupportedOperandException('Only SQL2 supports join'); @@ -63,11 +59,9 @@ protected function convertJoin(QOM\JoinInterface $join) * ChildNodeJoinCondition | * DescendantNodeJoinCondition. * - * @return string - * * @throws \InvalidArgumentException */ - protected function convertJoinCondition(QOM\JoinConditionInterface $condition) + protected function convertJoinCondition(QOM\JoinConditionInterface $condition): string { if ($condition instanceof QOM\EquiJoinConditionInterface) { return $this->convertEquiJoinCondition($condition); @@ -93,10 +87,8 @@ protected function convertJoinCondition(QOM\JoinConditionInterface $condition) * selector2Name ::= selectorName * property1Name ::= propertyName * property2Name ::= propertyName. - * - * @return string */ - protected function convertEquiJoinCondition(QOM\EquiJoinConditionInterface $condition) + protected function convertEquiJoinCondition(QOM\EquiJoinConditionInterface $condition): string { if (!$this->generator instanceof Sql2Generator) { throw new NotSupportedOperandException('Only SQL2 supports equi join condition'); @@ -116,10 +108,8 @@ protected function convertEquiJoinCondition(QOM\EquiJoinConditionInterface $cond * selector2Name * [',' selector2Path] ')' * selector2Path ::= Path. - * - * @return string */ - protected function convertSameNodeJoinCondition(QOM\SameNodeJoinConditionInterface $condition) + protected function convertSameNodeJoinCondition(QOM\SameNodeJoinConditionInterface $condition): string { if (!$this->generator instanceof Sql2Generator) { throw new NotSupportedOperandException('Only SQL2 supports same node join condition'); @@ -138,10 +128,8 @@ protected function convertSameNodeJoinCondition(QOM\SameNodeJoinConditionInterfa * parentSelectorName ')' * childSelectorName ::= selectorName * parentSelectorName ::= selectorName. - * - * @return string */ - protected function convertChildNodeJoinCondition(QOM\ChildNodeJoinConditionInterface $condition) + protected function convertChildNodeJoinCondition(QOM\ChildNodeJoinConditionInterface $condition): string { if (!$this->generator instanceof Sql2Generator) { throw new NotSupportedOperandException('Only SQL2 supports child node join condition'); @@ -159,10 +147,8 @@ protected function convertChildNodeJoinCondition(QOM\ChildNodeJoinConditionInter * ancestorSelectorName ')' * descendantSelectorName ::= selectorName * ancestorSelectorName ::= selectorName. - * - * @return string */ - protected function convertDescendantNodeJoinCondition(QOM\DescendantNodeJoinConditionInterface $condition) + protected function convertDescendantNodeJoinCondition(QOM\DescendantNodeJoinConditionInterface $condition): string { if (!$this->generator instanceof Sql2Generator) { throw new NotSupportedOperandException('Only SQL2 supports descendant node join condition'); @@ -195,11 +181,9 @@ protected function convertDescendantNodeJoinCondition(QOM\DescendantNodeJoinCond * // If only one selector exists in this query, explicit * specification of the selectorName is optional * - * @return string - * * @throws \InvalidArgumentException */ - protected function convertConstraint(QOM\ConstraintInterface $constraint) + protected function convertConstraint(QOM\ConstraintInterface $constraint): string { if ($constraint instanceof QOM\AndInterface) { return $this->generator->evalAnd( @@ -271,11 +255,9 @@ protected function convertConstraint(QOM\ConstraintInterface $constraint) * LowerCase ::= 'LOWER(' DynamicOperand ')' * UpperCase ::= 'UPPER(' DynamicOperand ')' * - * @return string - * * @throws \InvalidArgumentException */ - protected function convertDynamicOperand(QOM\DynamicOperandInterface $operand) + protected function convertDynamicOperand(QOM\DynamicOperandInterface $operand): string { if ($operand instanceof QOM\PropertyValueInterface) { return $this->convertPropertyValue($operand); diff --git a/src/PHPCR/Util/QOM/QueryBuilder.php b/src/PHPCR/Util/QOM/QueryBuilder.php index eb6211b8..9205152b 100644 --- a/src/PHPCR/Util/QOM/QueryBuilder.php +++ b/src/PHPCR/Util/QOM/QueryBuilder.php @@ -26,80 +26,62 @@ class QueryBuilder { /** The builder states. */ - public const STATE_DIRTY = 0; - public const STATE_CLEAN = 1; + private const STATE_DIRTY = 0; + private const STATE_CLEAN = 1; /** * @var int The state of the query object. Can be dirty or clean. */ - private $state = self::STATE_CLEAN; + private int $state = self::STATE_CLEAN; /** - * @var QueryObjectModelFactoryInterface QOMFactory + * @var int the offset to retrieve only a slice of results */ - private $qomFactory; + private int $firstResult = 0; /** - * @var int the maximum number of results to retrieve + * @var int The maximum number of results to retrieve. 0 sets no maximum. */ - private $firstResult; + private int $maxResults = 0; /** - * @var int the maximum number of results to retrieve + * @var OrderingInterface[] with the orderings that determine the order of the result */ - private $maxResults; + private array $orderings = []; - /** - * @var array with the orderings that determine the order of the result - */ - private $orderings = []; - - /** - * @var ConstraintInterface to apply to the query - */ - private $constraint; + private ?ConstraintInterface $constraint = null; /** - * @var array with the columns to be selected + * @var ColumnInterface[] the columns to be selected */ - private $columns = []; + private array $columns = []; - /** - * @var SourceInterface source of the query - */ - private $source; + private ?SourceInterface $source = null; - /** - * QOM tree. - * - * @var QueryObjectModelInterface - */ - private $query; + private ?QueryObjectModelInterface $query = null; /** - * @var array the query parameters + * @var array the query parameters */ - private $params = []; + private array $params = []; /** * Initializes a new QueryBuilder. */ - public function __construct(QueryObjectModelFactoryInterface $qomFactory) - { - $this->qomFactory = $qomFactory; + public function __construct( + private QueryObjectModelFactoryInterface $qomFactory + ) { } /** * Get a query builder instance from an existing query. * - * @param string $statement the statement in the specified language - * @param string $language the query language - * - * @return QueryBuilder this QueryBuilder instance + * @param string|QueryObjectModelInterface $statement the statement in the specified language + * @param string $language the query language * * @throws \InvalidArgumentException */ - public function setFromQuery($statement, $language) + public function setFromQuery(string|QueryObjectModelInterface $statement, string $language): static { if (QueryInterface::JCR_SQL2 === $language) { $converter = new Sql2ToQomQueryConverter($this->qomFactory); @@ -121,10 +103,8 @@ public function setFromQuery($statement, $language) /** * Get the associated QOMFactory for this query builder. - * - * @return QueryObjectModelFactoryInterface */ - public function getQOMFactory() + public function getQOMFactory(): QueryObjectModelFactoryInterface { return $this->qomFactory; } @@ -132,7 +112,7 @@ public function getQOMFactory() /** * Shortcut for getQOMFactory(). */ - public function qomf() + public function qomf(): QueryObjectModelFactoryInterface { return $this->getQOMFactory(); } @@ -141,10 +121,8 @@ public function qomf() * sets the position of the first result to retrieve (the "offset"). * * @param int $firstResult the First result to return - * - * @return QueryBuilder this QueryBuilder instance */ - public function setFirstResult($firstResult) + public function setFirstResult(int $firstResult): static { $this->firstResult = $firstResult; @@ -157,7 +135,7 @@ public function setFirstResult($firstResult) * * @return int the position of the first result */ - public function getFirstResult() + public function getFirstResult(): int { return $this->firstResult; } @@ -166,10 +144,8 @@ public function getFirstResult() * Sets the maximum number of results to retrieve (the "limit"). * * @param int $maxResults the maximum number of results to retrieve - * - * @return QueryBuilder this QueryBuilder instance */ - public function setMaxResults($maxResults) + public function setMaxResults(int $maxResults): static { $this->maxResults = $maxResults; @@ -179,10 +155,8 @@ public function setMaxResults($maxResults) /** * Gets the maximum number of results the query object was set to retrieve (the "limit"). * Returns NULL if {@link setMaxResults} was not applied to this query builder. - * - * @return int maximum number of results */ - public function getMaxResults() + public function getMaxResults(): int { return $this->maxResults; } @@ -192,7 +166,7 @@ public function getMaxResults() * * @return OrderingInterface[] orderings to apply */ - public function getOrderings() + public function getOrderings(): array { return $this->orderings; } @@ -203,11 +177,9 @@ public function getOrderings() * @param DynamicOperandInterface $sort the ordering expression * @param string $order the ordering direction * - * @return QueryBuilder this QueryBuilder instance - * * @throws \InvalidArgumentException */ - public function addOrderBy(DynamicOperandInterface $sort, $order = 'ASC') + public function addOrderBy(DynamicOperandInterface $sort, string $order = 'ASC'): static { $order = strtoupper($order); @@ -232,10 +204,8 @@ public function addOrderBy(DynamicOperandInterface $sort, $order = 'ASC') * * @param DynamicOperandInterface $sort the ordering expression * @param string $order the ordering direction - * - * @return QueryBuilder this QueryBuilder instance */ - public function orderBy(DynamicOperandInterface $sort, $order = 'ASC') + public function orderBy(DynamicOperandInterface $sort, string $order = 'ASC'): static { $this->orderings = []; $this->addOrderBy($sort, $order); @@ -246,10 +216,8 @@ public function orderBy(DynamicOperandInterface $sort, $order = 'ASC') /** * Specifies one restriction (may be simple or composed). * Replaces any previously specified restrictions, if any. - * - * @return QueryBuilder this QueryBuilder instance */ - public function where(ConstraintInterface $constraint) + public function where(ConstraintInterface $constraint): static { $this->state = self::STATE_DIRTY; $this->constraint = $constraint; @@ -259,10 +227,8 @@ public function where(ConstraintInterface $constraint) /** * Returns the constraint to apply. - * - * @return ConstraintInterface the constraint to be applied */ - public function getConstraint() + public function getConstraint(): ?ConstraintInterface { return $this->constraint; } @@ -279,10 +245,8 @@ public function getConstraint() * * If there is no previous constraint then it will simply store the * provided one - * - * @return QueryBuilder this QueryBuilder instance */ - public function andWhere(ConstraintInterface $constraint) + public function andWhere(ConstraintInterface $constraint): static { $this->state = self::STATE_DIRTY; @@ -307,10 +271,8 @@ public function andWhere(ConstraintInterface $constraint) * * If there is no previous constraint then it will simply store the * provided one - * - * @return QueryBuilder this QueryBuilder instance */ - public function orWhere(ConstraintInterface $constraint) + public function orWhere(ConstraintInterface $constraint): static { $this->state = self::STATE_DIRTY; @@ -328,7 +290,7 @@ public function orWhere(ConstraintInterface $constraint) * * @return ColumnInterface[] The columns to be selected */ - public function getColumns() + public function getColumns(): array { return $this->columns; } @@ -337,10 +299,8 @@ public function getColumns() * Sets the columns to be selected. * * @param ColumnInterface[] $columns The columns to be selected - * - * @return QueryBuilder this QueryBuilder instance */ - public function setColumns(array $columns) + public function setColumns(array $columns): static { $this->columns = $columns; @@ -350,14 +310,8 @@ public function setColumns(array $columns) /** * Identifies a property in the specified or default selector to include in the tabular view of query results. * Replaces any previously specified columns to be selected if any. - * - * @param string $selectorName - * @param string $propertyName - * @param string $columnName - * - * @return QueryBuilder this QueryBuilder instance */ - public function select($selectorName, $propertyName, $columnName = null) + public function select(string $selectorName, string $propertyName, string $columnName = null): static { $this->state = self::STATE_DIRTY; $this->columns = [$this->qomFactory->column($selectorName, $propertyName, $columnName)]; @@ -367,14 +321,8 @@ public function select($selectorName, $propertyName, $columnName = null) /** * Adds a property in the specified or default selector to include in the tabular view of query results. - * - * @param string $selectorName - * @param string $propertyName - * @param string $columnName - * - * @return QueryBuilder this QueryBuilder instance */ - public function addSelect($selectorName, $propertyName, $columnName = null) + public function addSelect(string $selectorName, string $propertyName, string $columnName = null): static { $this->state = self::STATE_DIRTY; @@ -386,10 +334,8 @@ public function addSelect($selectorName, $propertyName, $columnName = null) /** * Sets the default Selector or the node-tuple Source. Can be a selector * or a join. - * - * @return QueryBuilder this QueryBuilder instance */ - public function from(SourceInterface $source) + public function from(SourceInterface $source): static { $this->state = self::STATE_DIRTY; $this->source = $source; @@ -402,7 +348,7 @@ public function from(SourceInterface $source) * * @return SourceInterface the default selector */ - public function getSource() + public function getSource(): ?SourceInterface { return $this->source; } @@ -410,11 +356,9 @@ public function getSource() /** * Performs an inner join between the stored source and the supplied source. * - * @return QueryBuilder this QueryBuilder instance - * * @throws \RuntimeException if there is not an existing source */ - public function join(SourceInterface $rightSource, JoinConditionInterface $joinCondition) + public function join(SourceInterface $rightSource, JoinConditionInterface $joinCondition): static { return $this->innerJoin($rightSource, $joinCondition); } @@ -422,11 +366,9 @@ public function join(SourceInterface $rightSource, JoinConditionInterface $joinC /** * Performs an inner join between the stored source and the supplied source. * - * @return QueryBuilder this QueryBuilder instance - * * @throws \RuntimeException if there is not an existing source */ - public function innerJoin(SourceInterface $rightSource, JoinConditionInterface $joinCondition) + public function innerJoin(SourceInterface $rightSource, JoinConditionInterface $joinCondition): static { return $this->joinWithType($rightSource, QueryObjectModelConstantsInterface::JCR_JOIN_TYPE_INNER, $joinCondition); } @@ -434,11 +376,9 @@ public function innerJoin(SourceInterface $rightSource, JoinConditionInterface $ /** * Performs an left outer join between the stored source and the supplied source. * - * @return QueryBuilder this QueryBuilder instance - * * @throws \RuntimeException if there is not an existing source */ - public function leftJoin(SourceInterface $rightSource, JoinConditionInterface $joinCondition) + public function leftJoin(SourceInterface $rightSource, JoinConditionInterface $joinCondition): static { return $this->joinWithType($rightSource, QueryObjectModelConstantsInterface::JCR_JOIN_TYPE_LEFT_OUTER, $joinCondition); } @@ -446,11 +386,9 @@ public function leftJoin(SourceInterface $rightSource, JoinConditionInterface $j /** * Performs a right outer join between the stored source and the supplied source. * - * @return QueryBuilder this QueryBuilder instance - * * @throws \RuntimeException if there is not an existing source */ - public function rightJoin(SourceInterface $rightSource, JoinConditionInterface $joinCondition) + public function rightJoin(SourceInterface $rightSource, JoinConditionInterface $joinCondition): static { return $this->joinWithType($rightSource, QueryObjectModelConstantsInterface::JCR_JOIN_TYPE_RIGHT_OUTER, $joinCondition); } @@ -460,11 +398,9 @@ public function rightJoin(SourceInterface $rightSource, JoinConditionInterface $ * * @param string $joinType as specified in PHPCR\Query\QOM\QueryObjectModelConstantsInterface * - * @return QueryBuilder this QueryBuilder instance - * * @throws \RuntimeException if there is not an existing source */ - public function joinWithType(SourceInterface $rightSource, $joinType, JoinConditionInterface $joinCondition) + public function joinWithType(SourceInterface $rightSource, string $joinType, JoinConditionInterface $joinCondition): static { if (!$this->source) { throw new \RuntimeException('Cannot perform a join without a previous call to from'); @@ -478,10 +414,8 @@ public function joinWithType(SourceInterface $rightSource, $joinType, JoinCondit /** * Gets the query built. - * - * @return QueryObjectModelInterface */ - public function getQuery() + public function getQuery(): ?QueryObjectModelInterface { if (null !== $this->query && self::STATE_CLEAN === $this->state) { return $this->query; @@ -503,10 +437,8 @@ public function getQuery() /** * Executes the query setting firstResult and maxResults. - * - * @return QueryResultInterface */ - public function execute() + public function execute(): QueryResultInterface { if (null === $this->query || self::STATE_DIRTY === $this->state) { $this->query = $this->getQuery(); @@ -524,10 +456,8 @@ public function execute() * * @param string $key the parameter name * @param mixed $value the parameter value - * - * @return QueryBuilder this QueryBuilder instance */ - public function setParameter($key, $value) + public function setParameter(string $key, mixed $value): static { $this->params[$key] = $value; @@ -536,12 +466,8 @@ public function setParameter($key, $value) /** * Gets a (previously set) query parameter of the query being constructed. - * - * @param string $key the key (name) of the bound parameter - * - * @return mixed the value of the bound parameter */ - public function getParameter($key) + public function getParameter(string $key): mixed { return isset($this->params[$key]) ? $this->params[$key] : null; } @@ -549,11 +475,9 @@ public function getParameter($key) /** * Sets a collection of query parameters for the query being constructed. * - * @param array $params the query parameters to set - * - * @return QueryBuilder this QueryBuilder instance + * @param array $params the query parameters to set */ - public function setParameters(array $params) + public function setParameters(array $params): static { $this->params = $params; @@ -563,9 +487,9 @@ public function setParameters(array $params) /** * Gets all defined query parameters for the query being constructed. * - * @return array the currently defined query parameters + * @return array */ - public function getParameters() + public function getParameters(): array { return $this->params; } diff --git a/src/PHPCR/Util/QOM/Sql1Generator.php b/src/PHPCR/Util/QOM/Sql1Generator.php index bea5d88c..94edccff 100644 --- a/src/PHPCR/Util/QOM/Sql1Generator.php +++ b/src/PHPCR/Util/QOM/Sql1Generator.php @@ -14,22 +14,18 @@ class Sql1Generator extends BaseSqlGenerator * Selector ::= nodeTypeName * nodeTypeName ::= Name. * - * @param string $nodeTypeName The node type of the selector. If it does not contain starting and ending brackets ([]) they will be added automatically - * @param string $selectorName (unused) - * - * @return string + * @param string $nodeTypeName The node type of the selector. If it does not contain starting and ending brackets ([]) they will be added automatically + * @param string|null $selectorName (unused) */ - public function evalSelector($nodeTypeName, $selectorName = null) + public function evalSelector(string $nodeTypeName, string $selectorName = null): string { return $nodeTypeName; } /** * Helper method to emulate descendant with LIKE query on path property. - * - * @return string */ - protected function getPathForDescendantQuery($path) + protected function getPathForDescendantQuery(string $path): string { if ('/' === $path) { $sql1 = '/%'; @@ -44,13 +40,8 @@ protected function getPathForDescendantQuery($path) /** * SameNode ::= 'jcr:path like Path/% and not jcr:path like Path/%/%'. - * - * @param string $path - * @param string $selectorName - * - * @return string */ - public function evalChildNode($path, $selectorName = null) + public function evalChildNode(string $path, string $selectorName = null): string { $path = $this->getPathForDescendantQuery($path); $sql1 = "jcr:path LIKE '".$path."'"; @@ -62,12 +53,9 @@ public function evalChildNode($path, $selectorName = null) /** * Emulate descendant query with LIKE query. * - * @param string $path * @param string|null $selectorName Unused - * - * @return string */ - public function evalDescendantNode($path, $selectorName = null) + public function evalDescendantNode(string $path, string $selectorName = null): string { $path = $this->getPathForDescendantQuery($path); @@ -80,11 +68,8 @@ public function evalDescendantNode($path, $selectorName = null) * * @param string $selectorName declared to simplifiy interface - as there * are no joins in SQL1 there is no need for a selector - * @param string $propertyName - * - * @return string */ - public function evalPropertyExistence($selectorName, $propertyName) + public function evalPropertyExistence(?string $selectorName, string $propertyName): string { return $propertyName.' IS NOT NULL'; } @@ -95,13 +80,9 @@ public function evalPropertyExistence($selectorName, $propertyName) * FullTextSearchExpression ')' * FullTextSearchExpression ::= BindVariable | ''' FullTextSearchLiteral '''. * - * @param string $selectorName unusued - * @param string $searchExpression - * @param string $propertyName - * - * @return string + * @param string $selectorName unusued */ - public function evalFullTextSearch($selectorName, $searchExpression, $propertyName = null) + public function evalFullTextSearch(string $selectorName, string $searchExpression, string $propertyName = null): string { $propertyName = $propertyName ?: '*'; @@ -114,10 +95,8 @@ public function evalFullTextSearch($selectorName, $searchExpression, $propertyNa /** * columns ::= (Column ',' {Column}) | '*'. - * - * @return string */ - public function evalColumns($columns) + public function evalColumns(iterable $columns): string { if ((!is_array($columns) && !$columns instanceof \Countable) || 0 === count($columns) @@ -140,12 +119,9 @@ public function evalColumns($columns) /** * PropertyValue ::= propertyName. * - * @param string $propertyName - * @param string $selectorName unused in SQL1 - * - * @return string + * @param string|null $selectorName unused in SQL1 */ - public function evalPropertyValue($propertyName, $selectorName = null) + public function evalPropertyValue(string $propertyName, string $selectorName = null): string { return $propertyName; } @@ -156,13 +132,10 @@ public function evalPropertyValue($propertyName, $selectorName = null) * * No support for column name ('AS' columnName) in SQL1 * - * @param string $selectorName unused in SQL1 - * @param string $propertyName - * @param string $colname unused in SQL1 - * - * @return string + * @param string $selectorName unused in SQL1 + * @param string|null $colname unused in SQL1 */ - public function evalColumn($selectorName = null, $propertyName = null, $colname = null) + public function evalColumn(string $selectorName, string $propertyName = null, string $colname = null): string { return $propertyName; } @@ -170,12 +143,8 @@ public function evalColumn($selectorName = null, $propertyName = null, $colname /** * Path ::= simplePath * simplePath ::= A JCR Name that contains only SQL-legal characters. - * - * @param string $path - * - * @return string */ - public function evalPath($path) + public function evalPath(string $path): string { return $path; } @@ -185,7 +154,7 @@ public function evalPath($path) * * No explicit support, do some tricks where possible. */ - public function evalCastLiteral($literal, $type) + public function evalCastLiteral(string $literal, string $type): string { switch ($type) { case 'DATE': diff --git a/src/PHPCR/Util/QOM/Sql2Generator.php b/src/PHPCR/Util/QOM/Sql2Generator.php index a819c6c5..ca656fec 100644 --- a/src/PHPCR/Util/QOM/Sql2Generator.php +++ b/src/PHPCR/Util/QOM/Sql2Generator.php @@ -21,10 +21,8 @@ class Sql2Generator extends BaseSqlGenerator * added automatically. * @param string|null $selectorName The selector name. If it is different than * the nodeTypeName, the alias is declared. - * - * @return string */ - public function evalSelector($nodeTypeName, $selectorName = null) + public function evalSelector(string $nodeTypeName, string $selectorName = null): string { $sql2 = $this->addBracketsIfNeeded($nodeTypeName); @@ -41,15 +39,8 @@ public function evalSelector($nodeTypeName, $selectorName = null) * // If JoinType is omitted INNER is assumed. * left ::= Source * right ::= Source. - * - * @param string $left - * @param string $right - * @param string $joinCondition - * @param string $joinType - * - * @return string */ - public function evalJoin($left, $right, $joinCondition, $joinType = '') + public function evalJoin(string $left, string $right, string $joinCondition, string $joinType = ''): string { return "$left {$joinType}JOIN $right ON $joinCondition"; } @@ -59,23 +50,15 @@ public function evalJoin($left, $right, $joinCondition, $joinType = '') * Inner ::= 'INNER' * LeftOuter ::= 'LEFT OUTER' * RightOuter ::= 'RIGHT OUTER'. - * - * @param string $joinType - * - * @return string */ - public function evalJoinType($joinType) + public function evalJoinType(string $joinType): string { - switch ($joinType) { - case Constants::JCR_JOIN_TYPE_INNER: - return 'INNER '; - case Constants::JCR_JOIN_TYPE_LEFT_OUTER: - return 'LEFT OUTER '; - case Constants::JCR_JOIN_TYPE_RIGHT_OUTER: - return 'RIGHT OUTER '; - } - - return $joinType; + return match ($joinType) { + Constants::JCR_JOIN_TYPE_INNER => 'INNER ', + Constants::JCR_JOIN_TYPE_LEFT_OUTER => 'LEFT OUTER ', + Constants::JCR_JOIN_TYPE_RIGHT_OUTER => 'RIGHT OUTER ', + default => $joinType, + }; } /** @@ -85,15 +68,8 @@ public function evalJoinType($joinType) * selector2Name ::= selectorName * property1Name ::= propertyName * property2Name ::= propertyName. - * - * @param string $sel1Name - * @param string $prop1Name - * @param string $sel2Name - * @param string $prop2Name - * - * @return string */ - public function evalEquiJoinCondition($sel1Name, $prop1Name, $sel2Name, $prop2Name) + public function evalEquiJoinCondition(string $sel1Name, string $prop1Name, string $sel2Name, string $prop2Name): string { return $this->evalPropertyValue($prop1Name, $sel1Name).'='.$this->evalPropertyValue($prop2Name, $sel2Name); } @@ -104,14 +80,8 @@ public function evalEquiJoinCondition($sel1Name, $prop1Name, $sel2Name, $prop2Na * selector2Name * [',' selector2Path] ')' * selector2Path ::= Path. - * - * @param string $sel1Name - * @param string $sel2Name - * @param string $sel2Path - * - * @return string */ - public function evalSameNodeJoinCondition($sel1Name, $sel2Name, $sel2Path = null) + public function evalSameNodeJoinCondition(string $sel1Name, string $sel2Name, string $sel2Path = null): string { $sql2 = 'ISSAMENODE(' .$this->addBracketsIfNeeded($sel1Name).', ' @@ -130,13 +100,8 @@ public function evalSameNodeJoinCondition($sel1Name, $sel2Name, $sel2Path = null * parentSelectorName ')' * childSelectorName ::= selectorName * parentSelectorName ::= selectorName. - * - * @param string $childSelectorName - * @param string $parentSelectorName - * - * @return string */ - public function evalChildNodeJoinCondition($childSelectorName, $parentSelectorName) + public function evalChildNodeJoinCondition(string $childSelectorName, string $parentSelectorName): string { return 'ISCHILDNODE(' .$this->addBracketsIfNeeded($childSelectorName).', ' @@ -149,13 +114,8 @@ public function evalChildNodeJoinCondition($childSelectorName, $parentSelectorNa * ancestorSelectorName ')' * descendantSelectorName ::= selectorName * ancestorSelectorName ::= selectorName. - * - * @param string $descendantSelectorName - * @param string $ancestorselectorName - * - * @return string */ - public function evalDescendantNodeJoinCondition($descendantSelectorName, $ancestorselectorName) + public function evalDescendantNodeJoinCondition(string $descendantSelectorName, string $ancestorselectorName): string { return 'ISDESCENDANTNODE(' .$this->addBracketsIfNeeded($descendantSelectorName).', ' @@ -164,13 +124,8 @@ public function evalDescendantNodeJoinCondition($descendantSelectorName, $ancest /** * SameNode ::= 'ISSAMENODE(' [selectorName ','] Path ')'. - * - * @param string $path - * @param string $selectorName - * - * @return string */ - public function evalSameNode($path, $selectorName = null) + public function evalSameNode(string $path, string $selectorName = null): string { $sql2 = 'ISSAMENODE('; $sql2 .= null === $selectorName ? $path : $this->addBracketsIfNeeded($selectorName).', '.$path; @@ -181,13 +136,8 @@ public function evalSameNode($path, $selectorName = null) /** * SameNode ::= 'ISCHILDNODE(' [selectorName ','] Path ')'. - * - * @param string $path - * @param string $selectorName - * - * @return string */ - public function evalChildNode($path, $selectorName = null) + public function evalChildNode(string $path, string $selectorName = null): string { $sql2 = 'ISCHILDNODE('; $sql2 .= null === $selectorName ? $path : $this->addBracketsIfNeeded($selectorName).', '.$path; @@ -198,13 +148,8 @@ public function evalChildNode($path, $selectorName = null) /** * SameNode ::= 'ISDESCENDANTNODE(' [selectorName ','] Path ')'. - * - * @param string $path - * @param string $selectorName - * - * @return string */ - public function evalDescendantNode($path, $selectorName = null) + public function evalDescendantNode(string $path, string $selectorName = null): string { $sql2 = 'ISDESCENDANTNODE('; $sql2 .= null === $selectorName ? $path : $this->addBracketsIfNeeded($selectorName).', '.$path; @@ -219,10 +164,8 @@ public function evalDescendantNode($path, $selectorName = null) * propertyName 'IS NOT NULL' If only one * selector exists in * this query. - * - * @return string */ - public function evalPropertyExistence($selectorName, $propertyName) + public function evalPropertyExistence(?string $selectorName, string $propertyName): string { return $this->evalPropertyValue($propertyName, $selectorName).' IS NOT NULL'; } @@ -233,14 +176,8 @@ public function evalPropertyExistence($selectorName, $propertyName) * selectorName'.*') ',' * FullTextSearchExpression ')' * FullTextSearchExpression ::= BindVariable | ''' FullTextSearchLiteral '''. - * - * @param string $selectorName - * @param string $searchExpression - * @param string $propertyName - * - * @return string */ - public function evalFullTextSearch($selectorName, $searchExpression, $propertyName = null) + public function evalFullTextSearch(string $selectorName, string $searchExpression, string $propertyName = null): string { $propertyName = $propertyName ?: '*'; @@ -253,64 +190,43 @@ public function evalFullTextSearch($selectorName, $searchExpression, $propertyNa /** * Length ::= 'LENGTH(' PropertyValue ')'. - * - * @param string $propertyValue - * - * @return string */ - public function evalLength($propertyValue) + public function evalLength(string $propertyValue): string { return "LENGTH($propertyValue)"; } /** * NodeName ::= 'NAME(' [selectorName] ')'. - * - * @param string $selectorValue - * - * @return string */ - public function evalNodeName($selectorValue = null) + public function evalNodeName(string $selectorValue = null): string { return "NAME($selectorValue)"; } /** * NodeLocalName ::= 'LOCALNAME(' [selectorName] ')'. - * - * @param string $selectorValue - * - * @return string */ - public function evalNodeLocalName($selectorValue = null) + public function evalNodeLocalName(string $selectorValue = null): string { return "LOCALNAME($selectorValue)"; } /** * FullTextSearchScore ::= 'SCORE(' [selectorName] ')'. - * - * @param string $selectorValue - * - * @return string */ - public function evalFullTextSearchScore($selectorValue = null) + public function evalFullTextSearchScore(string $selectorValue = null): string { return "SCORE($selectorValue)"; } /** * PropertyValue ::= [selectorName'.'] propertyName // If only one selector exists. - * - * @param string $propertyName - * @param string $selectorName - * - * @return string */ - public function evalPropertyValue($propertyName, $selectorName = null) + public function evalPropertyValue(string $propertyName, string $selectorName = null): string { $sql2 = null !== $selectorName ? $this->addBracketsIfNeeded($selectorName).'.' : ''; - if ('*' !== $propertyName && '[' !== substr($propertyName, 0, 1)) { + if ('*' !== $propertyName && !str_starts_with($propertyName, '[')) { $propertyName = "[$propertyName]"; } $sql2 .= $propertyName; @@ -320,10 +236,8 @@ public function evalPropertyValue($propertyName, $selectorName = null) /** * columns ::= (Column ',' {Column}) | '*'. - * - * @return string */ - public function evalColumns($columns) + public function evalColumns(iterable $columns): string { if ((!is_array($columns) && !$columns instanceof \Countable) || 0 === count($columns) @@ -350,14 +264,8 @@ public function evalColumns($columns) * selectorName ::= Name * propertyName ::= Name * columnName ::= Name. - * - * @param string $selectorName - * @param string $propertyName - * @param string $colname - * - * @return string */ - public function evalColumn($selectorName, $propertyName = null, $colname = null) + public function evalColumn(string $selectorName, string $propertyName = null, string $colname = null): string { $sql2 = ''; if (null !== $selectorName && null === $propertyName && null === $colname) { @@ -377,20 +285,16 @@ public function evalColumn($selectorName, $propertyName = null, $colname = null) * Path ::= '[' quotedPath ']' | '[' simplePath ']' | simplePath * quotedPath ::= A JCR Path that contains non-SQL-legal characters * simplePath ::= A JCR Name that contains only SQL-legal characters. - * - * @param string $path - * - * @return string */ - public function evalPath($path) + public function evalPath(string $path): string { if (!$path) { return $path; } $sql2 = $path; // only ensure proper quoting if the user did not quote himself, we trust him to get it right if he did. - if (0 !== strpos($path, '[') && ']' !== substr($path, -1)) { - if (false !== strpos($sql2, ' ') || false !== strpos($sql2, '.')) { + if (!str_starts_with($path, '[') && !str_ends_with($path, ']')) { + if (str_contains($sql2, ' ') || str_contains($sql2, '.')) { $sql2 = '"'.$sql2.'"'; } $sql2 = '['.$sql2.']'; @@ -404,7 +308,7 @@ public function evalPath($path) * * CastLiteral ::= 'CAST(' UncastLiteral ' AS ' PropertyType ')' */ - public function evalCastLiteral($literal, $type) + public function evalCastLiteral(string $literal, string $type): string { return "CAST('$literal' AS $type)"; } @@ -412,15 +316,13 @@ public function evalCastLiteral($literal, $type) /** * Add square brackets around a selector if needed. * - * @param string $selector - * * @return string $selector guaranteed to have [] around it if needed */ - private function addBracketsIfNeeded($selector) + private function addBracketsIfNeeded(string $selector): string { - if ('[' !== substr($selector, 0, 1) - && ']' !== substr($selector, -1) - && false !== strpos($selector, ':') + if (!str_starts_with($selector, '[') + && !str_ends_with($selector, ']') + && str_contains($selector, ':') ) { return "[$selector]"; } diff --git a/src/PHPCR/Util/QOM/Sql2Scanner.php b/src/PHPCR/Util/QOM/Sql2Scanner.php index 2bc91f7d..9fd6472d 100644 --- a/src/PHPCR/Util/QOM/Sql2Scanner.php +++ b/src/PHPCR/Util/QOM/Sql2Scanner.php @@ -14,31 +14,25 @@ class Sql2Scanner { /** * The SQL2 query currently being parsed. - * - * @var string */ - protected $sql2; + protected string $sql2; /** * Token scanning result of the SQL2 string. * - * @var array + * @var string[] */ - protected $tokens; + protected array $tokens; /** * Parsing position in the SQL string. - * - * @var int */ - protected $curpos = 0; + protected int $curpos = 0; /** * Construct a scanner with the given SQL2 statement. - * - * @param string $sql2 */ - public function __construct($sql2) + public function __construct(string $sql2) { $this->sql2 = $sql2; $this->tokens = $this->scan($this->sql2); @@ -49,10 +43,8 @@ public function __construct($sql2) * Return an empty string when there are no more tokens. * * @param int $offset number of tokens to look ahead - defaults to 0, the current token - * - * @return string */ - public function lookupNextToken($offset = 0) + public function lookupNextToken(int $offset = 0): string { if ($this->curpos + $offset < count($this->tokens)) { return trim($this->tokens[$this->curpos + $offset]); @@ -64,10 +56,8 @@ public function lookupNextToken($offset = 0) /** * Get the next token and remove it from the queue. * Return an empty string when there are no more tokens. - * - * @return string */ - public function fetchNextToken() + public function fetchNextToken(): string { $token = $this->lookupNextToken(); if ('' !== $token) { @@ -82,12 +72,11 @@ public function fetchNextToken() * not the case. The equality test is done case sensitively/insensitively * depending on the second parameter. * - * @param string $token The expected token - * @param bool $case_insensitive + * @param string $token The expected token * * @throws InvalidQueryException */ - public function expectToken($token, $case_insensitive = true) + public function expectToken(string $token, bool $case_insensitive = true): void { $nextToken = $this->fetchNextToken(); if (!$this->tokenIs($nextToken, $token, $case_insensitive)) { @@ -99,14 +88,11 @@ public function expectToken($token, $case_insensitive = true) * Expect the next tokens to be the one given in the array of tokens and * throws an exception if it's not the case. * - * @param array $tokens - * @param bool $case_insensitive - * * @throws InvalidQueryException * * @see expectToken */ - public function expectTokens($tokens, $case_insensitive = true) + public function expectTokens(array $tokens, bool $case_insensitive = true): void { foreach ($tokens as $token) { $this->expectToken($token, $case_insensitive); @@ -115,14 +101,8 @@ public function expectTokens($tokens, $case_insensitive = true) /** * Test the equality of two tokens. - * - * @param string $token - * @param string $value - * @param bool $case_insensitive - * - * @return bool */ - public function tokenIs($token, $value, $case_insensitive = true) + public function tokenIs(string $token, string $value, bool $case_insensitive = true): bool { if ($case_insensitive) { $test = strtoupper($token) === strtoupper($value); @@ -150,7 +130,8 @@ protected function scan($sql2) $isEscaped = false; $escapedQuotesCount = 0; $splitString = \str_split($sql2); - for ($index = 0; $index < count($splitString); ++$index) { + $splitStringCount = count($splitString); + for ($index = 0; $index < $splitStringCount; ++$index) { $character = $splitString[$index]; if (!$stringStartCharacter && in_array($character, [' ', "\t", "\n", "\r"], true)) { if ('' !== $currentToken) { @@ -194,7 +175,7 @@ protected function scan($sql2) continue; } // If the escaped quotes are not paired up. eg. "I'''m cool" would be a parsing error - if (1 == $escapedQuotesCount % 2 && "'" !== $stringStartCharacter) { + if (1 === $escapedQuotesCount % 2 && "'" !== $stringStartCharacter) { throw new InvalidQueryException("Syntax error: Number of single quotes to be even: $currentToken"); } if ($character === $stringStartCharacter) { @@ -208,7 +189,7 @@ protected function scan($sql2) // When tokenizing `AS"abc"` add the current token (AS) as token already if (strlen($currentToken) > 1) { - $tokens[] = substr($currentToken, 0, strlen($currentToken) - 1); + $tokens[] = substr($currentToken, 0, -1); $currentToken = $character; } } diff --git a/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php b/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php index 7e58eb0e..d849cda8 100644 --- a/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php +++ b/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php @@ -36,44 +36,35 @@ class Sql2ToQomQueryConverter { /** * The factory to create QOM objects. - * - * @var QueryObjectModelFactoryInterface */ - protected $factory; + protected QueryObjectModelFactoryInterface $factory; /** * Scanner to parse SQL2. * * @var Sql2Scanner; */ - protected $scanner; + protected Sql2Scanner $scanner; /** * The SQL2 query (the converter is not reentrant). - * - * @var string */ - protected $sql2; + protected string $sql2; /** * The selector is not required for SQL2 but for QOM. * * We keep all selectors we encounter. If there is exactly one, it is used * whenever we encounter non-qualified names. - * - * @var string|array */ - protected $implicitSelectorName; + protected string|array|null $implicitSelectorName; - /** - * @var ValueConverter - */ - private $valueConverter; + private ValueConverter $valueConverter; /** * Instantiate a converter. * - * @param ValueConverter $valueConverter to override default converter + * @param ValueConverter|null $valueConverter to override default converter */ public function __construct(QueryObjectModelFactoryInterface $factory, ValueConverter $valueConverter = null) { @@ -87,11 +78,9 @@ public function __construct(QueryObjectModelFactoryInterface $factory, ValueConv * * @param string $sql2 * - * @return QueryObjectModelInterface - * * @throws InvalidQueryException */ - public function parse($sql2) + public function parse($sql2): QueryObjectModelInterface { $this->implicitSelectorName = null; $this->sql2 = $sql2; @@ -140,7 +129,7 @@ public function parse($sql2) * * @return SourceInterface */ - protected function parseSource() + protected function parseSource(): JoinInterface|SourceInterface|SelectorInterface { $selector = $this->parseSelector(); @@ -158,10 +147,8 @@ protected function parseSource() /** * 6.7.3. Selector * Parse an SQL2 selector and return a QOM\SelectorInterface. - * - * @return SelectorInterface */ - protected function parseSelector() + protected function parseSelector(): SelectorInterface { $nodetype = $this->fetchTokenWithoutBrackets(); @@ -179,10 +166,8 @@ protected function parseSelector() /** * 6.7.4. Name. - * - * @return string */ - protected function parseName() + protected function parseName(): string { return $this->scanner->fetchNextToken(); } @@ -193,10 +178,8 @@ protected function parseName() * Parse an SQL2 join source and return a QOM\Join. * * @param SourceInterface $leftSelector the left selector as it has been read by parseSource - * - * @return JoinInterface */ - protected function parseJoin(SourceInterface $leftSelector) + protected function parseJoin(SourceInterface $leftSelector): JoinInterface { $joinType = $this->parseJoinType(); $right = $this->parseSelector(); @@ -208,11 +191,9 @@ protected function parseJoin(SourceInterface $leftSelector) /** * 6.7.6. Join type. * - * @return string - * * @throws InvalidQueryException */ - protected function parseJoinType() + protected function parseJoinType(): string { $joinType = Constants::JCR_JOIN_TYPE_INNER; $token = $this->scanner->fetchNextToken(); @@ -245,7 +226,7 @@ protected function parseJoinType() * * @return JoinConditionInterface */ - protected function parseJoinCondition() + protected function parseJoinCondition(): SameNodeJoinConditionInterface|EquiJoinConditionInterface|DescendantNodeJoinConditionInterface|ChildNodeJoinConditionInterface|JoinConditionInterface { $this->scanner->expectToken('ON'); @@ -268,10 +249,8 @@ protected function parseJoinCondition() /** * 6.7.8. EquiJoinCondition * Parse an SQL2 equijoin condition and return a EquiJoinConditionInterface. - * - * @return EquiJoinConditionInterface */ - protected function parseEquiJoin() + protected function parseEquiJoin(): EquiJoinConditionInterface { list($selectorName1, $prop1) = $this->parseIdentifier(); $this->scanner->expectToken('='); @@ -283,10 +262,8 @@ protected function parseEquiJoin() /** * 6.7.9 SameNodeJoinCondition * Parse an SQL2 same node join condition and return a SameNodeJoinConditionInterface. - * - * @return SameNodeJoinConditionInterface */ - protected function parseSameNodeJoinCondition() + protected function parseSameNodeJoinCondition(): SameNodeJoinConditionInterface { $this->scanner->expectTokens(['ISSAMENODE', '(']); $selectorName1 = $this->fetchTokenWithoutBrackets(); @@ -309,10 +286,8 @@ protected function parseSameNodeJoinCondition() /** * 6.7.10 ChildNodeJoinCondition * Parse an SQL2 child node join condition and return a ChildNodeJoinConditionInterface. - * - * @return ChildNodeJoinConditionInterface */ - protected function parseChildNodeJoinCondition() + protected function parseChildNodeJoinCondition(): ChildNodeJoinConditionInterface { $this->scanner->expectTokens(['ISCHILDNODE', '(']); $child = $this->fetchTokenWithoutBrackets(); @@ -326,10 +301,8 @@ protected function parseChildNodeJoinCondition() /** * 6.7.11 DescendantNodeJoinCondition * Parse an SQL2 descendant node join condition and return a DescendantNodeJoinConditionInterface. - * - * @return DescendantNodeJoinConditionInterface */ - protected function parseDescendantNodeJoinCondition() + protected function parseDescendantNodeJoinCondition(): DescendantNodeJoinConditionInterface { $this->scanner->expectTokens(['ISDESCENDANTNODE', '(']); $descendant = $this->fetchTokenWithoutBrackets(); @@ -344,14 +317,12 @@ protected function parseDescendantNodeJoinCondition() * 6.7.13 And * 6.7.14 Or. * - * @param ConstraintInterface $lhs Left hand side - * @param int $minprec Precedence - * - * @return ConstraintInterface + * @param ConstraintInterface|null $lhs Left hand side + * @param int $minprec Precedence * * @throws \Exception */ - protected function parseConstraint($lhs = null, $minprec = 0) + protected function parseConstraint(ConstraintInterface $lhs = null, int $minprec = 0): FullTextSearchInterface|ComparisonInterface|NotInterface|ConstraintInterface|null { if (null === $lhs) { $lhs = $this->parsePrimaryConstraint(); @@ -453,10 +424,8 @@ protected function parsePrimaryConstraint() /** * 6.7.15 Not. - * - * @return NotInterface */ - protected function parseNot() + protected function parseNot(): NotInterface { $this->scanner->expectToken('NOT'); @@ -466,11 +435,9 @@ protected function parseNot() /** * 6.7.16 Comparison. * - * @return ComparisonInterface - * * @throws InvalidQueryException */ - protected function parseComparison() + protected function parseComparison(): ComparisonInterface { $op1 = $this->parseDynamicOperand(); @@ -489,7 +456,7 @@ protected function parseComparison() * * @return string a constant from QueryObjectModelConstantsInterface */ - protected function parseOperator() + protected function parseOperator(): string { $token = $this->scanner->fetchNextToken(); switch (strtoupper($token)) { @@ -514,10 +481,8 @@ protected function parseOperator() /** * 6.7.18 PropertyExistence. - * - * @return ConstraintInterface */ - protected function parsePropertyExistence() + protected function parsePropertyExistence(): ConstraintInterface { list($selectorName, $prop) = $this->parseIdentifier(); @@ -536,10 +501,8 @@ protected function parsePropertyExistence() /** * 6.7.19 FullTextSearch. - * - * @return FullTextSearchInterface */ - protected function parseFullTextSearch() + protected function parseFullTextSearch(): FullTextSearchInterface { $this->scanner->expectTokens(['CONTAINS', '(']); @@ -573,7 +536,7 @@ protected function parseSameNode() /** * 6.7.21 ChildNode. */ - protected function parseChildNode() + protected function parseChildNode(): \PHPCR\Query\QOM\ChildNodeInterface { $this->scanner->expectTokens(['ISCHILDNODE', '(']); if ($this->scanner->tokenIs($this->scanner->lookupNextToken(1), ',')) { @@ -592,7 +555,7 @@ protected function parseChildNode() /** * 6.7.22 DescendantNode. */ - protected function parseDescendantNode() + protected function parseDescendantNode(): \PHPCR\Query\QOM\DescendantNodeInterface { $this->scanner->expectTokens(['ISDESCENDANTNODE', '(']); if ($this->scanner->tokenIs($this->scanner->lookupNextToken(1), ',')) { @@ -629,10 +592,8 @@ protected function parsePath() * Parse an SQL2 static operand * 6.7.35 BindVariable * 6.7.36 Prefix. - * - * @return StaticOperandInterface */ - protected function parseStaticOperand() + protected function parseStaticOperand(): StaticOperandInterface { $token = $this->scanner->lookupNextToken(); if ('$' === substr($token, 0, 1)) { @@ -654,7 +615,7 @@ protected function parseStaticOperand() * * @return DynamicOperandInterface */ - protected function parseDynamicOperand() + protected function parseDynamicOperand(): DynamicOperandInterface|PropertyValueInterface { $token = $this->scanner->lookupNextToken(); @@ -733,17 +694,15 @@ protected function parseDynamicOperand() /** * 6.7.27 PropertyValue * Parse an SQL2 property value. - * - * @return PropertyValueInterface */ - protected function parsePropertyValue() + protected function parsePropertyValue(): PropertyValueInterface { list($selectorName, $prop) = $this->parseIdentifier(); return $this->factory->propertyValue($selectorName, $prop); } - protected function parseCastLiteral($token) + protected function parseCastLiteral($token): mixed { if (!$this->scanner->tokenIs($token, 'CAST')) { throw new \LogicException('parseCastLiteral when not a CAST'); @@ -786,7 +745,7 @@ protected function parseCastLiteral($token) * 6.7.34 Literal * Parse an SQL2 literal value. */ - protected function parseLiteralValue() + protected function parseLiteralValue(): mixed { $token = $this->scanner->fetchNextToken(); if ($this->scanner->tokenIs($token, 'CAST')) { @@ -799,8 +758,7 @@ protected function parseLiteralValue() $quotesUsed = $token[0]; $token = substr($token, 1, -1); // Unescape quotes - $token = str_replace('\\'.$quotesUsed, $quotesUsed, $token); - $token = str_replace("''", "'", $token); + $token = str_replace(['\\'.$quotesUsed, "''"], [$quotesUsed, "'"], $token); if (preg_match('/^\d{4}-\d{2}-\d{2}( \d{2}:\d{2}:\d+)?$/', $token)) { if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $token)) { $token .= ' 00:00:00'; @@ -808,7 +766,7 @@ protected function parseLiteralValue() $token = \DateTime::createFromFormat('Y-m-d H:i:s', $token); } } elseif (is_numeric($token)) { - $token = false === strpos($token, '.') ? (int) $token : (float) $token; + $token = !str_contains($token, '.') ? (int) $token : (float) $token; } elseif ('true' === $token) { $token = true; } elseif ('false' === $token) { @@ -821,7 +779,7 @@ protected function parseLiteralValue() /** * 6.7.37 Ordering. */ - protected function parseOrderings() + protected function parseOrderings(): array { $orderings = []; $continue = true; @@ -840,10 +798,8 @@ protected function parseOrderings() /** * 6.7.38 Order. - * - * @return OrderingInterface */ - protected function parseOrdering() + protected function parseOrdering(): OrderingInterface { $operand = $this->parseDynamicOperand(); $token = $this->scanner->lookupNextToken(); @@ -873,7 +829,7 @@ protected function parseOrdering() * * @return array of array */ - protected function scanColumns() + protected function scanColumns(): array { // Wildcard if ('*' === $this->scanner->lookupNextToken()) { @@ -902,11 +858,9 @@ protected function scanColumns() /** * Build the columns from the scanned column data. * - * @param array $data - * * @return ColumnInterface[] */ - protected function buildColumns($data) + protected function buildColumns(array $data): array { $columns = []; foreach ($data as $col) { @@ -919,14 +873,12 @@ protected function buildColumns($data) /** * Get the next token and make sure to remove the brackets if the token is * in the [ns:name] notation. - * - * @return string */ - private function fetchTokenWithoutBrackets() + private function fetchTokenWithoutBrackets(): string { $token = $this->scanner->fetchNextToken(); - if ('[' === substr($token, 0, 1) && ']' === substr($token, -1)) { + if (str_starts_with($token, '[') && str_ends_with($token, ']')) { // Remove brackets around the selector name $token = substr($token, 1, -1); } @@ -942,7 +894,7 @@ private function fetchTokenWithoutBrackets() * @return array with selectorName and propertyName. If no selectorName is * specified, defaults to $this->defaultSelectorName */ - private function parseIdentifier($checkSelector = true) + private function parseIdentifier(bool $checkSelector = true): array { $token = $this->fetchTokenWithoutBrackets(); @@ -966,11 +918,9 @@ private function parseIdentifier($checkSelector = true) /** * Add a selector name to the known selector names. * - * @param string $selectorName - * * @throws InvalidQueryException */ - protected function updateImplicitSelectorName($selectorName) + protected function updateImplicitSelectorName(string $selectorName): void { if (null === $this->implicitSelectorName) { $this->implicitSelectorName = $selectorName; @@ -989,18 +939,16 @@ protected function updateImplicitSelectorName($selectorName) * Ensure that the parsedName is a valid selector, or return the implicit * selector if its non-ambigous. * - * @param string|null $parsedName - * * @return string the selector to use * * @throws InvalidQueryException if there was no explicit selector and * there is more than one selector available */ - protected function ensureSelectorName($parsedName) + protected function ensureSelectorName(?string $parsedName): array|string|null { if (null !== $parsedName) { - if (is_array($this->implicitSelectorName) && !isset($this->implicitSelectorName[$parsedName]) - || !is_array($this->implicitSelectorName) && $this->implicitSelectorName !== $parsedName + if ((is_array($this->implicitSelectorName) && !isset($this->implicitSelectorName[$parsedName])) + || (!is_array($this->implicitSelectorName) && $this->implicitSelectorName !== $parsedName) ) { throw new InvalidQueryException("Unknown selector $parsedName in '{$this->sql2}'"); } @@ -1016,10 +964,8 @@ protected function ensureSelectorName($parsedName) /** * Scan a single SQL2 column definition and return an array of information. - * - * @return array */ - protected function scanColumn() + protected function scanColumn(): array { list($selectorName, $propertyName) = $this->parseIdentifier(false); @@ -1038,10 +984,8 @@ protected function scanColumn() * Build a single SQL2 column definition. * * @param array $data with selector name, property name and column name - * - * @return ColumnInterface */ - protected function buildColumn(array $data) + protected function buildColumn(array $data): ColumnInterface { list($selectorName, $propertyName, $columnName) = $data; $selectorName = $this->ensureSelectorName($selectorName); diff --git a/src/PHPCR/Util/TraversingItemVisitor.php b/src/PHPCR/Util/TraversingItemVisitor.php index 2890c555..911e2ba7 100644 --- a/src/PHPCR/Util/TraversingItemVisitor.php +++ b/src/PHPCR/Util/TraversingItemVisitor.php @@ -33,40 +33,30 @@ abstract class TraversingItemVisitor implements ItemVisitorInterface /** * Indicates if traversal should be done in a breadth-first manner rather * than depth-first (which is the default). - * - * @var bool */ - protected $breadthFirst = false; + protected bool $breadthFirst = false; /** * The 0-based depth up to which the hierarchy should be traversed (if it's * -1, the hierarchy will be traversed until there are no more children of * the current item). - * - * @var int */ - protected $maxDepth = -1; + protected int $maxDepth = -1; /** * Queue used to implement breadth-first traversal. - * - * @var \SplQueue */ - protected $currentQueue; + protected \SplQueue $currentQueue; /** * Queue used to implement breadth-first traversal. - * - * @var \SplQueue */ - protected $nextQueue; + protected \SplQueue $nextQueue; /** * Used to track hierarchy depth of item currently being processed. - * - * @var int */ - protected $currentDepth; + protected int $currentDepth; /** * Constructs a new instance of this class. @@ -81,7 +71,7 @@ abstract class TraversingItemVisitor implements ItemVisitorInterface * * @api */ - public function __construct($breadthFirst = false, $maxDepth = -1) + public function __construct(bool $breadthFirst = false, int $maxDepth = -1) { $this->breadthFirst = $breadthFirst; $this->maxDepth = $maxDepth; @@ -95,10 +85,8 @@ public function __construct($breadthFirst = false, $maxDepth = -1) /** * Update the current depth level for indention. - * - * @param int $level */ - public function setLevel($level) + public function setLevel(int $level): void { $this->currentDepth = $level; } @@ -116,7 +104,7 @@ public function setLevel($level) * * @api */ - abstract protected function entering(ItemInterface $item, $depth); + abstract protected function entering(ItemInterface $item, int $depth): void; /** * Implement this method to add behavior performed after a Property is @@ -131,7 +119,7 @@ abstract protected function entering(ItemInterface $item, $depth); * * @api */ - abstract protected function leaving(ItemInterface $item, $depth); + abstract protected function leaving(ItemInterface $item, int $depth): void; /** * Called when the Visitor is passed to an Item. @@ -149,7 +137,7 @@ abstract protected function leaving(ItemInterface $item, $depth); * * @api */ - public function visit(ItemInterface $item) + public function visit(ItemInterface $item): void { if (0 === $this->currentDepth) { $this->currentDepth = $item->getDepth(); diff --git a/src/PHPCR/Util/TreeWalker.php b/src/PHPCR/Util/TreeWalker.php index d1539e82..52fb7533 100644 --- a/src/PHPCR/Util/TreeWalker.php +++ b/src/PHPCR/Util/TreeWalker.php @@ -17,37 +17,33 @@ class TreeWalker { /** * Visitor for nodes. - * - * @var ItemVisitorInterface */ - protected $nodeVisitor; + protected ItemVisitorInterface $nodeVisitor; /** * Visitor for properties. - * - * @var ItemVisitorInterface */ - protected $propertyVisitor; + protected ?ItemVisitorInterface $propertyVisitor; /** * Filters to apply to decide whether a node needs to be visited. * * @var TreeWalkerFilterInterface[] */ - protected $nodeFilters = []; + protected array $nodeFilters = []; /** * Filters to apply to decide whether a property needs to be visited. * * @var TreeWalkerFilterInterface[] */ - protected $propertyFilters = []; + protected array $propertyFilters = []; /** * Instantiate a tree walker. * - * @param ItemVisitorInterface $nodeVisitor The visitor for the nodes - * @param ItemVisitorInterface $propertyVisitor The visitor for the nodes properties + * @param ItemVisitorInterface $nodeVisitor The visitor for the nodes + * @param ItemVisitorInterface|null $propertyVisitor The visitor for the nodes properties */ public function __construct(ItemVisitorInterface $nodeVisitor, ItemVisitorInterface $propertyVisitor = null) { @@ -58,9 +54,9 @@ public function __construct(ItemVisitorInterface $nodeVisitor, ItemVisitorInterf /** * Add a filter to select the nodes that will be traversed. */ - public function addNodeFilter(TreeWalkerFilterInterface $filter) + public function addNodeFilter(TreeWalkerFilterInterface $filter): void { - if (!in_array($filter, $this->nodeFilters)) { + if (!in_array($filter, $this->nodeFilters, true)) { $this->nodeFilters[] = $filter; } } @@ -68,7 +64,7 @@ public function addNodeFilter(TreeWalkerFilterInterface $filter) /** * Add a filter to select the properties that will be traversed. */ - public function addPropertyFilter(TreeWalkerFilterInterface $filter) + public function addPropertyFilter(TreeWalkerFilterInterface $filter): void { if (!in_array($filter, $this->propertyFilters)) { $this->propertyFilters[] = $filter; @@ -77,10 +73,8 @@ public function addPropertyFilter(TreeWalkerFilterInterface $filter) /** * Return whether a node must be traversed or not. - * - * @return bool */ - protected function mustVisitNode(NodeInterface $node) + protected function mustVisitNode(NodeInterface $node): bool { foreach ($this->nodeFilters as $filter) { if (!$filter->mustVisit($node)) { @@ -93,10 +87,8 @@ protected function mustVisitNode(NodeInterface $node) /** * Return whether a node property must be traversed or not. - * - * @return bool */ - protected function mustVisitProperty(PropertyInterface $property) + protected function mustVisitProperty(PropertyInterface $property): bool { foreach ($this->propertyFilters as $filter) { if (!$filter->mustVisit($property)) { @@ -113,7 +105,7 @@ protected function mustVisitProperty(PropertyInterface $property) * @param int $recurse Max recursion level * @param int $level Recursion level */ - public function traverse(NodeInterface $node, $recurse = -1, $level = 0): void + public function traverse(NodeInterface $node, int $recurse = -1, int $level = 0): void { if ($this->mustVisitNode($node)) { // Visit node diff --git a/src/PHPCR/Util/TreeWalkerFilterInterface.php b/src/PHPCR/Util/TreeWalkerFilterInterface.php index 1e326056..9265bccf 100644 --- a/src/PHPCR/Util/TreeWalkerFilterInterface.php +++ b/src/PHPCR/Util/TreeWalkerFilterInterface.php @@ -14,5 +14,5 @@ interface TreeWalkerFilterInterface /** * Whether to visit the passed item. */ - public function mustVisit(ItemInterface $item); + public function mustVisit(ItemInterface $item): mixed; } diff --git a/src/PHPCR/Util/UUIDHelper.php b/src/PHPCR/Util/UUIDHelper.php index 476c1369..0e59fa70 100644 --- a/src/PHPCR/Util/UUIDHelper.php +++ b/src/PHPCR/Util/UUIDHelper.php @@ -19,7 +19,7 @@ class UUIDHelper * * @return bool true if the test was passed, else false */ - public static function isUUID($id) + public static function isUUID(string $id): bool { // UUID is HEX_CHAR{8}-HEX_CHAR{4}-HEX_CHAR{4}-HEX_CHAR{4}-HEX_CHAR{12} return 1 === preg_match('/^[[:xdigit:]]{8}-[[:xdigit:]]{4}-[[:xdigit:]]{4}-[[:xdigit:]]{4}-[[:xdigit:]]{12}$/', $id); @@ -35,36 +35,34 @@ public static function isUUID($id) * * @return string a random UUID */ - public static function generateUUID() + public static function generateUUID(): string { if (class_exists(Uuid::class)) { - $uuid4 = Uuid::uuid4(); - - return $uuid4->toString(); + return Uuid::uuid4()->toString(); } return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x', // 32 bits for "time_low" - mt_rand(0, 0xFFFF), - mt_rand(0, 0xFFFF), + random_int(0, 0xFFFF), + random_int(0, 0xFFFF), // 16 bits for "time_mid" - mt_rand(0, 0xFFFF), + random_int(0, 0xFFFF), // 16 bits for "time_hi_and_version", // four most significant bits holds version number 4 - mt_rand(0, 0x0FFF) | 0x4000, + random_int(0, 0x0FFF) | 0x4000, // 16 bits, 8 bits for "clk_seq_hi_res", // 8 bits for "clk_seq_low", // two most significant bits holds zero and one for variant DCE1.1 - mt_rand(0, 0x3FFF) | 0x8000, + random_int(0, 0x3FFF) | 0x8000, // 48 bits for "node" - mt_rand(0, 0xFFFF), - mt_rand(0, 0xFFFF), - mt_rand(0, 0xFFFF) + random_int(0, 0xFFFF), + random_int(0, 0xFFFF), + random_int(0, 0xFFFF) ); } } diff --git a/src/PHPCR/Util/ValueConverter.php b/src/PHPCR/Util/ValueConverter.php index ab116639..c3ff5950 100644 --- a/src/PHPCR/Util/ValueConverter.php +++ b/src/PHPCR/Util/ValueConverter.php @@ -48,7 +48,7 @@ class ValueConverter * * @throws ValueFormatException if the type can not be determined */ - public function determineType($value, $weak = false) + public function determineType(mixed $value, bool $weak = false): int { if (is_array($value)) { if (0 === count($value)) { @@ -108,13 +108,13 @@ public function determineType($value, $weak = false) * * @return mixed the value casted into the proper format (throws an exception if conversion is not possible) * - * @throws ValueFormatException is thrown if the specified value cannot be converted to the specified type * @throws RepositoryException if the specified Node is not referenceable, the current Session is no longer active, or another error occurs * @throws \InvalidArgumentException if the specified DateTime value cannot be expressed in the ISO 8601-based format defined in the JCR 2.0 specification and the implementation does not support dates incompatible with that format. + * @throws ValueFormatException is thrown if the specified value cannot be converted to the specified type * * @see http://www.day.com/specs/jcr/2.0/3_Repository_Model.html#3.6.4%20Property%20Type%20Conversion */ - public function convertType($value, $type, $srcType = PropertyType::UNDEFINED) + public function convertType(mixed $value, int $type, int $srcType = PropertyType::UNDEFINED): mixed { if (is_array($value)) { $ret = []; @@ -142,7 +142,6 @@ public function convertType($value, $type, $srcType = PropertyType::UNDEFINED) } elseif ((PropertyType::REFERENCE === $srcType || PropertyType::WEAKREFERENCE === $srcType) && $value instanceof NodeInterface ) { - /** @var $value NodeInterface */ if (!$value->isNodeType('mix:referenceable')) { throw new ValueFormatException('Node '.$value->getPath().' is not referenceable'); } @@ -341,9 +340,9 @@ public function convertType($value, $type, $srcType = PropertyType::UNDEFINED) case PropertyType::NAME: return '../'.rawurlencode($value); case PropertyType::PATH: - if (strlen($value) > 0 - && '/' != $value[0] - && '.' != $value[0] + if ('' !== $value + && '/' !== $value[0] + && '.' !== $value[0] ) { $value = './'.$value; } diff --git a/tests/PHPCR/Tests/Util/PathHelperTest.php b/tests/PHPCR/Tests/Util/PathHelperTest.php index cc7ec87c..0e0dd06c 100644 --- a/tests/PHPCR/Tests/Util/PathHelperTest.php +++ b/tests/PHPCR/Tests/Util/PathHelperTest.php @@ -171,7 +171,7 @@ public static function dataproviderNormalizePathInvalid() ['bar'], ['/foo/bar/'], [''], - [new \stdClass()], + ['//'], ]; } @@ -180,12 +180,12 @@ public static function dataproviderNormalizePathInvalid() /** * @dataProvider dataproviderAbsolutizePath */ - public function testAbsolutizePath($inputPath, $context, $outputPath) + public function testAbsolutizePath(string $inputPath, string $context, string $outputPath): void { $this->assertSame($outputPath, PathHelper::absolutizePath($inputPath, $context)); } - public static function dataproviderAbsolutizePath() + public static function dataproviderAbsolutizePath(): array { return [ ['/../foo', '/', '/foo'], @@ -216,9 +216,8 @@ public static function dataproviderAbsolutizePathInvalid() { return [ ['', '/context', false], - [null, '/context', false], - ['foo', null, false], - [new \stdClass(), '/context', false], + ['//', '/context', false], + ['foo', '//', false], ['foo[2]', '/bar', true], ]; } diff --git a/tests/PHPCR/Tests/Util/QOM/QueryBuilderTest.php b/tests/PHPCR/Tests/Util/QOM/QueryBuilderTest.php index 7b50c429..c5466d01 100644 --- a/tests/PHPCR/Tests/Util/QOM/QueryBuilderTest.php +++ b/tests/PHPCR/Tests/Util/QOM/QueryBuilderTest.php @@ -9,6 +9,7 @@ use PHPCR\Query\QOM\QueryObjectModelInterface; use PHPCR\Query\QOM\SameNodeJoinConditionInterface; use PHPCR\Query\QOM\SourceInterface; +use PHPCR\Query\QueryResultInterface; use PHPCR\Util\QOM\QueryBuilder; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; @@ -322,7 +323,7 @@ public function testGetQuery() $this->qf->expects($this->once()) ->method('createQuery') - ->willReturn('true'); + ->willReturn($this->createMock(QueryObjectModelInterface::class)); $qb->getQuery(); } @@ -385,7 +386,10 @@ public function testSetParameters() $value2 = 'value2'; $qb = new QueryBuilder($this->qf); - $qb->setParameters([$key1, $value1], [$key2, $value2]); + $qb->setParameters([ + $key1 => $value1, + $key2 => $value2, + ]); $this->assertCount(2, $qb->getParameters()); } @@ -395,8 +399,11 @@ public function testExecute() $constraint = $this->createConstraintMock(); $query = $this->createQueryMock(); + $result = $this->createMock(QueryResultInterface::class); $query->expects($this->once()) - ->method('execute'); + ->method('execute') + ->willReturn($result) + ; $query->expects($this->once()) ->method('bindValue'); @@ -406,11 +413,13 @@ public function testExecute() ->willReturn($query); $qb = new QueryBuilder($this->qf); - $qb->from($source) - ->where($constraint) - ->setFirstResult(10) - ->setMaxResults(10) - ->setParameter('Key', 'value') - ->execute(); + $this->assertSame($result, + $qb->from($source) + ->where($constraint) + ->setFirstResult(10) + ->setMaxResults(10) + ->setParameter('Key', 'value') + ->execute() + ); } } diff --git a/tests/PHPCR/Tests/Util/QOM/Sql1GeneratorTest.php b/tests/PHPCR/Tests/Util/QOM/Sql1GeneratorTest.php index b3f37199..4bc2184e 100644 --- a/tests/PHPCR/Tests/Util/QOM/Sql1GeneratorTest.php +++ b/tests/PHPCR/Tests/Util/QOM/Sql1GeneratorTest.php @@ -74,15 +74,15 @@ public function testPopertyExistence() public function testFullTextSearch() { - $literal = $this->generator->evalFullTextSearch(null, "'foo'"); + $literal = $this->generator->evalFullTextSearch('', "'foo'"); $this->assertSame("CONTAINS(*, 'foo')", $literal); - $literal = $this->generator->evalFullTextSearch(null, "'foo'", 'bar'); + $literal = $this->generator->evalFullTextSearch('', "'foo'", 'bar'); $this->assertSame("CONTAINS(bar, 'foo')", $literal); } public function testColumns() { - $literal = $this->generator->evalColumns(null); + $literal = $this->generator->evalColumns([]); $this->assertSame('s', $literal); $literal = $this->generator->evalColumns(['bar', 'foo']); $this->assertSame('bar, foo', $literal); diff --git a/tests/PHPCR/Tests/Util/QOM/Sql2GeneratorTest.php b/tests/PHPCR/Tests/Util/QOM/Sql2GeneratorTest.php index 1dac2525..5517fb3f 100644 --- a/tests/PHPCR/Tests/Util/QOM/Sql2GeneratorTest.php +++ b/tests/PHPCR/Tests/Util/QOM/Sql2GeneratorTest.php @@ -75,7 +75,7 @@ public function testFullTextSearch() public function testColumns() { - $literal = $this->generator->evalColumns(null); + $literal = $this->generator->evalColumns([]); $this->assertSame('*', $literal); $literal = $this->generator->evalColumns(['bar', 'foo']); $this->assertSame('bar, foo', $literal); diff --git a/tests/PHPCR/Tests/Util/ValueConverterTest.php b/tests/PHPCR/Tests/Util/ValueConverterTest.php index e69ed968..ce74b05f 100644 --- a/tests/PHPCR/Tests/Util/ValueConverterTest.php +++ b/tests/PHPCR/Tests/Util/ValueConverterTest.php @@ -16,17 +16,14 @@ */ class ValueConverterTest extends TestCase { - /** - * @var ValueConverter - */ - private $valueConverter; + private ValueConverter $valueConverter; public function setUp(): void { $this->valueConverter = new ValueConverter(); } - public function dataConversionMatrix() + public function dataConversionMatrix(): array { $stream = fopen('php://memory', '+rw'); fwrite($stream, 'test string'); @@ -267,11 +264,9 @@ public function dataConversionMatrix() /** * Skip binary target as its a special case. * - * @param int $srcType PropertyType constant to convert from - * * @dataProvider dataConversionMatrix */ - public function testConvertType($value, $srcType, $expected, $targetType) + public function testConvertType(mixed $value, int $srcType, mixed $expected, int $targetType): void { if (null === $expected) { try { @@ -292,7 +287,7 @@ public function testConvertType($value, $srcType, $expected, $targetType) } } - public function testConvertTypeToBinary() + public function testConvertTypeToBinary(): void { $stream = $this->valueConverter->convertType('test string', PropertyType::BINARY); $this->assertIsResource($stream); @@ -311,7 +306,7 @@ public function testConvertTypeToBinary() $readDate = new \DateTime($string); $this->assertEquals($date->getTimestamp(), $readDate->getTimestamp()); - $stream = fopen('php://memory', '+rw'); + $stream = fopen('php://memory', '+rwb'); fwrite($stream, 'test string'); rewind($stream); @@ -321,7 +316,7 @@ public function testConvertTypeToBinary() // if conversion to string works, should be fine for all others } - public function testConvertTypeArray() + public function testConvertTypeArray(): void { $result = $this->valueConverter->convertType( ['2012-01-10', '2012-02-12'], @@ -341,7 +336,7 @@ public function testConvertTypeArray() $this->assertEquals([], $result); } - public function testConvertTypeAutodetect() + public function testConvertTypeAutodetect(): void { $date = new \DateTime('2012-10-10'); $result = $this->valueConverter->convertType($date, PropertyType::STRING); @@ -353,35 +348,35 @@ public function testConvertTypeAutodetect() $this->assertEquals(1331668855, $result->getTimestamp()); } - public function testConvertTypeArrayInvalid() + public function testConvertTypeArrayInvalid(): void { $this->expectException(ValueFormatException::class); $this->valueConverter->convertType(['a', 'b', 'c'], PropertyType::NAME, PropertyType::REFERENCE); } - public function testConvertInvalidString() + public function testConvertInvalidString(): void { $this->expectException(ValueFormatException::class); $this->valueConverter->convertType($this, PropertyType::STRING); } - public function testConvertInvalidBinary() + public function testConvertInvalidBinary(): void { $this->expectException(ValueFormatException::class); $this->valueConverter->convertType($this, PropertyType::BINARY); } - public function testConvertInvalidDate() + public function testConvertInvalidDate(): void { $this->expectException(ValueFormatException::class); $this->valueConverter->convertType($this, PropertyType::DATE); } - public function testConvertNewNode() + public function testConvertNewNode(): void { $this->expectException(ValueFormatException::class); @@ -393,7 +388,7 @@ public function testConvertNewNode() $this->valueConverter->convertType($nodeMock, PropertyType::STRING); } - public function testConvertNonRefNode() + public function testConvertNonRefNode(): void { $this->expectException(ValueFormatException::class); @@ -410,7 +405,10 @@ public function testConvertNonRefNode() $this->valueConverter->convertType($nodeMock, PropertyType::STRING); } - public function dataDateTargetType() + /** + * @return array> + */ + public function dataDateTargetType(): array { return [ [PropertyType::STRING], @@ -424,14 +422,14 @@ public function dataDateTargetType() * * @dataProvider dataDateTargetType */ - public function testConvertInvalidDateValue($targettype) + public function testConvertInvalidDateValue(int $targettype): void { $this->expectException(RepositoryException::class); $this->valueConverter->convertType('', $targettype, PropertyType::DATE); } - public function testConvertTypeInvalidTarget() + public function testConvertTypeInvalidTarget(): void { $this->expectException(ValueFormatException::class); From ec608adceef86abd177db2284a4d5b9e6b65112a Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Tue, 28 Nov 2023 10:12:36 +0100 Subject: [PATCH 05/13] modernize code for php8 --- .../Util/CND/Exception/ParserException.php | 2 + .../Util/CND/Exception/ScannerException.php | 2 + src/PHPCR/Util/CND/Parser/AbstractParser.php | 2 + src/PHPCR/Util/CND/Parser/CndParser.php | 2 + src/PHPCR/Util/CND/Reader/BufferReader.php | 2 + src/PHPCR/Util/CND/Reader/FileReader.php | 2 + src/PHPCR/Util/CND/Reader/ReaderInterface.php | 2 + .../Util/CND/Scanner/AbstractScanner.php | 2 + .../Scanner/Context/DefaultScannerContext.php | 2 + ...ScannerContextWithoutSpacesAndComments.php | 2 + .../CND/Scanner/Context/ScannerContext.php | 2 + src/PHPCR/Util/CND/Scanner/GenericScanner.php | 2 + src/PHPCR/Util/CND/Scanner/GenericToken.php | 2 + src/PHPCR/Util/CND/Scanner/Token.php | 2 + .../Scanner/TokenFilter/NoCommentsFilter.php | 2 + .../Scanner/TokenFilter/NoNewlinesFilter.php | 2 + .../TokenFilter/NoWhitespacesFilter.php | 2 + .../Scanner/TokenFilter/TokenFilterChain.php | 2 + .../TokenFilter/TokenFilterInterface.php | 2 + .../Scanner/TokenFilter/TokenTypeFilter.php | 2 + src/PHPCR/Util/CND/Scanner/TokenQueue.php | 2 + src/PHPCR/Util/CND/Writer/CndWriter.php | 2 + .../Util/Console/Command/BaseCommand.php | 2 + .../Command/BaseNodeManipulationCommand.php | 2 + .../Util/Console/Command/NodeDumpCommand.php | 20 +++---- .../Util/Console/Command/NodeMoveCommand.php | 14 ++--- .../Console/Command/NodeRemoveCommand.php | 16 +++--- .../Util/Console/Command/NodeTouchCommand.php | 22 ++++---- .../Console/Command/NodeTypeListCommand.php | 8 +-- .../Command/NodeTypeRegisterCommand.php | 30 ++++++----- .../Console/Command/NodesUpdateCommand.php | 38 ++++++------- .../Command/WorkspaceCreateCommand.php | 10 ++-- .../Command/WorkspaceDeleteCommand.php | 12 +++-- .../Command/WorkspaceExportCommand.php | 12 +++-- .../Command/WorkspaceImportCommand.php | 42 ++++++++------- .../Console/Command/WorkspaceListCommand.php | 6 ++- .../Console/Command/WorkspacePurgeCommand.php | 8 +-- .../Console/Command/WorkspaceQueryCommand.php | 2 + .../Helper/PhpcrConsoleDumperHelper.php | 2 + src/PHPCR/Util/Console/Helper/PhpcrHelper.php | 4 +- .../TreeDumper/ConsoleDumperItemVisitor.php | 2 + .../TreeDumper/ConsoleDumperNodeVisitor.php | 4 +- .../ConsoleDumperPropertyVisitor.php | 4 +- .../Helper/TreeDumper/SystemNodeFilter.php | 2 + src/PHPCR/Util/NodeHelper.php | 4 +- src/PHPCR/Util/PathHelper.php | 2 + .../Util/QOM/BaseQomToSqlQueryConverter.php | 4 +- src/PHPCR/Util/QOM/BaseSqlGenerator.php | 2 + .../QOM/NotSupportedConstraintException.php | 4 +- .../Util/QOM/NotSupportedOperandException.php | 4 +- .../Util/QOM/QomToSql1QueryConverter.php | 4 +- .../Util/QOM/QomToSql2QueryConverter.php | 4 +- src/PHPCR/Util/QOM/QueryBuilder.php | 4 +- src/PHPCR/Util/QOM/Sql1Generator.php | 2 + src/PHPCR/Util/QOM/Sql2Generator.php | 2 + src/PHPCR/Util/QOM/Sql2Scanner.php | 2 + .../Util/QOM/Sql2ToQomQueryConverter.php | 16 +++--- src/PHPCR/Util/TraversingItemVisitor.php | 4 +- src/PHPCR/Util/TreeWalker.php | 2 + src/PHPCR/Util/TreeWalkerFilterInterface.php | 2 + src/PHPCR/Util/UUIDHelper.php | 2 + src/PHPCR/Util/ValueConverter.php | 39 +++++++++----- tests/PHPCR/Tests/Stubs/MockNode.php | 2 + .../PHPCR/Tests/Stubs/MockNodeTypeManager.php | 2 + tests/PHPCR/Tests/Stubs/MockRow.php | 2 + .../Util/CND/Reader/BufferReaderTest.php | 4 +- .../Tests/Util/CND/Reader/FileReaderTest.php | 8 +-- .../Util/CND/Scanner/GenericScannerTest.php | 10 ++-- .../Tests/Util/CND/Scanner/TokenQueueTest.php | 14 ++--- .../Tests/Util/CND/Scanner/TokenTest.php | 10 ++-- .../Util/Console/Command/BaseCommandTest.php | 2 + .../Console/Command/NodeDumpCommandTest.php | 10 ++-- .../Console/Command/NodeMoveCommandTest.php | 4 +- .../Console/Command/NodeRemoveCommandTest.php | 6 ++- .../Console/Command/NodeTouchCommandTest.php | 8 +-- .../Command/NodeTypeListCommandTest.php | 4 +- .../Command/NodeTypeRegisterCommandTest.php | 4 +- .../Command/NodesUpdateCommandTest.php | 12 +++-- .../Command/WorkspaceCreateCommandTest.php | 6 ++- .../Command/WorkspaceDeleteCommandTest.php | 6 ++- .../Command/WorkspaceExportCommandTest.php | 4 +- .../Command/WorkspaceImportCommandTest.php | 6 ++- .../Command/WorkspaceListCommandTest.php | 12 +++-- .../Command/WorkspacePurgeCommandTest.php | 4 +- .../Command/WorkspaceQueryCommandTest.php | 4 +- .../Helper/PhpcrConsoleDumperHelperTest.php | 4 +- tests/PHPCR/Tests/Util/NodeHelperTest.php | 20 +++---- tests/PHPCR/Tests/Util/PathHelperTest.php | 44 +++++++-------- .../Tests/Util/QOM/BaseSqlGeneratorTest.php | 4 +- .../PHPCR/Tests/Util/QOM/QueryBuilderTest.php | 53 ++++++++++--------- .../Tests/Util/QOM/Sql1GeneratorTest.php | 24 +++++---- .../Tests/Util/QOM/Sql2GeneratorTest.php | 24 +++++---- .../PHPCR/Tests/Util/QOM/Sql2ScannerTest.php | 34 ++++++------ .../Util/QOM/Sql2ToQomQueryConverterTest.php | 4 +- .../Tests/Util/TraversingItemVisitorTest.php | 4 +- tests/PHPCR/Tests/Util/UUIDHelperTest.php | 6 ++- tests/PHPCR/Tests/Util/ValueConverterTest.php | 2 + tests/bootstrap.php | 2 + 98 files changed, 493 insertions(+), 285 deletions(-) diff --git a/src/PHPCR/Util/CND/Exception/ParserException.php b/src/PHPCR/Util/CND/Exception/ParserException.php index 8be90b32..3cb73bdc 100644 --- a/src/PHPCR/Util/CND/Exception/ParserException.php +++ b/src/PHPCR/Util/CND/Exception/ParserException.php @@ -1,5 +1,7 @@ setDescription('Dump subtrees of the content repository') ->setHelp( <<<'HERE' -The dump command recursively outputs the name of the node specified -by the identifier argument and its subnodes in a yaml-like style. + The dump command recursively outputs the name of the node specified + by the identifier argument and its subnodes in a yaml-like style. -If the props option is used the nodes properties are -displayed as yaml arrays. + If the props option is used the nodes properties are + displayed as yaml arrays. -By default the command filters out system nodes and properties (i.e. nodes and -properties with names starting with 'jcr:'), the --sys-nodes option -allows to turn this filter off. -HERE + By default the command filters out system nodes and properties (i.e. nodes and + properties with names starting with 'jcr:'), the --sys-nodes option + allows to turn this filter off. + HERE ); } @@ -83,7 +85,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $node = $session->getNode($identifier); } - $walker->traverse($node, $input->getOption('depth')); + $walker->traverse($node, (int) $input->getOption('depth')); } catch (RepositoryException $e) { if ($e instanceof PathNotFoundException || $e instanceof ItemNotFoundException) { $output->writeln("Path '$identifier' does not exist"); diff --git a/src/PHPCR/Util/Console/Command/NodeMoveCommand.php b/src/PHPCR/Util/Console/Command/NodeMoveCommand.php index 2eef8c19..e6b67303 100644 --- a/src/PHPCR/Util/Console/Command/NodeMoveCommand.php +++ b/src/PHPCR/Util/Console/Command/NodeMoveCommand.php @@ -1,5 +1,7 @@ setDescription('Moves a node from one path to another') ->setHelp( <<<'EOF' -This command simply moves a node from one path (the source path) -to another (the destination path), it can also be considered -as a rename command. + This command simply moves a node from one path (the source path) + to another (the destination path), it can also be considered + as a rename command. - $ php bin/phpcr phpcr:move /foobar /barfoo + $ php bin/phpcr phpcr:move /foobar /barfoo -Note that the parent node of the destination path must already exist. -EOF + Note that the parent node of the destination path must already exist. + EOF ); } diff --git a/src/PHPCR/Util/Console/Command/NodeRemoveCommand.php b/src/PHPCR/Util/Console/Command/NodeRemoveCommand.php index bbf0071c..ec987051 100644 --- a/src/PHPCR/Util/Console/Command/NodeRemoveCommand.php +++ b/src/PHPCR/Util/Console/Command/NodeRemoveCommand.php @@ -1,5 +1,7 @@ addOption('only-children', null, InputOption::VALUE_NONE, 'Use to only purge children of specified path') ->setHelp( <<<'EOF' -The phpcr:node:remove command will remove the given node or the -children of the given node according to the options given. + The phpcr:node:remove command will remove the given node or the + children of the given node according to the options given. -Remove specified node and its children: + Remove specified node and its children: - $ php bin/phpcr phpcr:node:remove /cms/content/blog + $ php bin/phpcr phpcr:node:remove /cms/content/blog -Remove only the children of the specified node + Remove only the children of the specified node - $ php bin/phpcr phpcr:node:remove /cms/content/blog --only-children -EOF + $ php bin/phpcr phpcr:node:remove /cms/content/blog --only-children + EOF ); } diff --git a/src/PHPCR/Util/Console/Command/NodeTouchCommand.php b/src/PHPCR/Util/Console/Command/NodeTouchCommand.php index f397e4b6..3ff77f0a 100644 --- a/src/PHPCR/Util/Console/Command/NodeTouchCommand.php +++ b/src/PHPCR/Util/Console/Command/NodeTouchCommand.php @@ -1,5 +1,7 @@ setDescription('Create or modify a node') ->setHelp( <<<'HERE' -This command allows you to create or modify a node at the specified path. + This command allows you to create or modify a node at the specified path. -For example:: + For example:: - $ ./bin/phpcr phpcr:touch /foobar --type=my:nodetype --set-prop=foo=bar + $ ./bin/phpcr phpcr:touch /foobar --type=my:nodetype --set-prop=foo=bar -Will create the node "/foobar" and set (or create) the "foo" property -with a value of "bar". + Will create the node "/foobar" and set (or create) the "foo" property + with a value of "bar". -You can execute the command again to further modify the node. Here we add -the property "bar" and remove the property "foo". We also add the dump option -to output a string reperesentation of the node. + You can execute the command again to further modify the node. Here we add + the property "bar" and remove the property "foo". We also add the dump option + to output a string reperesentation of the node. - $ ./bin/phpcr phpcr:touch /foobar --type=my:nodetype --set-prop=bar=myvalue --remove-prop=foo --dump -HERE + $ ./bin/phpcr phpcr:touch /foobar --type=my:nodetype --set-prop=bar=myvalue --remove-prop=foo --dump + HERE ); } diff --git a/src/PHPCR/Util/Console/Command/NodeTypeListCommand.php b/src/PHPCR/Util/Console/Command/NodeTypeListCommand.php index 557e6fa7..88c6dbba 100644 --- a/src/PHPCR/Util/Console/Command/NodeTypeListCommand.php +++ b/src/PHPCR/Util/Console/Command/NodeTypeListCommand.php @@ -1,5 +1,7 @@ setDescription('List all available node types in the repository') ->setHelp( <<<'EOT' -This command lists all of the available node types and their subtypes -in the PHPCR repository. -EOT + This command lists all of the available node types and their subtypes + in the PHPCR repository. + EOT ); } diff --git a/src/PHPCR/Util/Console/Command/NodeTypeRegisterCommand.php b/src/PHPCR/Util/Console/Command/NodeTypeRegisterCommand.php index 3fc5c9dd..7950ee4b 100644 --- a/src/PHPCR/Util/Console/Command/NodeTypeRegisterCommand.php +++ b/src/PHPCR/Util/Console/Command/NodeTypeRegisterCommand.php @@ -1,5 +1,7 @@ addOption('allow-update', null, InputOption::VALUE_NONE, 'Overwrite existig node type') ->setHelp( <<<'EOT' -Register node types in the PHPCR repository. + Register node types in the PHPCR repository. -This command allows to register node types in the repository that are defined -in a CND (Compact Namespace and Node Type Definition) file as defined in the JCR-283 -specification. + This command allows to register node types in the repository that are defined + in a CND (Compact Namespace and Node Type Definition) file as defined in the JCR-283 + specification. -Custom node types can be used to define the structure of content repository -nodes, like allowed properties and child nodes together with the namespaces -and their prefix used for the names of node types and properties. + Custom node types can be used to define the structure of content repository + nodes, like allowed properties and child nodes together with the namespaces + and their prefix used for the names of node types and properties. -This command allows you to specify multiple files and/or folders: + This command allows you to specify multiple files and/or folders: - $ php app/console phpcr:node-type:register /path/to/nodetype1.cnd /path/to/a/folder + $ php app/console phpcr:node-type:register /path/to/nodetype1.cnd /path/to/a/folder -When a folder is specified all files within the folder that have the .cnd -extension will be treated as node definition files. + When a folder is specified all files within the folder that have the .cnd + extension will be treated as node definition files. -If you use --allow-update existing node type definitions will be overwritten -in the repository. -EOT + If you use --allow-update existing node type definitions will be overwritten + in the repository. + EOT ); } diff --git a/src/PHPCR/Util/Console/Command/NodesUpdateCommand.php b/src/PHPCR/Util/Console/Command/NodesUpdateCommand.php index fd49f99a..eeb4d94f 100644 --- a/src/PHPCR/Util/Console/Command/NodesUpdateCommand.php +++ b/src/PHPCR/Util/Console/Command/NodesUpdateCommand.php @@ -1,5 +1,7 @@ setDescription('Command to manipulate the nodes in the workspace.') ->setHelp( <<phpcr:nodes:update can manipulate the properties of nodes -found using the given query. + The phpcr:nodes:update can manipulate the properties of nodes + found using the given query. -For example, to set the property foo to bar on all unstructured nodes: + For example, to set the property foo to bar on all unstructured nodes: - php bin/phpcr phpcr:nodes:update --query="SELECT * FROM [nt:unstructured]" --set-prop=foo=bar + php bin/phpcr phpcr:nodes:update --query="SELECT * FROM [nt:unstructured]" --set-prop=foo=bar -Or to update only nodes matching a certain criteria: + Or to update only nodes matching a certain criteria: - php bin/phpcr phpcr:nodes:update \ - --query="SELECT * FROM [nt:unstructured] WHERE [phpcr:class]=\"Some\\Class\\Here\"" \ - --add-mixin=mix:mimetype + php bin/phpcr phpcr:nodes:update \ + --query="SELECT * FROM [nt:unstructured] WHERE [phpcr:class]=\"Some\\Class\\Here\"" \ + --add-mixin=mix:mimetype -The options for manipulating nodes are the same as with the -node:touch command and -can be repeated to update multiple properties. + The options for manipulating nodes are the same as with the + node:touch command and + can be repeated to update multiple properties. -If you have an advanced use case you can use the --apply-closure option: + If you have an advanced use case you can use the --apply-closure option: - php bin/phpcr phpcr:nodes:update \ - --query="SELECT * FROM [nt:unstructured] WHERE [phpcr:class]=\"Some\\Class\\Here\"" \ - --apply-closure="\\\$session->doSomething(); \\\$node->setProperty('foo', 'bar');" + php bin/phpcr phpcr:nodes:update \ + --query="SELECT * FROM [nt:unstructured] WHERE [phpcr:class]=\"Some\\Class\\Here\"" \ + --apply-closure="\\\$session->doSomething(); \\\$node->setProperty('foo', 'bar');" -For each node in the result set, the closure will be passed the current -PHPCR\SessionInterface implementation and the node (PHPCR\NodeInterface) as \$session and \$node. -HERE + For each node in the result set, the closure will be passed the current + PHPCR\SessionInterface implementation and the node (PHPCR\NodeInterface) as \$session and \$node. + HERE ); } diff --git a/src/PHPCR/Util/Console/Command/WorkspaceCreateCommand.php b/src/PHPCR/Util/Console/Command/WorkspaceCreateCommand.php index 90ce44a9..07f6c554 100644 --- a/src/PHPCR/Util/Console/Command/WorkspaceCreateCommand.php +++ b/src/PHPCR/Util/Console/Command/WorkspaceCreateCommand.php @@ -1,5 +1,7 @@ setDescription('Create a workspace in the configured repository') ->setHelp( <<<'EOT' -The workspace:create command creates a workspace with the specified name. -It will fail if a workspace with that name already exists or if the repository implementation -does not support the workspace creation operation. -EOT + The workspace:create command creates a workspace with the specified name. + It will fail if a workspace with that name already exists or if the repository implementation + does not support the workspace creation operation. + EOT ); } diff --git a/src/PHPCR/Util/Console/Command/WorkspaceDeleteCommand.php b/src/PHPCR/Util/Console/Command/WorkspaceDeleteCommand.php index 8a6bee19..23662768 100644 --- a/src/PHPCR/Util/Console/Command/WorkspaceDeleteCommand.php +++ b/src/PHPCR/Util/Console/Command/WorkspaceDeleteCommand.php @@ -1,5 +1,7 @@ setDescription('Delete a workspace from the configured repository') ->setHelp( <<<'EOT' -The workspace:delete command deletes the workspace with the specified name if it -exists. If the workspace with that name does not yet exist, the command will not fail. -However, if the workspace does exist but the repository implementation does not support -the delete operation, the command will fail. -EOT + The workspace:delete command deletes the workspace with the specified name if it + exists. If the workspace with that name does not yet exist, the command will not fail. + However, if the workspace does exist but the repository implementation does not support + the delete operation, the command will fail. + EOT ); } diff --git a/src/PHPCR/Util/Console/Command/WorkspaceExportCommand.php b/src/PHPCR/Util/Console/Command/WorkspaceExportCommand.php index 1487b4af..25009189 100644 --- a/src/PHPCR/Util/Console/Command/WorkspaceExportCommand.php +++ b/src/PHPCR/Util/Console/Command/WorkspaceExportCommand.php @@ -1,5 +1,7 @@ setDescription('Export nodes from the repository, either to the JCR system view format or the document view format') ->setHelp( <<<'EOF' -The export command uses the PHPCR SessionInterface::exportSystemView -method to export parts of the repository into an XML document. + The export command uses the PHPCR SessionInterface::exportSystemView + method to export parts of the repository into an XML document. -If the path option is set, given path is exported. -Otherwise the entire repository is exported. -EOF + If the path option is set, given path is exported. + Otherwise the entire repository is exported. + EOF ); } diff --git a/src/PHPCR/Util/Console/Command/WorkspaceImportCommand.php b/src/PHPCR/Util/Console/Command/WorkspaceImportCommand.php index 109f3f96..b9b0047c 100644 --- a/src/PHPCR/Util/Console/Command/WorkspaceImportCommand.php +++ b/src/PHPCR/Util/Console/Command/WorkspaceImportCommand.php @@ -1,5 +1,7 @@ setDescription('Import xml data into the repository, either in JCR system view format or arbitrary xml') ->setHelp( <<<'EOF' -The import command uses the PHPCR SessionInterface::importXml method -to import an XML document into the repository. If the document is in the JCR -system view format, it is interpreted according to the spec, otherwise it is -treated as document view format, meaning XML elements are translated to nodes -and XML attributes into properties. - -If the parentpath option is set, the document is imported to that -path. Otherwise the document is imported at the repository root. - -The optional uuid-behavior option describes how UUIDs should be -handled. The following options are available: - -* new recreate a new uuid for each imported node; -* remove on collision, remove the old node from the repository and - put the imported data in the tree; -* replace on collision, replace the existing node with the one being - imported. All children of the imported node also go to the new path; -* throw throw an exception on uuid collision. - -EOF + The import command uses the PHPCR SessionInterface::importXml method + to import an XML document into the repository. If the document is in the JCR + system view format, it is interpreted according to the spec, otherwise it is + treated as document view format, meaning XML elements are translated to nodes + and XML attributes into properties. + + If the parentpath option is set, the document is imported to that + path. Otherwise the document is imported at the repository root. + + The optional uuid-behavior option describes how UUIDs should be + handled. The following options are available: + + * new recreate a new uuid for each imported node; + * remove on collision, remove the old node from the repository and + put the imported data in the tree; + * replace on collision, replace the existing node with the one being + imported. All children of the imported node also go to the new path; + * throw throw an exception on uuid collision. + + EOF ); } diff --git a/src/PHPCR/Util/Console/Command/WorkspaceListCommand.php b/src/PHPCR/Util/Console/Command/WorkspaceListCommand.php index 4210891c..3a5d6317 100644 --- a/src/PHPCR/Util/Console/Command/WorkspaceListCommand.php +++ b/src/PHPCR/Util/Console/Command/WorkspaceListCommand.php @@ -1,5 +1,7 @@ setDescription('List all available workspaces in the configured repository') ->setHelp( <<<'EOT' -The workspace:list command lists all avaialable workspaces. -EOT + The workspace:list command lists all avaialable workspaces. + EOT ); } diff --git a/src/PHPCR/Util/Console/Command/WorkspacePurgeCommand.php b/src/PHPCR/Util/Console/Command/WorkspacePurgeCommand.php index c9112bb9..ac2dc07d 100644 --- a/src/PHPCR/Util/Console/Command/WorkspacePurgeCommand.php +++ b/src/PHPCR/Util/Console/Command/WorkspacePurgeCommand.php @@ -1,5 +1,7 @@ addOption('force', null, InputOption::VALUE_NONE, 'Use to bypass the confirmation dialog') ->setHelp( <<<'EOF' -The phpcr:workspace:purge command removes all nodes except the -system nodes and all non-system properties of the root node from the workspace. -EOF + The phpcr:workspace:purge command removes all nodes except the + system nodes and all non-system properties of the root node from the workspace. + EOF ); } diff --git a/src/PHPCR/Util/Console/Command/WorkspaceQueryCommand.php b/src/PHPCR/Util/Console/Command/WorkspaceQueryCommand.php index d7015fff..2b9944e8 100644 --- a/src/PHPCR/Util/Console/Command/WorkspaceQueryCommand.php +++ b/src/PHPCR/Util/Console/Command/WorkspaceQueryCommand.php @@ -1,5 +1,7 @@ writeln(sprintf( diff --git a/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperItemVisitor.php b/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperItemVisitor.php index a28551e7..d9b1d867 100644 --- a/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperItemVisitor.php +++ b/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperItemVisitor.php @@ -1,5 +1,7 @@ getDepth()) { diff --git a/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperPropertyVisitor.php b/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperPropertyVisitor.php index 55ddc74a..97f696d3 100644 --- a/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperPropertyVisitor.php +++ b/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperPropertyVisitor.php @@ -1,5 +1,7 @@ getString(); diff --git a/src/PHPCR/Util/Console/Helper/TreeDumper/SystemNodeFilter.php b/src/PHPCR/Util/Console/Helper/TreeDumper/SystemNodeFilter.php index cffc9b88..64a7e796 100644 --- a/src/PHPCR/Util/Console/Helper/TreeDumper/SystemNodeFilter.php +++ b/src/PHPCR/Util/Console/Helper/TreeDumper/SystemNodeFilter.php @@ -1,5 +1,7 @@ generator->evalFullText($literal); diff --git a/src/PHPCR/Util/QOM/BaseSqlGenerator.php b/src/PHPCR/Util/QOM/BaseSqlGenerator.php index f1b43f1c..2215ec74 100644 --- a/src/PHPCR/Util/QOM/BaseSqlGenerator.php +++ b/src/PHPCR/Util/QOM/BaseSqlGenerator.php @@ -1,5 +1,7 @@ params[$key]) ? $this->params[$key] : null; + return $this->params[$key] ?? null; } /** diff --git a/src/PHPCR/Util/QOM/Sql1Generator.php b/src/PHPCR/Util/QOM/Sql1Generator.php index 94edccff..3f637a98 100644 --- a/src/PHPCR/Util/QOM/Sql1Generator.php +++ b/src/PHPCR/Util/QOM/Sql1Generator.php @@ -1,5 +1,7 @@ parseIdentifier(); + [$selectorName1, $prop1] = $this->parseIdentifier(); $this->scanner->expectToken('='); - list($selectorName2, $prop2) = $this->parseIdentifier(); + [$selectorName2, $prop2] = $this->parseIdentifier(); return $this->factory->equiJoinCondition($selectorName1, $prop1, $selectorName2, $prop2); } @@ -484,7 +486,7 @@ protected function parseOperator(): string */ protected function parsePropertyExistence(): ConstraintInterface { - list($selectorName, $prop) = $this->parseIdentifier(); + [$selectorName, $prop] = $this->parseIdentifier(); $this->scanner->expectToken('IS'); $token = $this->scanner->lookupNextToken(); @@ -506,7 +508,7 @@ protected function parseFullTextSearch(): FullTextSearchInterface { $this->scanner->expectTokens(['CONTAINS', '(']); - list($selectorName, $propertyName) = $this->parseIdentifier(); + [$selectorName, $propertyName] = $this->parseIdentifier(); $this->scanner->expectToken(','); $expression = $this->parseLiteralValue(); $this->scanner->expectToken(')'); @@ -697,7 +699,7 @@ protected function parseDynamicOperand(): DynamicOperandInterface|PropertyValueI */ protected function parsePropertyValue(): PropertyValueInterface { - list($selectorName, $prop) = $this->parseIdentifier(); + [$selectorName, $prop] = $this->parseIdentifier(); return $this->factory->propertyValue($selectorName, $prop); } @@ -967,7 +969,7 @@ protected function ensureSelectorName(?string $parsedName): array|string|null */ protected function scanColumn(): array { - list($selectorName, $propertyName) = $this->parseIdentifier(false); + [$selectorName, $propertyName] = $this->parseIdentifier(false); // AS name if ($this->scanner->tokenIs($this->scanner->lookupNextToken(), 'AS')) { @@ -987,7 +989,7 @@ protected function scanColumn(): array */ protected function buildColumn(array $data): ColumnInterface { - list($selectorName, $propertyName, $columnName) = $data; + [$selectorName, $propertyName, $columnName] = $data; $selectorName = $this->ensureSelectorName($selectorName); return $this->factory->column($selectorName, $propertyName, $columnName); diff --git a/src/PHPCR/Util/TraversingItemVisitor.php b/src/PHPCR/Util/TraversingItemVisitor.php index 911e2ba7..1ee1ced9 100644 --- a/src/PHPCR/Util/TraversingItemVisitor.php +++ b/src/PHPCR/Util/TraversingItemVisitor.php @@ -1,5 +1,7 @@ getName(), $item->getPath(), - get_class($item) + $item::class )); } diff --git a/src/PHPCR/Util/TreeWalker.php b/src/PHPCR/Util/TreeWalker.php index 52fb7533..0ebe6f03 100644 --- a/src/PHPCR/Util/TreeWalker.php +++ b/src/PHPCR/Util/TreeWalker.php @@ -1,5 +1,7 @@ getTimestamp(); } if (is_object($value)) { - throw new ValueFormatException('Cannot convert object of class "'.get_class($value).'" to a LONG'); + throw new ValueFormatException('Cannot convert object of class "'.$value::class.'" to a LONG'); } throw new ValueFormatException('Cannot convert "'.var_export($value, true).'" to a LONG'); @@ -232,7 +234,7 @@ public function convertType(mixed $value, int $type, int $srcType = PropertyType return (float) $value->getTimestamp(); } if (is_object($value)) { - throw new ValueFormatException('Cannot convert object of class "'.get_class($value).'" to a DOUBLE'); + throw new ValueFormatException('Cannot convert object of class "'.$value::class.'" to a DOUBLE'); } throw new ValueFormatException('Cannot convert "'.var_export($value, true).'" to a DOUBLE'); @@ -250,15 +252,26 @@ public function convertType(mixed $value, int $type, int $srcType = PropertyType throw new ValueFormatException("String '$value' is not a valid date", 0, $e); } case PropertyType::LONG: + return (new \DateTime()) + ->setTimestamp($value) + ; case PropertyType::DOUBLE: + return (new \DateTime()) + ->setTimestamp((int) round($value)) + ; case PropertyType::DECIMAL: - $datetime = new \DateTime(); - $datetime = $datetime->setTimestamp(round($value)); + if (function_exists('bccomp') + && 1 === \bccomp($value, (string) PHP_INT_MAX) + ) { + throw new ValueFormatException('Decimal number is too large for integer'); + } - return $datetime; + return (new \DateTime()) + ->setTimestamp((int) round((float) $value)) + ; } if (is_object($value)) { - throw new ValueFormatException('Cannot convert object of class "'.get_class($value).'" to a DATE'); + throw new ValueFormatException('Cannot convert object of class "'.$value::class.'" to a DATE'); } throw new ValueFormatException('Cannot convert "'.var_export($value, true).'" to DATE'); @@ -277,7 +290,7 @@ public function convertType(mixed $value, int $type, int $srcType = PropertyType return (bool) ((float) $value); // '0' is false too } if (is_object($value)) { - throw new ValueFormatException('Cannot convert object of class "'.get_class($value).'" to a BOOLEAN'); + throw new ValueFormatException('Cannot convert object of class "'.$value::class.'" to a BOOLEAN'); } throw new ValueFormatException('Cannot convert "'.var_export($value, true).'" to a BOOLEAN'); @@ -293,7 +306,7 @@ public function convertType(mixed $value, int $type, int $srcType = PropertyType return $value; } if (is_object($value)) { - throw new ValueFormatException('Cannot convert object of class "'.get_class($value).'" to a NAME'); + throw new ValueFormatException('Cannot convert object of class "'.$value::class.'" to a NAME'); } throw new ValueFormatException('Cannot convert "'.var_export($value, true).'" to NAME'); @@ -310,7 +323,7 @@ public function convertType(mixed $value, int $type, int $srcType = PropertyType return $value; } if (is_object($value)) { - throw new ValueFormatException('Cannot convert object of class "'.get_class($value).'" to a PATH'); + throw new ValueFormatException('Cannot convert object of class "'.$value::class.'" to a PATH'); } throw new ValueFormatException('Cannot convert "'.var_export($value, true).'" to PATH'); @@ -328,7 +341,7 @@ public function convertType(mixed $value, int $type, int $srcType = PropertyType return $value; } if (is_object($value)) { - throw new ValueFormatException('Cannot convert object of class "'.get_class($value).'" to a unique id'); + throw new ValueFormatException('Cannot convert object of class "'.$value::class.'" to a unique id'); } throw new ValueFormatException('Cannot convert "'.var_export($value, true).'" to unique id'); @@ -352,7 +365,7 @@ public function convertType(mixed $value, int $type, int $srcType = PropertyType return $value; } if (is_object($value)) { - throw new ValueFormatException('Cannot convert object of class "'.get_class($value).'" to a URI'); + throw new ValueFormatException('Cannot convert object of class "'.$value::class.'" to a URI'); } throw new ValueFormatException('Cannot convert "'.var_export($value, true).'" to URI'); @@ -372,7 +385,7 @@ public function convertType(mixed $value, int $type, int $srcType = PropertyType return (string) $value->getTimestamp(); } if (is_object($value)) { - throw new ValueFormatException('Cannot convert object of class "'.get_class($value).'" to a DECIMAL'); + throw new ValueFormatException('Cannot convert object of class "'.$value::class.'" to a DECIMAL'); } throw new ValueFormatException('Cannot convert "'.var_export($value, true).'" to a DECIMAL'); diff --git a/tests/PHPCR/Tests/Stubs/MockNode.php b/tests/PHPCR/Tests/Stubs/MockNode.php index ea937214..68603a0a 100644 --- a/tests/PHPCR/Tests/Stubs/MockNode.php +++ b/tests/PHPCR/Tests/Stubs/MockNode.php @@ -1,5 +1,7 @@ assertEquals($reader->getEofMarker(), $reader->forward()); } - public function testConstructEmptyString() + public function testConstructEmptyString(): void { $reader = new BufferReader(''); diff --git a/tests/PHPCR/Tests/Util/CND/Reader/FileReaderTest.php b/tests/PHPCR/Tests/Util/CND/Reader/FileReaderTest.php index e7fed571..00e8fc89 100644 --- a/tests/PHPCR/Tests/Util/CND/Reader/FileReaderTest.php +++ b/tests/PHPCR/Tests/Util/CND/Reader/FileReaderTest.php @@ -1,5 +1,7 @@ expectException(\InvalidArgumentException::class); new FileReader('unexisting_file'); } - public function testGetPath() + public function testGetPath(): void { $this->assertEquals($this->filepath, $this->reader->getPath()); } - public function testGetNextChar() + public function testGetNextChar(): void { $curLine = 1; $curCol = 1; diff --git a/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php b/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php index 53c5212a..84982b55 100644 --- a/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php +++ b/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php @@ -1,5 +1,7 @@ assertTokens($this->expectedTokens, $queue); } - public function testFilteredScan() + public function testFilteredScan(): void { $reader = new FileReader(__DIR__.'/../Fixtures/files/TestFile.php'); @@ -138,7 +140,7 @@ public function testFilteredScan() $this->assertTokens($this->expectedTokensNoEmptyToken, $queue); } - protected function assertTokens($tokens, TokenQueue $queue) + protected function assertTokens($tokens, TokenQueue $queue): void { $queue->reset(); @@ -160,7 +162,7 @@ protected function assertTokens($tokens, TokenQueue $queue) $this->assertTrue($queue->isEof(), 'There are more unexpected tokens.'); } - protected function assertToken($type, $data, Token $token) + protected function assertToken($type, $data, Token|false $token): void { $this->assertEquals( $type, diff --git a/tests/PHPCR/Tests/Util/CND/Scanner/TokenQueueTest.php b/tests/PHPCR/Tests/Util/CND/Scanner/TokenQueueTest.php index 7af6afb0..8b653c50 100644 --- a/tests/PHPCR/Tests/Util/CND/Scanner/TokenQueueTest.php +++ b/tests/PHPCR/Tests/Util/CND/Scanner/TokenQueueTest.php @@ -1,5 +1,7 @@ queue->add($this->token3); } - public function testAdd() + public function testAdd(): void { $queue = new TokenQueue(); $reflection = new \ReflectionClass($queue); @@ -62,13 +64,13 @@ public function testAdd() $this->assertSame([$this->token0, $this->token1], $tokens->getValue($queue)); } - public function testResetAndPeek() + public function testResetAndPeek(): void { $this->assertEquals($this->token0, $this->queue->reset()); $this->assertEquals($this->token0, $this->queue->peek()); } - public function testIsEofAndNext() + public function testIsEofAndNext(): void { // Token0 $this->assertFalse($this->queue->isEof()); @@ -90,7 +92,7 @@ public function testIsEofAndNext() $this->assertTrue($this->queue->isEof()); } - public function testIsEofEmptyQueue() + public function testIsEofEmptyQueue(): void { $queue = new TokenQueue(); $this->assertTrue($queue->isEof()); @@ -98,7 +100,7 @@ public function testIsEofEmptyQueue() $this->assertFalse($queue->isEof()); } - public function testGet() + public function testGet(): void { $this->queue->reset(); $this->assertEquals($this->token0, $this->queue->get()); @@ -108,7 +110,7 @@ public function testGet() $this->assertEquals(false, $this->queue->get()); } - public function testGetIterator() + public function testGetIterator(): void { $this->assertEquals( [$this->token0, $this->token1, $this->token2, $this->token3], diff --git a/tests/PHPCR/Tests/Util/CND/Scanner/TokenTest.php b/tests/PHPCR/Tests/Util/CND/Scanner/TokenTest.php index 272ce1e4..08b7673b 100644 --- a/tests/PHPCR/Tests/Util/CND/Scanner/TokenTest.php +++ b/tests/PHPCR/Tests/Util/CND/Scanner/TokenTest.php @@ -1,5 +1,7 @@ token = new Token(123, 'foobar'); } - public function testConstruct() + public function testConstruct(): void { $this->assertSame(123, $this->token->type); $this->assertSame('foobar', $this->token->data); } - public function testGetData() + public function testGetData(): void { $this->assertEquals('foobar', $this->token->getData()); } - public function testGetType() + public function testGetType(): void { $this->assertEquals(123, $this->token->getType()); } - public function testToString() + public function testToString(): void { $this->assertEquals('TOKEN(123, \'foobar\', 0, 0)', $this->token->__toString()); } diff --git a/tests/PHPCR/Tests/Util/Console/Command/BaseCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/BaseCommandTest.php index 26c13f6f..84d430ec 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/BaseCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/BaseCommandTest.php @@ -1,5 +1,7 @@ application->add($ndCommand); } - public function testCommand() + public function testCommand(): void { $this->dumperHelper ->expects($this->once()) @@ -45,7 +47,7 @@ public function testCommand() $this->executeCommand('phpcr:node:dump', []); } - public function testCommandIdentifier() + public function testCommandIdentifier(): void { $uuid = UUIDHelper::generateUUID(); @@ -68,7 +70,7 @@ public function testCommandIdentifier() $this->executeCommand('phpcr:node:dump', ['identifier' => $uuid]); } - public function testInvalidRefFormat() + public function testInvalidRefFormat(): void { $this->expectException(\Exception::class); @@ -76,7 +78,7 @@ public function testInvalidRefFormat() $this->fail('invalid ref-format did not produce exception'); } - public function testNotFound() + public function testNotFound(): void { $this->session ->expects($this->once()) diff --git a/tests/PHPCR/Tests/Util/Console/Command/NodeMoveCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodeMoveCommandTest.php index 132aafb7..52d57760 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodeMoveCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodeMoveCommandTest.php @@ -1,5 +1,7 @@ session->expects($this->once()) ->method('move') diff --git a/tests/PHPCR/Tests/Util/Console/Command/NodeRemoveCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodeRemoveCommandTest.php index 7edbd102..6381ba59 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodeRemoveCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodeRemoveCommandTest.php @@ -1,5 +1,7 @@ application->add(new NodeRemoveCommand()); } - public function testRemove() + public function testRemove(): void { $this->session->expects($this->once()) ->method('removeItem') @@ -25,7 +27,7 @@ public function testRemove() ]); } - public function testRemoveRoot() + public function testRemoveRoot(): void { $this->expectException(\LogicException::class); diff --git a/tests/PHPCR/Tests/Util/Console/Command/NodeTouchCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodeTouchCommandTest.php index 30cc7fae..41febd1b 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodeTouchCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodeTouchCommandTest.php @@ -1,5 +1,7 @@ helperSet->set($this->phpcrHelper); } - public function testTouch() + public function testTouch(): void { $node = $this->node1; $child = $this->createMock(MockNode::class); @@ -71,7 +73,7 @@ public function testTouch() $this->executeCommand('phpcr:node:touch', ['path' => '/cms']); } - public function testUpdate() + public function testUpdate(): void { $nodeType = $this->createMock(NodeTypeInterface::class); $nodeType->expects($this->once()) @@ -91,7 +93,7 @@ public function testUpdate() $this->phpcrHelper->expects($this->once()) ->method('processNode') - ->willReturnCallback(function ($output, $node, $options) use ($me) { + ->willReturnCallback(function ($output, $node, $options) use ($me): void { $me->assertEquals($me->node1, $node); $me->assertEquals([ 'setProp' => ['foo=bar'], diff --git a/tests/PHPCR/Tests/Util/Console/Command/NodeTypeListCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodeTypeListCommandTest.php index f74f6fde..3359f872 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodeTypeListCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodeTypeListCommandTest.php @@ -1,5 +1,7 @@ getMock(); } - public function testNodeTypeList() + public function testNodeTypeList(): void { $this->session->expects($this->once()) ->method('getWorkspace') diff --git a/tests/PHPCR/Tests/Util/Console/Command/NodeTypeRegisterCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodeTypeRegisterCommandTest.php index b39fe38a..76fc4e71 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodeTypeRegisterCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodeTypeRegisterCommandTest.php @@ -1,5 +1,7 @@ getMock(); } - public function testNodeTypeRegister() + public function testNodeTypeRegister(): void { $this->session->expects($this->once()) ->method('getWorkspace') diff --git a/tests/PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php index a05ea5a5..251655a2 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php @@ -1,5 +1,7 @@ ''], $options); @@ -68,7 +70,7 @@ protected function setupQueryManager($options) /** * @dataProvider provideNodeUpdate */ - public function testNodeUpdate($options) + public function testNodeUpdate($options): void { $options = array_merge([ 'query' => null, @@ -96,7 +98,7 @@ public function testNodeUpdate($options) $setPropertyArguments = []; foreach ($options['setProp'] as $setProp) { - list($prop, $value) = $setProp; + [$prop, $value] = $setProp; $setPropertyArguments[] = [$prop, $value, null]; $args['--set-prop'][] = $prop.'='.$value; } @@ -129,14 +131,14 @@ public function testNodeUpdate($options) $this->executeCommand('phpcr:nodes:update', $args); } - public function testApplyClosure() + public function testApplyClosure(): void { $args = [ '--query' => 'SELECT foo FROM bar', '--no-interaction' => true, '--apply-closure' => [ '$session->getNodeByIdentifier("/foo"); $node->setProperty("foo", "bar");', - function ($session, $node) { + function ($session, $node): void { $node->setProperty('foo', 'bar'); }, ], diff --git a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceCreateCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceCreateCommandTest.php index 34f86086..f3352a3b 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceCreateCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceCreateCommandTest.php @@ -1,5 +1,7 @@ application->add(new WorkspaceCreateCommand()); } - public function testCreate() + public function testCreate(): void { $this->session->expects($this->once()) ->method('getWorkspace') @@ -45,7 +47,7 @@ public function testCreate() /** * Handle trying to create existing workspace. */ - public function testCreateExisting() + public function testCreateExisting(): void { $this->session->expects($this->exactly(2)) ->method('getWorkspace') diff --git a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceDeleteCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceDeleteCommandTest.php index ebd841fa..30df1404 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceDeleteCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceDeleteCommandTest.php @@ -1,5 +1,7 @@ application->add(new WorkspaceDeleteCommand()); } - public function testDelete() + public function testDelete(): void { $this->session->expects($this->once()) ->method('getWorkspace') @@ -45,7 +47,7 @@ public function testDelete() $this->assertStringContainsString("Deleted workspace 'test_workspace'.", $ct->getDisplay()); } - public function testDeleteNonexistent() + public function testDeleteNonexistent(): void { $this->session->expects($this->once()) ->method('getWorkspace') diff --git a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceExportCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceExportCommandTest.php index a16e2656..1868ed0c 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceExportCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceExportCommandTest.php @@ -1,5 +1,7 @@ session->expects($this->once()) ->method('getRepository') diff --git a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceImportCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceImportCommandTest.php index 5d2958c9..13e16cf4 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceImportCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceImportCommandTest.php @@ -1,5 +1,7 @@ application->add(new WorkspaceImportCommand()); } - public function testImport() + public function testImport(): void { $this->session->expects($this->once()) ->method('getRepository') @@ -37,7 +39,7 @@ public function testImport() $this->assertStringContainsString('Successfully imported', $ct->getDisplay()); } - public function testImportUuidBehaviorThrow() + public function testImportUuidBehaviorThrow(): void { $this->session->expects($this->once()) ->method('getRepository') diff --git a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceListCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceListCommandTest.php index 86ef8fc7..1044200d 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceListCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceListCommandTest.php @@ -1,5 +1,7 @@ application->add(new WorkspaceListCommand()); } - public function testNodeTypeList() + public function testNodeTypeList(): void { $this->session->expects($this->once()) ->method('getWorkspace') @@ -27,11 +29,11 @@ public function testNodeTypeList() ]); $expected = <<<'HERE' -The following 2 workspaces are available: -foo -bar + The following 2 workspaces are available: + foo + bar -HERE; + HERE; $this->assertEquals($expected, $ct->getDisplay()); } diff --git a/tests/PHPCR/Tests/Util/Console/Command/WorkspacePurgeCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/WorkspacePurgeCommandTest.php index 5938ac86..f37ecfe1 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/WorkspacePurgeCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/WorkspacePurgeCommandTest.php @@ -1,5 +1,7 @@ application->add(new WorkspacePurgeCommand()); } - public function testNodeTypePurge() + public function testNodeTypePurge(): void { $this->session->expects($this->once()) ->method('getRootNode') diff --git a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceQueryCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceQueryCommandTest.php index 9ab438bb..184f9cb2 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceQueryCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceQueryCommandTest.php @@ -1,5 +1,7 @@ query = $this->createMock(QueryInterface::class); } - public function testQuery() + public function testQuery(): void { $this->queryManager ->method('getSupportedQueryLanguages') diff --git a/tests/PHPCR/Tests/Util/Console/Helper/PhpcrConsoleDumperHelperTest.php b/tests/PHPCR/Tests/Util/Console/Helper/PhpcrConsoleDumperHelperTest.php index 6c4b97dc..575fc28e 100644 --- a/tests/PHPCR/Tests/Util/Console/Helper/PhpcrConsoleDumperHelperTest.php +++ b/tests/PHPCR/Tests/Util/Console/Helper/PhpcrConsoleDumperHelperTest.php @@ -1,5 +1,7 @@ false, diff --git a/tests/PHPCR/Tests/Util/NodeHelperTest.php b/tests/PHPCR/Tests/Util/NodeHelperTest.php index a3659292..68e514a1 100644 --- a/tests/PHPCR/Tests/Util/NodeHelperTest.php +++ b/tests/PHPCR/Tests/Util/NodeHelperTest.php @@ -1,5 +1,7 @@ usedNames, $this->namespaces, 'a'); $this->assertEquals('a:', substr($result, 0, 2)); @@ -64,7 +66,7 @@ public function testGenerateAutoNodeNameNoHint() /** * @dataProvider hints */ - public function testGenerateAutoNodeName($hint, $expect) + public function testGenerateAutoNodeName($hint, $expect): void { $result = NodeHelper::generateAutoNodeName($this->usedNames, $this->namespaces, 'a', $hint); if (true === $expect) { @@ -77,13 +79,13 @@ public function testGenerateAutoNodeName($hint, $expect) /** * @dataProvider invalidHints */ - public function testGenerateAutoNodeNameInvalid($hint) + public function testGenerateAutoNodeNameInvalid($hint): void { $this->expectException(RepositoryException::class); NodeHelper::generateAutoNodeName($this->usedNames, $this->namespaces, 'a', $hint); } - public function testIsSystemItem() + public function testIsSystemItem(): void { /** @var MockNode|MockObject $sys */ $sys = $this->createMock(MockNode::class); @@ -130,7 +132,7 @@ public function testIsSystemItem() $this->assertFalse(NodeHelper::isSystemItem($deep)); } - public function testCalculateOrderBeforeSwapLast() + public function testCalculateOrderBeforeSwapLast(): void { $old = ['one', 'two', 'three', 'four']; $new = ['one', 'two', 'four', 'three']; @@ -145,7 +147,7 @@ public function testCalculateOrderBeforeSwapLast() $this->assertEquals($expected, $reorders); } - public function testCalculateOrderBeforeSwap() + public function testCalculateOrderBeforeSwap(): void { $old = ['one', 'two', 'three', 'four']; $new = ['one', 'four', 'three', 'two']; @@ -160,7 +162,7 @@ public function testCalculateOrderBeforeSwap() $this->assertEquals($expected, $reorders); } - public function testCalculateOrderBeforeReverse() + public function testCalculateOrderBeforeReverse(): void { $old = ['one', 'two', 'three', 'four']; $new = ['four', 'three', 'two', 'one']; @@ -175,7 +177,7 @@ public function testCalculateOrderBeforeReverse() $this->assertEquals($expected, $reorders); } - public function testCalculateOrderBeforeDeleted() + public function testCalculateOrderBeforeDeleted(): void { $old = ['one', 'two', 'three', 'four']; $new = ['one', 'three', 'two']; @@ -193,7 +195,7 @@ public function testCalculateOrderBeforeDeleted() /** * @group benchmark */ - public function testBenchmarkOrderBeforeArray() + public function testBenchmarkOrderBeforeArray(): void { $nodes = []; diff --git a/tests/PHPCR/Tests/Util/PathHelperTest.php b/tests/PHPCR/Tests/Util/PathHelperTest.php index 0e0dd06c..8e03eeab 100644 --- a/tests/PHPCR/Tests/Util/PathHelperTest.php +++ b/tests/PHPCR/Tests/Util/PathHelperTest.php @@ -1,5 +1,7 @@ assertTrue(PathHelper::assertValidAbsolutePath($path, $destination)); } @@ -34,7 +36,7 @@ public function dataproviderValidAbsolutePaths() /** * @dataProvider dataproviderInvalidAbsolutePaths */ - public function testAssertInvalidAbsolutePath($path, $destination = false) + public function testAssertInvalidAbsolutePath($path, $destination = false): void { $this->expectException(RepositoryException::class); @@ -44,7 +46,7 @@ public function testAssertInvalidAbsolutePath($path, $destination = false) /** * @dataProvider dataproviderValidAbsolutePathsWithNamespaces */ - public function testAssertAbsolutePathNamespace($path) + public function testAssertAbsolutePathNamespace($path): void { $this->assertTrue(PathHelper::assertValidAbsolutePath($path, false, true, ['jcr', 'nt'])); } @@ -64,7 +66,7 @@ public function dataproviderValidAbsolutePathsWithNamespaces() ]; } - public function testAssertInvalidNamespaceAbsolutePath() + public function testAssertInvalidNamespaceAbsolutePath(): void { $this->expectException(NamespaceException::class); $this->expectExceptionMessage('invalidprefix and other-ns'); @@ -75,7 +77,7 @@ public function testAssertInvalidNamespaceAbsolutePath() /** * @dataProvider dataproviderInvalidAbsolutePaths */ - public function testAssertInvalidAbsolutePathNoThrow($path, $destination = false) + public function testAssertInvalidAbsolutePathNoThrow($path, $destination = false): void { $this->assertFalse(PathHelper::assertValidAbsolutePath($path, $destination, false)); } @@ -95,12 +97,12 @@ public function dataproviderInvalidAbsolutePaths() // assertValidLocalName tests - public function testAssertValidLocalName() + public function testAssertValidLocalName(): void { $this->assertTrue(PathHelper::assertValidLocalName('nodename')); } - public function testAssertValidLocalNameRootnode() + public function testAssertValidLocalNameRootnode(): void { $this->assertTrue(PathHelper::assertValidLocalName('')); } @@ -108,7 +110,7 @@ public function testAssertValidLocalNameRootnode() /** * @dataProvider dataproviderInvalidLocalNames */ - public function testAssertInvalidLocalName($name) + public function testAssertInvalidLocalName($name): void { $this->expectException(RepositoryException::class); @@ -130,7 +132,7 @@ public function dataproviderInvalidLocalNames() /** * @dataProvider dataproviderNormalizePath */ - public function testNormalizePath($inputPath, $outputPath) + public function testNormalizePath($inputPath, $outputPath): void { $this->assertSame($outputPath, PathHelper::normalizePath($inputPath)); } @@ -149,7 +151,7 @@ public static function dataproviderNormalizePath() /** * @dataProvider dataproviderNormalizePathInvalid */ - public function testNormalizePathInvalidThrow($input) + public function testNormalizePathInvalidThrow($input): void { $this->expectException(RepositoryException::class); @@ -159,7 +161,7 @@ public function testNormalizePathInvalidThrow($input) /** * @dataProvider dataproviderNormalizePathInvalid */ - public function testNormalizePathInvalidNoThrow($input) + public function testNormalizePathInvalidNoThrow($input): void { $this->assertFalse(PathHelper::normalizePath($input, true, false)); } @@ -198,7 +200,7 @@ public static function dataproviderAbsolutizePath(): array /** * @dataProvider dataproviderAbsolutizePathInvalid */ - public function testAbsolutizePathInvalidThrow($inputPath, $context, $target) + public function testAbsolutizePathInvalidThrow($inputPath, $context, $target): void { $this->expectException(RepositoryException::class); PathHelper::absolutizePath($inputPath, $context, $target); @@ -207,7 +209,7 @@ public function testAbsolutizePathInvalidThrow($inputPath, $context, $target) /** * @dataProvider dataproviderAbsolutizePathInvalid */ - public function testAbsolutizePathInvalidNoThrow($inputPath, $context, $target) + public function testAbsolutizePathInvalidNoThrow($inputPath, $context, $target): void { $this->assertFalse(PathHelper::absolutizePath($inputPath, $context, $target, false)); } @@ -227,7 +229,7 @@ public static function dataproviderAbsolutizePathInvalid() /** * @dataProvider dataproviderRelativizePath */ - public function testRelativizePath($inputPath, $context, $outputPath) + public function testRelativizePath($inputPath, $context, $outputPath): void { $this->assertSame($outputPath, PathHelper::relativizePath($inputPath, $context)); } @@ -243,7 +245,7 @@ public static function dataproviderRelativizePath() /** * @dataProvider dataproviderRelativizePathInvalid */ - public function testRelativizePathInvalidThrow($inputPath, $context) + public function testRelativizePathInvalidThrow($inputPath, $context): void { $this->expectException(RepositoryException::class); @@ -253,7 +255,7 @@ public function testRelativizePathInvalidThrow($inputPath, $context) /** * @dataProvider dataproviderRelativizePathInvalid */ - public function testRelativizePathInvalidNoThrow($inputPath, $context) + public function testRelativizePathInvalidNoThrow($inputPath, $context): void { $this->assertFalse(PathHelper::relativizePath($inputPath, $context, false)); } @@ -271,7 +273,7 @@ public static function dataproviderRelativizePathInvalid() /** * @dataProvider dataproviderParentPath */ - public function testGetParentPath($path, $parent) + public function testGetParentPath($path, $parent): void { $this->assertEquals($parent, PathHelper::getParentPath($path)); } @@ -291,7 +293,7 @@ public function dataproviderParentPath() /** * @dataProvider dataproviderGetNodeName */ - public function testGetNodeName($path, $expected = null) + public function testGetNodeName($path, $expected = null): void { $this->assertEquals($expected, PathHelper::getNodeName($path)); } @@ -308,7 +310,7 @@ public function dataproviderGetNodeName() /** * @dataProvider dataproviderGetLocalNodeName */ - public function testGetLocalNodeName($path, $expected = null) + public function testGetLocalNodeName($path, $expected = null): void { $this->assertEquals($expected, PathHelper::getLocalNodeName($path)); } @@ -324,7 +326,7 @@ public function dataproviderGetLocalNodeName() ]; } - public function testGetNodeNameMustBeAbsolute() + public function testGetNodeNameMustBeAbsolute(): void { $this->expectException(RepositoryException::class); $this->expectExceptionMessage('must be an absolute path'); @@ -337,7 +339,7 @@ public function testGetNodeNameMustBeAbsolute() /** * @dataProvider dataproviderPathDepth */ - public function testGetPathDepth($path, $depth) + public function testGetPathDepth($path, $depth): void { $this->assertEquals($depth, PathHelper::getPathDepth($path)); } diff --git a/tests/PHPCR/Tests/Util/QOM/BaseSqlGeneratorTest.php b/tests/PHPCR/Tests/Util/QOM/BaseSqlGeneratorTest.php index 0f11e57d..c89b55e3 100644 --- a/tests/PHPCR/Tests/Util/QOM/BaseSqlGeneratorTest.php +++ b/tests/PHPCR/Tests/Util/QOM/BaseSqlGeneratorTest.php @@ -1,5 +1,7 @@ generator->evalNot('foo = bar'); $this->assertSame('(NOT foo = bar)', $string); diff --git a/tests/PHPCR/Tests/Util/QOM/QueryBuilderTest.php b/tests/PHPCR/Tests/Util/QOM/QueryBuilderTest.php index c5466d01..40aff3cb 100644 --- a/tests/PHPCR/Tests/Util/QOM/QueryBuilderTest.php +++ b/tests/PHPCR/Tests/Util/QOM/QueryBuilderTest.php @@ -1,5 +1,7 @@ getMock(); } - public function testSetFirstResult() + public function testSetFirstResult(): void { $qb = new QueryBuilder($this->qf); $qb->setFirstResult(15); $this->assertEquals(15, $qb->getFirstResult()); } - public function testSetMaxResults() + public function testSetMaxResults(): void { $qb = new QueryBuilder($this->qf); $qb->setMaxResults(15); @@ -57,7 +59,7 @@ private function createDynamicOperandMock() return $dynamicOperand; } - public function testAddOrderBy() + public function testAddOrderBy(): void { $dynamicOperand = $this->createDynamicOperandMock(); @@ -68,7 +70,7 @@ public function testAddOrderBy() $orderings = $qb->getOrderings(); } - public function testAddOrderByLowercase() + public function testAddOrderByLowercase(): void { $dynamicOperand = $this->createDynamicOperandMock(); @@ -79,7 +81,7 @@ public function testAddOrderByLowercase() $orderings = $qb->getOrderings(); } - public function testAddOrderByInvalid() + public function testAddOrderByInvalid(): void { $this->expectException(\InvalidArgumentException::class); @@ -89,7 +91,7 @@ public function testAddOrderByInvalid() $qb->addOrderBy($dynamicOperand, 'FOO'); } - public function testOrderBy() + public function testOrderBy(): void { $dynamicOperand = $this->createDynamicOperandMock(); @@ -99,7 +101,7 @@ public function testOrderBy() $this->assertCount(1, $qb->getOrderings()); } - public function testOrderAscending() + public function testOrderAscending(): void { $dynamicOperand = $this->createDynamicOperandMock(); @@ -111,7 +113,7 @@ public function testOrderAscending() $qb->addOrderBy($dynamicOperand, 'ASC'); } - public function testOrderDescending() + public function testOrderDescending(): void { $dynamicOperand = $this->createDynamicOperandMock(); @@ -123,7 +125,7 @@ public function testOrderDescending() $qb->addOrderBy($dynamicOperand, 'DESC'); } - public function testOrderAscendingIsDefault() + public function testOrderAscendingIsDefault(): void { $dynamicOperand = $this->createDynamicOperandMock(); @@ -149,7 +151,7 @@ private function createConstraintMock() return $constraint; } - public function testWhere() + public function testWhere(): void { $constraint = $this->createConstraintMock(); @@ -158,7 +160,7 @@ public function testWhere() $this->assertEquals($constraint, $qb->getConstraint()); } - public function testAndWhere() + public function testAndWhere(): void { $this->qf->expects($this->once()) ->method('andConstraint'); @@ -171,7 +173,7 @@ public function testAndWhere() $qb->andWhere($constraint2); } - public function testOrWhere() + public function testOrWhere(): void { $this->qf->expects($this->once()) ->method('orConstraint'); @@ -184,7 +186,7 @@ public function testOrWhere() $qb->orWhere($constraint2); } - public function testSelect() + public function testSelect(): void { $qb = new QueryBuilder($this->qf); $this->assertCount(0, $qb->getColumns()); @@ -194,7 +196,7 @@ public function testSelect() $this->assertCount(1, $qb->getColumns()); } - public function testAddSelect() + public function testAddSelect(): void { $qb = new QueryBuilder($this->qf); $this->assertCount(0, $qb->getColumns()); @@ -218,7 +220,7 @@ private function createSourceMock() return $source; } - public function testFrom() + public function testFrom(): void { $source = $this->createSourceMock(); @@ -241,7 +243,7 @@ private function createSameNodeJoinConditionMock() return $joinCondition; } - public function testInvalidJoin() + public function testInvalidJoin(): void { $this->expectException(\RuntimeException::class); @@ -252,7 +254,7 @@ public function testInvalidJoin() $qb->join($source, $joinCondition); } - public function testJoin() + public function testJoin(): void { $source1 = $this->createSourceMock(); $source2 = $this->createSourceMock(); @@ -272,7 +274,7 @@ public function testJoin() $qb->join($source2, $joinCondition); } - public function testRightJoin() + public function testRightJoin(): void { $source1 = $this->createSourceMock(); $source2 = $this->createSourceMock(); @@ -292,7 +294,7 @@ public function testRightJoin() $qb->rightJoin($source2, $joinCondition); } - public function testLeftJoin() + public function testLeftJoin(): void { $source1 = $this->createSourceMock(); $source2 = $this->createSourceMock(); @@ -312,7 +314,7 @@ public function testLeftJoin() $qb->leftJoin($source2, $joinCondition); } - public function testGetQuery() + public function testGetQuery(): void { $source = $this->createSourceMock(); $constraint = $this->createConstraintMock(); @@ -342,7 +344,7 @@ private function createQueryMock() return $query; } - public function testGetQueryWithOffsetAndLimit() + public function testGetQueryWithOffsetAndLimit(): void { $source = $this->createSourceMock(); $constraint = $this->createConstraintMock(); @@ -367,7 +369,7 @@ public function testGetQueryWithOffsetAndLimit() $qb->getQuery(); } - public function testSetParameter() + public function testSetParameter(): void { $key = 'key'; $value = 'value'; @@ -378,7 +380,7 @@ public function testSetParameter() $this->assertEquals($value, $qb->getParameter($key)); } - public function testSetParameters() + public function testSetParameters(): void { $key1 = 'key1'; $value1 = 'value1'; @@ -393,7 +395,7 @@ public function testSetParameters() $this->assertCount(2, $qb->getParameters()); } - public function testExecute() + public function testExecute(): void { $source = $this->createSourceMock(); $constraint = $this->createConstraintMock(); @@ -413,7 +415,8 @@ public function testExecute() ->willReturn($query); $qb = new QueryBuilder($this->qf); - $this->assertSame($result, + $this->assertSame( + $result, $qb->from($source) ->where($constraint) ->setFirstResult(10) diff --git a/tests/PHPCR/Tests/Util/QOM/Sql1GeneratorTest.php b/tests/PHPCR/Tests/Util/QOM/Sql1GeneratorTest.php index 4bc2184e..8798c678 100644 --- a/tests/PHPCR/Tests/Util/QOM/Sql1GeneratorTest.php +++ b/tests/PHPCR/Tests/Util/QOM/Sql1GeneratorTest.php @@ -1,5 +1,7 @@ generator = new Sql1Generator(new ValueConverter()); } - public function testLiteral() + public function testLiteral(): void { $literal = $this->generator->evalLiteral('Foobar'); $this->assertEquals("'Foobar'", $literal); } - public function testDateTimeLiteral() + public function testDateTimeLiteral(): void { $literal = $this->generator->evalLiteral(new \DateTime('2011-12-23T00:00:00.000+00:00')); $this->assertEquals("TIMESTAMP '2011-12-23T00:00:00.000+00:00'", $literal); } - public function testBoolLiteral() + public function testBoolLiteral(): void { $literal = $this->generator->evalLiteral(true); $this->assertEquals("'true'", $literal); } - public function testLongLiteral() + public function testLongLiteral(): void { $literal = $this->generator->evalLiteral(11); $this->assertSame('11', $literal); } - public function testDoubleLiteral() + public function testDoubleLiteral(): void { $literal = $this->generator->evalLiteral(11.0); $this->assertSame('11.0', $literal); } - public function testChildNode() + public function testChildNode(): void { $literal = $this->generator->evalChildNode('/'); $this->assertSame("jcr:path LIKE '/%' AND NOT jcr:path LIKE '/%/%'", $literal); @@ -57,7 +59,7 @@ public function testChildNode() $this->assertSame("jcr:path LIKE '/foo[%]/bar[%]/baz[%]/%' AND NOT jcr:path LIKE '/foo[%]/bar[%]/baz[%]/%/%'", $literal); } - public function testDescendantNode() + public function testDescendantNode(): void { $literal = $this->generator->evalDescendantNode('/'); $this->assertSame("jcr:path LIKE '/%'", $literal); @@ -66,13 +68,13 @@ public function testDescendantNode() $this->assertSame("jcr:path LIKE '/foo[%]/bar[%]/baz[%]/%'", $literal); } - public function testPopertyExistence() + public function testPopertyExistence(): void { $literal = $this->generator->evalPropertyExistence(null, 'foo'); $this->assertSame('foo IS NOT NULL', $literal); } - public function testFullTextSearch() + public function testFullTextSearch(): void { $literal = $this->generator->evalFullTextSearch('', "'foo'"); $this->assertSame("CONTAINS(*, 'foo')", $literal); @@ -80,7 +82,7 @@ public function testFullTextSearch() $this->assertSame("CONTAINS(bar, 'foo')", $literal); } - public function testColumns() + public function testColumns(): void { $literal = $this->generator->evalColumns([]); $this->assertSame('s', $literal); @@ -88,7 +90,7 @@ public function testColumns() $this->assertSame('bar, foo', $literal); } - public function testPropertyValue() + public function testPropertyValue(): void { $literal = $this->generator->evalPropertyValue('foo'); $this->assertSame('foo', $literal); diff --git a/tests/PHPCR/Tests/Util/QOM/Sql2GeneratorTest.php b/tests/PHPCR/Tests/Util/QOM/Sql2GeneratorTest.php index 5517fb3f..f7d8c761 100644 --- a/tests/PHPCR/Tests/Util/QOM/Sql2GeneratorTest.php +++ b/tests/PHPCR/Tests/Util/QOM/Sql2GeneratorTest.php @@ -1,5 +1,7 @@ generator = new Sql2Generator(new ValueConverter()); } - public function testLiteral() + public function testLiteral(): void { $literal = $this->generator->evalLiteral('Foobar'); $this->assertEquals("'Foobar'", $literal); } - public function testDateTimeLiteral() + public function testDateTimeLiteral(): void { $literal = $this->generator->evalLiteral(new \DateTime('2011-12-23T00:00:00.000+00:00')); $this->assertEquals("CAST('2011-12-23T00:00:00.000+00:00' AS DATE)", $literal); } - public function testBoolLiteral() + public function testBoolLiteral(): void { $literal = $this->generator->evalLiteral(true); $this->assertEquals("CAST('true' AS BOOLEAN)", $literal); } - public function testLongLiteral() + public function testLongLiteral(): void { $literal = $this->generator->evalLiteral(11); $this->assertEquals("CAST('11' AS LONG)", $literal); } - public function testDoubleLiteral() + public function testDoubleLiteral(): void { $literal = $this->generator->evalLiteral(11.0); $this->assertEquals("CAST('11' AS DOUBLE)", $literal); } - public function testChildNode() + public function testChildNode(): void { $literal = $this->generator->evalChildNode('/foo/bar/baz'); $this->assertSame('ISCHILDNODE(/foo/bar/baz)', $literal); } - public function testDescendantNode() + public function testDescendantNode(): void { $literal = $this->generator->evalDescendantNode('/foo/bar/baz'); $this->assertSame('ISDESCENDANTNODE(/foo/bar/baz)', $literal); } - public function testPopertyExistence() + public function testPopertyExistence(): void { $literal = $this->generator->evalPropertyExistence(null, 'foo'); $this->assertSame('[foo] IS NOT NULL', $literal); } - public function testFullTextSearch() + public function testFullTextSearch(): void { $literal = $this->generator->evalFullTextSearch('data', "'foo'"); $this->assertSame("CONTAINS(data.*, 'foo')", $literal); @@ -73,7 +75,7 @@ public function testFullTextSearch() $this->assertSame("CONTAINS(data.[bar], 'foo')", $literal); } - public function testColumns() + public function testColumns(): void { $literal = $this->generator->evalColumns([]); $this->assertSame('*', $literal); @@ -81,7 +83,7 @@ public function testColumns() $this->assertSame('bar, foo', $literal); } - public function testPropertyValue() + public function testPropertyValue(): void { $literal = $this->generator->evalPropertyValue('foo'); $this->assertSame('[foo]', $literal); diff --git a/tests/PHPCR/Tests/Util/QOM/Sql2ScannerTest.php b/tests/PHPCR/Tests/Util/QOM/Sql2ScannerTest.php index b4627bbb..9b6ea95e 100644 --- a/tests/PHPCR/Tests/Util/QOM/Sql2ScannerTest.php +++ b/tests/PHPCR/Tests/Util/QOM/Sql2ScannerTest.php @@ -1,5 +1,7 @@ ['SELECT page.* FROM [nt:unstructured] AS page WHERE name ="Hello world"'], @@ -63,11 +65,11 @@ public function dataTestStringTokenization(): array ]; } - public function testEscapingStrings() + public function testEscapingStrings(): void { $sql = <<expectTokensFromScanner($scanner, $expected); } - public function testSQLEscapedStrings() + public function testSQLEscapedStrings(): void { $sql = "WHERE page.name = 'Hello, it''s me.'"; @@ -106,7 +108,7 @@ public function testSQLEscapedStrings() $this->expectTokensFromScanner($scanner, $expected); } - public function testSQLEscapedStrings2() + public function testSQLEscapedStrings2(): void { $sql = "WHERE page.name = 'Hello, it''' AND"; @@ -124,7 +126,7 @@ public function testSQLEscapedStrings2() $this->expectTokensFromScanner($scanner, $expected); } - public function testSquareBrackets() + public function testSquareBrackets(): void { $sql = 'WHERE ISSAMENODE(file, ["/home node"])'; @@ -142,7 +144,7 @@ public function testSquareBrackets() $this->expectTokensFromScanner($scanner, $expected); } - public function testSquareBracketsWithoutQuotes() + public function testSquareBracketsWithoutQuotes(): void { $sql = 'WHERE ISSAMENODE(file, [/home node])'; @@ -160,7 +162,7 @@ public function testSquareBracketsWithoutQuotes() $this->expectTokensFromScanner($scanner, $expected); } - public function testTokenizingWithMissingSpaces() + public function testTokenizingWithMissingSpaces(): void { $sql = 'SELECT * AS"all"'; @@ -175,7 +177,7 @@ public function testTokenizingWithMissingSpaces() $this->expectTokensFromScanner($scanner, $expected); } - public function testThrowingErrorOnUnclosedString() + public function testThrowingErrorOnUnclosedString(): void { $this->expectException(InvalidQueryException::class); new Sql2Scanner('SELECT page.* FROM [nt:unstructured] AS page WHERE name ="Hello '); @@ -187,7 +189,7 @@ public function testThrowingErrorOnUnclosedString() * * @param array $expected */ - private function expectTokensFromScanner(Sql2Scanner $scanner, array $expected) + private function expectTokensFromScanner(Sql2Scanner $scanner, array $expected): void { $actualTokens = []; while ($token = $scanner->fetchNextToken()) { diff --git a/tests/PHPCR/Tests/Util/QOM/Sql2ToQomQueryConverterTest.php b/tests/PHPCR/Tests/Util/QOM/Sql2ToQomQueryConverterTest.php index 393e3e6b..d52beeed 100644 --- a/tests/PHPCR/Tests/Util/QOM/Sql2ToQomQueryConverterTest.php +++ b/tests/PHPCR/Tests/Util/QOM/Sql2ToQomQueryConverterTest.php @@ -1,5 +1,7 @@ converter = new Sql2ToQomQueryConverter($this->qomFactory, $this->valueConverter); } - public function testInvalid() + public function testInvalid(): void { $this->expectException(InvalidQueryException::class); $this->expectExceptionMessage('Error parsing query'); diff --git a/tests/PHPCR/Tests/Util/TraversingItemVisitorTest.php b/tests/PHPCR/Tests/Util/TraversingItemVisitorTest.php index e2330267..abc3be63 100644 --- a/tests/PHPCR/Tests/Util/TraversingItemVisitorTest.php +++ b/tests/PHPCR/Tests/Util/TraversingItemVisitorTest.php @@ -1,12 +1,14 @@ markTestSkipped('TODO: implement tests for breath and depth first and with and without limit'); } diff --git a/tests/PHPCR/Tests/Util/UUIDHelperTest.php b/tests/PHPCR/Tests/Util/UUIDHelperTest.php index 3e20505e..f6efc33d 100644 --- a/tests/PHPCR/Tests/Util/UUIDHelperTest.php +++ b/tests/PHPCR/Tests/Util/UUIDHelperTest.php @@ -1,5 +1,7 @@ assertEquals(1, preg_match('/^[[:xdigit:]]{8}-[[:xdigit:]]{4}-[[:xdigit:]]{4}-[[:xdigit:]]{4}-[[:xdigit:]]{12}$/', $id)); } - public function testIsUUID() + public function testIsUUID(): void { $this->assertTrue(UUIDHelper::isUUID('550e8400-e29b-41d4-a716-446655440000')); $this->assertTrue(UUIDHelper::isUUID('00000000-0000-0000-C000-000000000046')); diff --git a/tests/PHPCR/Tests/Util/ValueConverterTest.php b/tests/PHPCR/Tests/Util/ValueConverterTest.php index ce74b05f..4b871944 100644 --- a/tests/PHPCR/Tests/Util/ValueConverterTest.php +++ b/tests/PHPCR/Tests/Util/ValueConverterTest.php @@ -1,5 +1,7 @@ Date: Tue, 28 Nov 2023 12:00:13 +0100 Subject: [PATCH 06/13] more phpdoc cleanup --- src/PHPCR/Util/CND/Parser/AbstractParser.php | 5 +- src/PHPCR/Util/CND/Parser/CndParser.php | 43 ++++++++-------- src/PHPCR/Util/CND/Scanner/GenericScanner.php | 25 +--------- src/PHPCR/Util/CND/Scanner/GenericToken.php | 2 +- src/PHPCR/Util/CND/Scanner/Token.php | 38 ++++---------- src/PHPCR/Util/CND/Writer/CndWriter.php | 14 +++--- .../Console/Command/NodeRemoveCommand.php | 2 - .../Util/Console/Command/NodeTouchCommand.php | 2 +- src/PHPCR/Util/Console/Helper/PhpcrHelper.php | 19 +------ .../TreeDumper/ConsoleDumperItemVisitor.php | 14 ++---- .../TreeDumper/ConsoleDumperNodeVisitor.php | 9 +--- .../ConsoleDumperPropertyVisitor.php | 17 ++----- src/PHPCR/Util/NodeHelper.php | 11 ++-- src/PHPCR/Util/PathHelper.php | 19 +++---- .../Util/QOM/BaseQomToSqlQueryConverter.php | 3 -- src/PHPCR/Util/QOM/QueryBuilder.php | 50 ++++++------------- src/PHPCR/Util/QOM/Sql1Generator.php | 4 +- src/PHPCR/Util/QOM/Sql2Scanner.php | 3 -- .../Util/QOM/Sql2ToQomQueryConverter.php | 47 ++++++----------- src/PHPCR/Util/TraversingItemVisitor.php | 4 -- src/PHPCR/Util/TreeWalker.php | 20 +------- src/PHPCR/Util/UUIDHelper.php | 2 - .../Util/CND/Scanner/GenericScannerTest.php | 10 +++- .../Tests/Util/CND/Scanner/TokenTest.php | 4 +- 24 files changed, 106 insertions(+), 261 deletions(-) diff --git a/src/PHPCR/Util/CND/Parser/AbstractParser.php b/src/PHPCR/Util/CND/Parser/AbstractParser.php index d2edb48e..1dfa587c 100644 --- a/src/PHPCR/Util/CND/Parser/AbstractParser.php +++ b/src/PHPCR/Util/CND/Parser/AbstractParser.php @@ -23,9 +23,6 @@ */ abstract class AbstractParser { - /** - * The token queue. - */ protected TokenQueue $tokenQueue; /** @@ -105,7 +102,7 @@ protected function expectToken(int $type, string $data = null): Token * @param int $type The expected token type * @param string|null $data The expected token data or null */ - protected function checkAndExpectToken(int $type, string $data = null): bool|Token + protected function checkAndExpectToken(int $type, string $data = null): false|Token { if ($this->checkToken($type, $data)) { $token = $this->tokenQueue->peek(); diff --git a/src/PHPCR/Util/CND/Parser/CndParser.php b/src/PHPCR/Util/CND/Parser/CndParser.php index bf789ee9..58a76d8c 100644 --- a/src/PHPCR/Util/CND/Parser/CndParser.php +++ b/src/PHPCR/Util/CND/Parser/CndParser.php @@ -68,12 +68,12 @@ final class CndParser extends AbstractParser /** * @var string[] */ - protected array $namespaces = []; + private array $namespaces = []; /** * @var string[] */ - protected array $nodeTypes = []; + private array $nodeTypes = []; public function __construct(NodeTypeManagerInterface $ntm) { @@ -142,7 +142,7 @@ private function parse(ReaderInterface $reader): array * Prefix ::= String * Uri ::= String */ - protected function parseNamespaceMapping(): void + private function parseNamespaceMapping(): void { $this->expectToken(Token::TK_SYMBOL, '<'); $prefix = $this->parseCndString(); @@ -162,7 +162,7 @@ protected function parseNamespaceMapping(): void * [NodeTypeAttribute {NodeTypeAttribute}] * {PropertyDef | ChildNodeDef} */ - protected function parseNodeType(): void + private function parseNodeType(): void { $nodeType = $this->ntm->createNodeTypeTemplate(); $this->parseNodeTypeName($nodeType); @@ -183,7 +183,7 @@ protected function parseNodeType(): void * * NodeTypeName ::= '[' String ']' */ - protected function parseNodeTypeName(NodeTypeTemplateInterface $nodeType): void + private function parseNodeTypeName(NodeTypeTemplateInterface $nodeType): void { $this->expectToken(Token::TK_SYMBOL, '['); $name = $this->parseCndString(); @@ -200,7 +200,7 @@ protected function parseNodeTypeName(NodeTypeTemplateInterface $nodeType): void * * Supertypes ::= '>' (StringList | '?') */ - protected function parseSupertypes(NodeTypeTemplateInterface $nodeType): void + private function parseSupertypes(NodeTypeTemplateInterface $nodeType): void { $this->expectToken(Token::TK_SYMBOL, '>'); @@ -243,7 +243,7 @@ protected function parseSupertypes(NodeTypeTemplateInterface $nodeType): void * Query ::= ('noquery' | 'nq') | ('query' | 'q' ) * PrimaryItem ::= ('primaryitem'| '!')(String | '?') */ - protected function parseNodeTypeAttributes(NodeTypeTemplateInterface $nodeType): void + private function parseNodeTypeAttributes(NodeTypeTemplateInterface $nodeType): void { while (true) { if ($this->checkTokenIn(Token::TK_IDENTIFIER, $this->ORDERABLE)) { @@ -284,7 +284,7 @@ protected function parseNodeTypeAttributes(NodeTypeTemplateInterface $nodeType): * * {PropertyDef | ChildNodeDef} */ - protected function parseChildrenAndAttributes(NodeTypeTemplateInterface $nodeType): void + private function parseChildrenAndAttributes(NodeTypeTemplateInterface $nodeType): void { while (true) { if ($this->checkToken(Token::TK_SYMBOL, '-')) { @@ -310,7 +310,7 @@ protected function parseChildrenAndAttributes(NodeTypeTemplateInterface $nodeTyp * [ValueConstraints] * PropertyName ::= '-' String */ - protected function parsePropDef(NodeTypeTemplateInterface $nodeType): void + private function parsePropDef(NodeTypeTemplateInterface $nodeType): void { $this->expectToken(Token::TK_SYMBOL, '-'); @@ -364,7 +364,7 @@ protected function parsePropDef(NodeTypeTemplateInterface $nodeType): void * 'DECIMAL' | 'URI' | 'UNDEFINED' | '*' | * '?') ')' */ - protected function parsePropertyType(PropertyDefinitionTemplateInterface $property): void + private function parsePropertyType(PropertyDefinitionTemplateInterface $property): void { $types = ['STRING', 'BINARY', 'LONG', 'DOUBLE', 'BOOLEAN', 'DATE', 'NAME', 'PATH', 'REFERENCE', 'WEAKREFERENCE', 'DECIMAL', 'URI', 'UNDEFINED', '*', '?', ]; @@ -388,7 +388,7 @@ protected function parsePropertyType(PropertyDefinitionTemplateInterface $proper * * DefaultValues ::= '=' (StringList | '?') */ - protected function parseDefaultValue(PropertyDefinitionTemplateInterface $property): void + private function parseDefaultValue(PropertyDefinitionTemplateInterface $property): void { if ($this->checkAndExpectToken(Token::TK_SYMBOL, '?')) { $list = ['?']; @@ -406,7 +406,7 @@ protected function parseDefaultValue(PropertyDefinitionTemplateInterface $proper * * ValueConstraints ::= '<' (StringList | '?') */ - protected function parseValueConstraints(PropertyDefinitionTemplateInterface $property): void + private function parseValueConstraints(PropertyDefinitionTemplateInterface $property): void { $this->expectToken(Token::TK_SYMBOL, '<'); @@ -473,7 +473,7 @@ protected function parseValueConstraints(PropertyDefinitionTemplateInterface $pr * NoFullText ::= ('nofulltext' | 'nof') ['?'] * NoQueryOrder ::= ('noqueryorder' | 'nqord') ['?'] */ - protected function parsePropertyAttributes(NodeTypeTemplateInterface $parentType, PropertyDefinitionTemplateInterface $property): void + private function parsePropertyAttributes(NodeTypeTemplateInterface $parentType, PropertyDefinitionTemplateInterface $property): void { $opvSeen = false; while (true) { @@ -527,7 +527,7 @@ protected function parsePropertyAttributes(NodeTypeTemplateInterface $parentType * RequiredTypes ::= '(' (StringList | '?') ')' * DefaultType ::= '=' (String | '?') */ - protected function parseChildNodeDef(NodeTypeTemplateInterface $nodeType): void + private function parseChildNodeDef(NodeTypeTemplateInterface $nodeType): void { $this->expectToken(Token::TK_SYMBOL, '+'); $childType = $this->ntm->createNodeDefinitionTemplate(); @@ -593,7 +593,7 @@ protected function parseChildNodeDef(NodeTypeTemplateInterface $nodeType): void * 'IGNORE' | 'ABORT' | ('OPV' '?') * Sns ::= ('sns' | '*') ['?'] */ - protected function parseChildNodeAttributes( + private function parseChildNodeAttributes( NodeTypeTemplateInterface $parentType, NodeDefinitionTemplateInterface $childType ): void { @@ -627,7 +627,7 @@ protected function parseChildNodeAttributes( * * @return string[] */ - protected function parseCndStringList(): array + private function parseCndStringList(): array { $strings = []; @@ -658,7 +658,7 @@ protected function parseCndStringList(): array * * TODO: check \n, \r, \t are valid in CND strings! */ - protected function parseCndString(): string + private function parseCndString(): string { $string = ''; $lastType = null; @@ -714,9 +714,9 @@ protected function parseCndString(): string * (('''Operator {','Operator}''') | '?') * Operator ::= '=' | '<>' | '<' | '<=' | '>' | '>=' | 'LIKE' * - * @return array + * @return array */ - protected function parseQueryOpsAttribute() + private function parseQueryOpsAttribute(): array { if ($this->checkAndExpectToken(Token::TK_SYMBOL, '?')) { // this denotes a variant, whatever that is @@ -732,10 +732,7 @@ protected function parseQueryOpsAttribute() return $ops; } - /** - * Parse a query operator. - */ - protected function parseQueryOperator(): bool|string + private function parseQueryOperator(): bool|string { $token = $this->tokenQueue->peek(); $data = $token->getData(); diff --git a/src/PHPCR/Util/CND/Scanner/GenericScanner.php b/src/PHPCR/Util/CND/Scanner/GenericScanner.php index 1396b4de..d03bb90c 100644 --- a/src/PHPCR/Util/CND/Scanner/GenericScanner.php +++ b/src/PHPCR/Util/CND/Scanner/GenericScanner.php @@ -93,11 +93,6 @@ protected function consumeNewLine(ReaderInterface $reader): bool return false; } - /** - * Detect and consume strings. - * - * @throws ScannerException - */ protected function consumeString(ReaderInterface $reader): bool { $curDelimiter = $reader->currentChar(); @@ -121,9 +116,6 @@ protected function consumeString(ReaderInterface $reader): bool return false; } - /** - * Detect and consume comments. - */ protected function consumeComments(ReaderInterface $reader): bool { if ($this->consumeBlockComments($reader)) { @@ -133,11 +125,6 @@ protected function consumeComments(ReaderInterface $reader): bool return $this->consumeLineComments($reader); } - /** - * Detect and consume block comments. - * - * @throws ScannerException - */ protected function consumeBlockComments(ReaderInterface $reader): bool { $nextChar = $reader->currentChar(); @@ -184,15 +171,13 @@ protected function consumeBlockComments(ReaderInterface $reader): bool return false; } - /** - * Detect and consume line comments. - */ protected function consumeLineComments(ReaderInterface $reader): bool { $nextChar = $reader->currentChar(); foreach ($this->context->getLineCommentDelimiters() as $delimiter) { if ($delimiter && $nextChar === $delimiter[0]) { - for ($i = 1; $i <= strlen($delimiter); ++$i) { + $delimiterLength = strlen($delimiter); + for ($i = 1; $i <= $delimiterLength; ++$i) { $reader->forward(); } @@ -218,9 +203,6 @@ protected function consumeLineComments(ReaderInterface $reader): bool return false; } - /** - * Detect and consume identifiers. - */ protected function consumeIdentifiers(ReaderInterface $reader): bool { $nextChar = $reader->currentChar(); @@ -239,9 +221,6 @@ protected function consumeIdentifiers(ReaderInterface $reader): bool return false; } - /** - * Detect and consume symbols. - */ protected function consumeSymbols(ReaderInterface $reader): bool { $found = false; diff --git a/src/PHPCR/Util/CND/Scanner/GenericToken.php b/src/PHPCR/Util/CND/Scanner/GenericToken.php index 9c52e98c..9f88af81 100644 --- a/src/PHPCR/Util/CND/Scanner/GenericToken.php +++ b/src/PHPCR/Util/CND/Scanner/GenericToken.php @@ -36,6 +36,6 @@ public static function getTypeName(int $type): string public function __toString() { - return sprintf("TOKEN(%s, '%s', %s, %s)", self::getTypeName($this->getType()), trim($this->data), $this->line, $this->row); + return sprintf("TOKEN(%s, '%s', %s, %s)", self::getTypeName($this->getType()), trim($this->getData()), $this->getLine(), $this->getRow()); } } diff --git a/src/PHPCR/Util/CND/Scanner/Token.php b/src/PHPCR/Util/CND/Scanner/Token.php index 112e59e0..10813282 100644 --- a/src/PHPCR/Util/CND/Scanner/Token.php +++ b/src/PHPCR/Util/CND/Scanner/Token.php @@ -15,35 +15,15 @@ */ class Token { - /** - * The type of token. - */ - public int $type; - - /** - * The token raw data. - */ - public string $data; - - /** - * The line where the token appears. - */ - protected int $line; - - /** - * The column where the token appears. - */ - protected int $row; - - /** - * Constructor. - */ - public function __construct(int $type = 0, string $data = '', int $line = 0, int $row = 0) - { - $this->type = $type; - $this->data = $data; - $this->line = $line; - $this->row = $row; + public function __construct( + private int $type = 0, + /** + * The token raw data. + */ + private string $data = '', + private int $line = 0, + private int $row = 0 + ) { } public function getData(): string diff --git a/src/PHPCR/Util/CND/Writer/CndWriter.php b/src/PHPCR/Util/CND/Writer/CndWriter.php index 33c0a89d..20f8d5e0 100644 --- a/src/PHPCR/Util/CND/Writer/CndWriter.php +++ b/src/PHPCR/Util/CND/Writer/CndWriter.php @@ -27,14 +27,14 @@ */ class CndWriter { - private NamespaceRegistryInterface $ns; - - /** @var array hashmap of prefix => namespace uri */ + /** + * @var array hashmap of prefix => namespace uri + */ private array $namespaces = []; - public function __construct(NamespaceRegistryInterface $ns) - { - $this->ns = $ns; + public function __construct( + private NamespaceRegistryInterface $ns + ) { } /** @@ -232,7 +232,7 @@ private function writeChildren(?array $children): string if ($child->isProtected()) { $attributes .= 'protected '; } - if (OnParentVersionAction::COPY != $child->getOnParentVersion()) { + if (OnParentVersionAction::COPY !== $child->getOnParentVersion()) { $attributes .= OnParentVersionAction::nameFromValue($child->getOnParentVersion()).' '; } if ($child->allowsSameNameSiblings()) { diff --git a/src/PHPCR/Util/Console/Command/NodeRemoveCommand.php b/src/PHPCR/Util/Console/Command/NodeRemoveCommand.php index ec987051..362df924 100644 --- a/src/PHPCR/Util/Console/Command/NodeRemoveCommand.php +++ b/src/PHPCR/Util/Console/Command/NodeRemoveCommand.php @@ -4,7 +4,6 @@ namespace PHPCR\Util\Console\Command; -use PHPCR\NodeInterface; use Symfony\Component\Console\Exception\InvalidArgumentException as CliInvalidArgumentException; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; @@ -97,7 +96,6 @@ protected function execute(InputInterface $input, OutputInterface $output): int if ($onlyChildren) { $baseNode = $session->getNode($path, 0); - /** @var NodeInterface $childNode */ foreach ($baseNode->getNodes() as $childNode) { $childNodePath = $childNode->getPath(); $childNode->remove(); diff --git a/src/PHPCR/Util/Console/Command/NodeTouchCommand.php b/src/PHPCR/Util/Console/Command/NodeTouchCommand.php index 3ff77f0a..7d554afd 100644 --- a/src/PHPCR/Util/Console/Command/NodeTouchCommand.php +++ b/src/PHPCR/Util/Console/Command/NodeTouchCommand.php @@ -15,7 +15,7 @@ /** * Command to create a PHPCR node of a specified type from - * the command line.. + * the command line. * * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License diff --git a/src/PHPCR/Util/Console/Helper/PhpcrHelper.php b/src/PHPCR/Util/Console/Helper/PhpcrHelper.php index 3af5473f..f447df5b 100644 --- a/src/PHPCR/Util/Console/Helper/PhpcrHelper.php +++ b/src/PHPCR/Util/Console/Helper/PhpcrHelper.php @@ -5,7 +5,6 @@ namespace PHPCR\Util\Console\Helper; use PHPCR\NodeInterface; -use PHPCR\PropertyInterface; use PHPCR\Query\QueryInterface; use PHPCR\SessionInterface; use Symfony\Component\Console\Helper\Helper; @@ -19,24 +18,13 @@ */ class PhpcrHelper extends Helper { - /** - * The session bound to this helper. - */ - protected SessionInterface $session; + private SessionInterface $session; - /** - * Constructor. - * - * @param SessionInterface $session the session to use in commands - */ public function __construct(SessionInterface $session) { $this->session = $session; } - /** - * Get the session. - */ public function getSession(): SessionInterface { return $this->session; @@ -124,7 +112,6 @@ public function processNode(OutputInterface $output, NodeInterface $node, array if ($operations['dump']) { $output->writeln('Node dump: '); - /** @var PropertyInterface $property */ foreach ($node->getProperties() as $property) { $value = $property->getValue(); if (!is_string($value)) { @@ -159,11 +146,9 @@ public function createQuery(string $language, string $sql): QueryInterface /** * Check if this is a supported query language. * - * @param string $language language name - * * @throws \Exception if the language is not supported */ - protected function validateQueryLanguage(string $language) + protected function validateQueryLanguage(string $language): string { $qm = $this->getSession()->getWorkspace()->getQueryManager(); $langs = $qm->getSupportedQueryLanguages(); diff --git a/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperItemVisitor.php b/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperItemVisitor.php index d9b1d867..ecdd293b 100644 --- a/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperItemVisitor.php +++ b/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperItemVisitor.php @@ -14,22 +14,14 @@ */ abstract class ConsoleDumperItemVisitor implements ItemVisitorInterface { - /** - * Target for printing information. - */ - protected OutputInterface $output; - /** * Current depth in the tree. */ protected int $level = 0; - /** - * Instantiate the console dumper visitor. - */ - public function __construct(OutputInterface $output) - { - $this->output = $output; + public function __construct( + protected OutputInterface $output + ) { } /** diff --git a/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperNodeVisitor.php b/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperNodeVisitor.php index b788646e..e1f81530 100644 --- a/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperNodeVisitor.php +++ b/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperNodeVisitor.php @@ -26,9 +26,7 @@ class ConsoleDumperNodeVisitor extends ConsoleDumperItemVisitor protected bool $showFullPath = false; /** - * Instantiate the console dumper visitor. - * - * @param bool $identifiers whether to output the node UUID + * @param bool $identifiers whether to output the node UUIDs */ public function __construct(OutputInterface $output, bool $identifiers = false) { @@ -36,9 +34,6 @@ public function __construct(OutputInterface $output, bool $identifiers = false) $this->identifiers = $identifiers; } - /** - * If to show the full path or not. - */ public function setShowFullPath(bool $showFullPath): void { $this->showFullPath = $showFullPath; @@ -47,8 +42,6 @@ public function setShowFullPath(bool $showFullPath): void /** * Print information about the visited node. * - * @param ItemInterface $item the node to visit - * * @throws \Exception */ public function visit(ItemInterface $item): void diff --git a/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperPropertyVisitor.php b/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperPropertyVisitor.php index 97f696d3..cd07faaf 100644 --- a/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperPropertyVisitor.php +++ b/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperPropertyVisitor.php @@ -18,19 +18,12 @@ class ConsoleDumperPropertyVisitor extends ConsoleDumperItemVisitor { /** * Limit to cap lines at to avoid garbled output on long property values. - * - * @var int */ - protected mixed $maxLineLength; + protected int $maxLineLength; - /** - * @var string - */ - private mixed $refFormat; + private string $refFormat; /** - * Instantiate property visitor. - * * @param array $options */ public function __construct(OutputInterface $output, array $options = []) @@ -42,15 +35,13 @@ public function __construct(OutputInterface $output, array $options = []) parent::__construct($output); - $this->maxLineLength = $options['max_line_length']; - $this->refFormat = $options['ref_format']; + $this->maxLineLength = (int) $options['max_line_length']; + $this->refFormat = (string) $options['ref_format']; } /** * Print information about this property. * - * @param ItemInterface $item the property to visit - * * @throws \Exception */ public function visit(ItemInterface $item): void diff --git a/src/PHPCR/Util/NodeHelper.php b/src/PHPCR/Util/NodeHelper.php index 28abbd48..97924878 100644 --- a/src/PHPCR/Util/NodeHelper.php +++ b/src/PHPCR/Util/NodeHelper.php @@ -12,7 +12,6 @@ use PHPCR\NodeInterface; use PHPCR\NodeType\ConstraintViolationException; use PHPCR\PathNotFoundException; -use PHPCR\PropertyInterface; use PHPCR\RepositoryException; use PHPCR\SessionInterface; use PHPCR\Version\VersionException; @@ -35,7 +34,9 @@ private function __construct() } /** - * Create a node and it's parents, if necessary. Like mkdir -p. + * Create a node and it's parents, if necessary. + * + * Like mkdir -p. * * @param SessionInterface $session the PHPCR session to create the path * @param string $path full path, like /content/jobs/data @@ -87,14 +88,12 @@ public static function purgeWorkspace(SessionInterface $session): void { $root = $session->getRootNode(); - /** @var PropertyInterface $property */ foreach ($root->getProperties() as $property) { if (!self::isSystemItem($property)) { $property->remove(); } } - /** @var NodeInterface $node */ foreach ($root->getNodes() as $node) { if (!self::isSystemItem($node)) { $node->remove(); @@ -107,8 +106,6 @@ public static function purgeWorkspace(SessionInterface $session): void * usually want to hide and that should not be removed when purging the * repository. * - * @return bool true if $item is a system item, false otherwise - * * @throws RepositoryException */ public static function isSystemItem(ItemInterface $item): bool @@ -282,7 +279,7 @@ public static function calculateOrderBefore(array $old, array $new): array $newIndex = array_flip($new); foreach ($old as $key => $value) { - if (!isset($newIndex[$value])) { + if (!array_key_exists($value, $newIndex)) { unset($old[$key]); } } diff --git a/src/PHPCR/Util/PathHelper.php b/src/PHPCR/Util/PathHelper.php index e8fcbfce..ffa1464f 100644 --- a/src/PHPCR/Util/PathHelper.php +++ b/src/PHPCR/Util/PathHelper.php @@ -124,13 +124,12 @@ public static function assertValidLocalName(string $name, bool $throw = true): b * @param bool $throw whether to throw an exception if validation fails or * just to return false * - * @return string The normalized path or false if $throw was false and the path invalid - * @return string The normalized path or false if $throw was false and the path invalid + * @return false|string The normalized path or false if $throw was false and the path invalid * * @throws RepositoryException if the path is not a valid absolute path and * $throw is true */ - public static function normalizePath(string $path, bool $destination = false, bool $throw = true): bool|string + public static function normalizePath(string $path, bool $destination = false, bool $throw = true): false|string { if ('' === $path) { return self::error('Path must not be of zero length', $throw); @@ -184,13 +183,13 @@ public static function normalizePath(string $path, bool $destination = false, bo * @param bool $throw whether to throw an exception if validation fails or * just to return false * - * @return string The normalized, absolute path or false if $throw was - * false and the path invalid + * @return false|string The normalized, absolute path or false if $throw was + * false and the path invalid * * @throws RepositoryException if the path can not be made into a valid * absolute path and $throw is true */ - public static function absolutizePath(string $path, string $context, bool $destination = false, bool $throw = true): bool|string + public static function absolutizePath(string $path, string $context, bool $destination = false, bool $throw = true): false|string { if ('' === $path) { return self::error('Path must not be of zero length', $throw); @@ -214,9 +213,9 @@ public static function absolutizePath(string $path, string $context, bool $desti * @param string $context The absolute path to an ancestor of $path * @param bool $throw whether to throw exceptions on invalid data * - * @return string The relative path from $context to $path + * @return false|string The relative path from $context to $path */ - public static function relativizePath(string $path, string $context, bool $throw = true): bool|string + public static function relativizePath(string $path, string $context, bool $throw = true): false|string { if (!str_starts_with($path, $context)) { return self::error("$path is not within $context", $throw); @@ -278,8 +277,6 @@ public static function getNodeName(string $path): string * * @param string $path a valid absolute path * - * @return string The localname - * * @throws RepositoryException */ public static function getLocalNodeName(string $path): string @@ -313,7 +310,7 @@ public static function getPathDepth(string $path): int * @param string $msg the exception message to use in case of throw being true * @param bool $throw whether to throw the exception or return false * - * @return bool false + * @return false * * @throws RepositoryException */ diff --git a/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php b/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php index f4d8c38c..f9444b71 100644 --- a/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php +++ b/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php @@ -17,9 +17,6 @@ abstract class BaseQomToSqlQueryConverter { protected BaseSqlGenerator $generator; - /** - * Instantiate the converter. - */ public function __construct(BaseSqlGenerator $generator) { $this->generator = $generator; diff --git a/src/PHPCR/Util/QOM/QueryBuilder.php b/src/PHPCR/Util/QOM/QueryBuilder.php index f7fa228c..f29faa9c 100644 --- a/src/PHPCR/Util/QOM/QueryBuilder.php +++ b/src/PHPCR/Util/QOM/QueryBuilder.php @@ -47,14 +47,14 @@ class QueryBuilder private int $maxResults = 0; /** - * @var OrderingInterface[] with the orderings that determine the order of the result + * @var OrderingInterface[] */ private array $orderings = []; private ?ConstraintInterface $constraint = null; /** - * @var ColumnInterface[] the columns to be selected + * @var ColumnInterface[] */ private array $columns = []; @@ -67,9 +67,6 @@ class QueryBuilder */ private array $params = []; - /** - * Initializes a new QueryBuilder. - */ public function __construct( private QueryObjectModelFactoryInterface $qomFactory ) { @@ -79,19 +76,18 @@ public function __construct( * Get a query builder instance from an existing query. * * @param string|QueryObjectModelInterface $statement the statement in the specified language - * @param string $language the query language * * @throws \InvalidArgumentException */ - public function setFromQuery(string|QueryObjectModelInterface $statement, string $language): static + public function setFromQuery(string|QueryObjectModelInterface $statement, string $queryLanguage): static { - if (QueryInterface::JCR_SQL2 === $language) { + if (QueryInterface::JCR_SQL2 === $queryLanguage) { $converter = new Sql2ToQomQueryConverter($this->qomFactory); $statement = $converter->parse($statement); } if (!$statement instanceof QueryObjectModelInterface) { - throw new \InvalidArgumentException("Language '$language' not supported"); + throw new \InvalidArgumentException("Language '$queryLanguage' not supported"); } $this->state = self::STATE_DIRTY; @@ -103,9 +99,6 @@ public function setFromQuery(string|QueryObjectModelInterface $statement, string return $this; } - /** - * Get the associated QOMFactory for this query builder. - */ public function getQOMFactory(): QueryObjectModelFactoryInterface { return $this->qomFactory; @@ -121,8 +114,6 @@ public function qomf(): QueryObjectModelFactoryInterface /** * sets the position of the first result to retrieve (the "offset"). - * - * @param int $firstResult the First result to return */ public function setFirstResult(int $firstResult): static { @@ -144,8 +135,6 @@ public function getFirstResult(): int /** * Sets the maximum number of results to retrieve (the "limit"). - * - * @param int $maxResults the maximum number of results to retrieve */ public function setMaxResults(int $maxResults): static { @@ -164,9 +153,7 @@ public function getMaxResults(): int } /** - * Gets the array of orderings. - * - * @return OrderingInterface[] orderings to apply + * @return OrderingInterface[] */ public function getOrderings(): array { @@ -288,9 +275,7 @@ public function orWhere(ConstraintInterface $constraint): static } /** - * Returns the columns to be selected. - * - * @return ColumnInterface[] The columns to be selected + * @return ColumnInterface[] */ public function getColumns(): array { @@ -298,9 +283,7 @@ public function getColumns(): array } /** - * Sets the columns to be selected. - * - * @param ColumnInterface[] $columns The columns to be selected + * @param ColumnInterface[] $columns */ public function setColumns(array $columns): static { @@ -348,7 +331,7 @@ public function from(SourceInterface $source): static /** * Gets the default Selector. * - * @return SourceInterface the default selector + * @return SourceInterface|null the default selector */ public function getSource(): ?SourceInterface { @@ -455,13 +438,10 @@ public function execute(): QueryResultInterface /** * Sets a query parameter for the query being constructed. - * - * @param string $key the parameter name - * @param mixed $value the parameter value */ - public function setParameter(string $key, mixed $value): static + public function setParameter(string $parameterName, mixed $parameterValue): static { - $this->params[$key] = $value; + $this->params[$parameterName] = $parameterValue; return $this; } @@ -469,9 +449,9 @@ public function setParameter(string $key, mixed $value): static /** * Gets a (previously set) query parameter of the query being constructed. */ - public function getParameter(string $key): mixed + public function getParameter(string $parameterName): mixed { - return $this->params[$key] ?? null; + return $this->params[$parameterName] ?? null; } /** @@ -487,9 +467,7 @@ public function setParameters(array $params): static } /** - * Gets all defined query parameters for the query being constructed. - * - * @return array + * @return array Map of parameter name => parameter value */ public function getParameters(): array { diff --git a/src/PHPCR/Util/QOM/Sql1Generator.php b/src/PHPCR/Util/QOM/Sql1Generator.php index 3f637a98..bcd7b936 100644 --- a/src/PHPCR/Util/QOM/Sql1Generator.php +++ b/src/PHPCR/Util/QOM/Sql1Generator.php @@ -68,8 +68,8 @@ public function evalDescendantNode(string $path, string $selectorName = null): s * PropertyExistence ::= * propertyName 'IS NOT NULL'. * - * @param string $selectorName declared to simplifiy interface - as there - * are no joins in SQL1 there is no need for a selector + * @param string|null $selectorName declared to simplifiy interface - as there + * are no joins in SQL1 there is no need for a selector */ public function evalPropertyExistence(?string $selectorName, string $propertyName): string { diff --git a/src/PHPCR/Util/QOM/Sql2Scanner.php b/src/PHPCR/Util/QOM/Sql2Scanner.php index 1f83f7d1..0ec2a830 100644 --- a/src/PHPCR/Util/QOM/Sql2Scanner.php +++ b/src/PHPCR/Util/QOM/Sql2Scanner.php @@ -31,9 +31,6 @@ class Sql2Scanner */ protected int $curpos = 0; - /** - * Construct a scanner with the given SQL2 statement. - */ public function __construct(string $sql2) { $this->sql2 = $sql2; diff --git a/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php b/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php index bde44172..880a0f9e 100644 --- a/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php +++ b/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php @@ -6,10 +6,12 @@ use PHPCR\PropertyType; use PHPCR\Query\InvalidQueryException; +use PHPCR\Query\QOM\ChildNodeInterface; use PHPCR\Query\QOM\ChildNodeJoinConditionInterface; use PHPCR\Query\QOM\ColumnInterface; use PHPCR\Query\QOM\ComparisonInterface; use PHPCR\Query\QOM\ConstraintInterface; +use PHPCR\Query\QOM\DescendantNodeInterface; use PHPCR\Query\QOM\DescendantNodeJoinConditionInterface; use PHPCR\Query\QOM\DynamicOperandInterface; use PHPCR\Query\QOM\EquiJoinConditionInterface; @@ -22,6 +24,7 @@ use PHPCR\Query\QOM\QueryObjectModelConstantsInterface as Constants; use PHPCR\Query\QOM\QueryObjectModelFactoryInterface; use PHPCR\Query\QOM\QueryObjectModelInterface; +use PHPCR\Query\QOM\SameNodeInterface; use PHPCR\Query\QOM\SameNodeJoinConditionInterface; use PHPCR\Query\QOM\SelectorInterface; use PHPCR\Query\QOM\SourceInterface; @@ -36,16 +39,8 @@ */ class Sql2ToQomQueryConverter { - /** - * The factory to create QOM objects. - */ protected QueryObjectModelFactoryInterface $factory; - /** - * Scanner to parse SQL2. - * - * @var Sql2Scanner; - */ protected Sql2Scanner $scanner; /** @@ -64,8 +59,6 @@ class Sql2ToQomQueryConverter private ValueConverter $valueConverter; /** - * Instantiate a converter. - * * @param ValueConverter|null $valueConverter to override default converter */ public function __construct(QueryObjectModelFactoryInterface $factory, ValueConverter $valueConverter = null) @@ -128,8 +121,6 @@ public function parse($sql2): QueryObjectModelInterface /** * 6.7.2. Source * Parse an SQL2 source definition and return the corresponding QOM Source. - * - * @return SourceInterface */ protected function parseSource(): JoinInterface|SourceInterface|SelectorInterface { @@ -225,10 +216,8 @@ protected function parseJoinType(): string /** * 6.7.7. JoinCondition * Parse an SQL2 join condition and return a JoinConditionInterface. - * - * @return JoinConditionInterface */ - protected function parseJoinCondition(): SameNodeJoinConditionInterface|EquiJoinConditionInterface|DescendantNodeJoinConditionInterface|ChildNodeJoinConditionInterface|JoinConditionInterface + protected function parseJoinCondition(): JoinConditionInterface { $this->scanner->expectToken('ON'); @@ -324,7 +313,7 @@ protected function parseDescendantNodeJoinCondition(): DescendantNodeJoinConditi * * @throws \Exception */ - protected function parseConstraint(ConstraintInterface $lhs = null, int $minprec = 0): FullTextSearchInterface|ComparisonInterface|NotInterface|ConstraintInterface|null + protected function parseConstraint(ConstraintInterface $lhs = null, int $minprec = 0): ConstraintInterface|null { if (null === $lhs) { $lhs = $this->parsePrimaryConstraint(); @@ -370,10 +359,8 @@ protected function parseConstraint(ConstraintInterface $lhs = null, int $minprec /** * 6.7.12 Constraint. - * - * @return ConstraintInterface */ - protected function parsePrimaryConstraint() + protected function parsePrimaryConstraint(): ConstraintInterface { $constraint = null; $token = $this->scanner->lookupNextToken(); @@ -519,7 +506,7 @@ protected function parseFullTextSearch(): FullTextSearchInterface /** * 6.7.20 SameNode. */ - protected function parseSameNode() + protected function parseSameNode(): SameNodeInterface { $this->scanner->expectTokens(['ISSAMENODE', '(']); if ($this->scanner->tokenIs($this->scanner->lookupNextToken(1), ',')) { @@ -538,7 +525,7 @@ protected function parseSameNode() /** * 6.7.21 ChildNode. */ - protected function parseChildNode(): \PHPCR\Query\QOM\ChildNodeInterface + protected function parseChildNode(): ChildNodeInterface { $this->scanner->expectTokens(['ISCHILDNODE', '(']); if ($this->scanner->tokenIs($this->scanner->lookupNextToken(1), ',')) { @@ -557,7 +544,7 @@ protected function parseChildNode(): \PHPCR\Query\QOM\ChildNodeInterface /** * 6.7.22 DescendantNode. */ - protected function parseDescendantNode(): \PHPCR\Query\QOM\DescendantNodeInterface + protected function parseDescendantNode(): DescendantNodeInterface { $this->scanner->expectTokens(['ISDESCENDANTNODE', '(']); if ($this->scanner->tokenIs($this->scanner->lookupNextToken(1), ',')) { @@ -583,7 +570,7 @@ protected function parseDescendantNode(): \PHPCR\Query\QOM\DescendantNodeInterfa protected function parsePath() { $path = $this->parseLiteralValue(); - if ('[' === substr($path, 0, 1) && ']' === substr($path, -1)) { + if (str_starts_with($path, '[') && str_ends_with($path, ']')) { $path = substr($path, 1, -1); } @@ -598,7 +585,7 @@ protected function parsePath() protected function parseStaticOperand(): StaticOperandInterface { $token = $this->scanner->lookupNextToken(); - if ('$' === substr($token, 0, 1)) { + if (str_starts_with($token, '$')) { return $this->factory->bindVariable(substr($this->scanner->fetchNextToken(), 1)); } @@ -614,8 +601,6 @@ protected function parseStaticOperand(): StaticOperandInterface * 6.7.32 LowerCase * 6.7.33 UpperCase * Parse an SQL2 dynamic operand. - * - * @return DynamicOperandInterface */ protected function parseDynamicOperand(): DynamicOperandInterface|PropertyValueInterface { @@ -893,8 +878,8 @@ private function fetchTokenWithoutBrackets(): string * * @param bool $checkSelector whether we need to ensure a valid selector * - * @return array with selectorName and propertyName. If no selectorName is - * specified, defaults to $this->defaultSelectorName + * @return string[] with selectorName and propertyName. If no selectorName is + * specified, defaults to $this->defaultSelectorName */ private function parseIdentifier(bool $checkSelector = true): array { @@ -939,14 +924,12 @@ protected function updateImplicitSelectorName(string $selectorName): void /** * Ensure that the parsedName is a valid selector, or return the implicit - * selector if its non-ambigous. - * - * @return string the selector to use + * selector if its non-ambiguous. * * @throws InvalidQueryException if there was no explicit selector and * there is more than one selector available */ - protected function ensureSelectorName(?string $parsedName): array|string|null + protected function ensureSelectorName(?string $parsedName): string|null { if (null !== $parsedName) { if ((is_array($this->implicitSelectorName) && !isset($this->implicitSelectorName[$parsedName])) diff --git a/src/PHPCR/Util/TraversingItemVisitor.php b/src/PHPCR/Util/TraversingItemVisitor.php index 1ee1ced9..4707e962 100644 --- a/src/PHPCR/Util/TraversingItemVisitor.php +++ b/src/PHPCR/Util/TraversingItemVisitor.php @@ -61,8 +61,6 @@ abstract class TraversingItemVisitor implements ItemVisitorInterface protected int $currentDepth; /** - * Constructs a new instance of this class. - * * @param bool $breadthFirst if $breadthFirst is true then traversal is * done in a breadth-first manner; otherwise it is done in a * depth-first manner (which is the default behavior) @@ -70,8 +68,6 @@ abstract class TraversingItemVisitor implements ItemVisitorInterface * to which the hierarchy should be traversed (if it's -1, the * hierarchy will be traversed until there are no more children of the * current item) - * - * @api */ public function __construct(bool $breadthFirst = false, int $maxDepth = -1) { diff --git a/src/PHPCR/Util/TreeWalker.php b/src/PHPCR/Util/TreeWalker.php index 0ebe6f03..723b54ba 100644 --- a/src/PHPCR/Util/TreeWalker.php +++ b/src/PHPCR/Util/TreeWalker.php @@ -17,14 +17,8 @@ */ class TreeWalker { - /** - * Visitor for nodes. - */ protected ItemVisitorInterface $nodeVisitor; - /** - * Visitor for properties. - */ protected ?ItemVisitorInterface $propertyVisitor; /** @@ -42,8 +36,6 @@ class TreeWalker protected array $propertyFilters = []; /** - * Instantiate a tree walker. - * * @param ItemVisitorInterface $nodeVisitor The visitor for the nodes * @param ItemVisitorInterface|null $propertyVisitor The visitor for the nodes properties */ @@ -53,9 +45,6 @@ public function __construct(ItemVisitorInterface $nodeVisitor, ItemVisitorInterf $this->propertyVisitor = $propertyVisitor; } - /** - * Add a filter to select the nodes that will be traversed. - */ public function addNodeFilter(TreeWalkerFilterInterface $filter): void { if (!in_array($filter, $this->nodeFilters, true)) { @@ -63,12 +52,9 @@ public function addNodeFilter(TreeWalkerFilterInterface $filter): void } } - /** - * Add a filter to select the properties that will be traversed. - */ public function addPropertyFilter(TreeWalkerFilterInterface $filter): void { - if (!in_array($filter, $this->propertyFilters)) { + if (!in_array($filter, $this->propertyFilters, true)) { $this->propertyFilters[] = $filter; } } @@ -102,10 +88,8 @@ protected function mustVisitProperty(PropertyInterface $property): bool } /** - * Traverse a node. - * * @param int $recurse Max recursion level - * @param int $level Recursion level + * @param int $level Current recursion level */ public function traverse(NodeInterface $node, int $recurse = -1, int $level = 0): void { diff --git a/src/PHPCR/Util/UUIDHelper.php b/src/PHPCR/Util/UUIDHelper.php index 6b5f5ec2..f9a76953 100644 --- a/src/PHPCR/Util/UUIDHelper.php +++ b/src/PHPCR/Util/UUIDHelper.php @@ -18,8 +18,6 @@ class UUIDHelper * Checks if the string could be a UUID. * * @param string $id Possible uuid - * - * @return bool true if the test was passed, else false */ public static function isUUID(string $id): bool { diff --git a/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php b/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php index 84982b55..79360382 100644 --- a/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php +++ b/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php @@ -14,7 +14,10 @@ class GenericScannerTest extends TestCase { - protected $expectedTokens = [ + /** + * @var array + */ + private array $expectedTokens = [ // [Token::TK_SYMBOL, '<'], [Token::TK_SYMBOL, '?'], @@ -104,7 +107,10 @@ class GenericScannerTest extends TestCase [Token::TK_NEWLINE, ''], ]; - protected $expectedTokensNoEmptyToken; + /** + * @var Token[] + */ + protected array $expectedTokensNoEmptyToken; public function setUp(): void { diff --git a/tests/PHPCR/Tests/Util/CND/Scanner/TokenTest.php b/tests/PHPCR/Tests/Util/CND/Scanner/TokenTest.php index 08b7673b..79cf6603 100644 --- a/tests/PHPCR/Tests/Util/CND/Scanner/TokenTest.php +++ b/tests/PHPCR/Tests/Util/CND/Scanner/TokenTest.php @@ -21,8 +21,8 @@ public function setUp(): void public function testConstruct(): void { - $this->assertSame(123, $this->token->type); - $this->assertSame('foobar', $this->token->data); + $this->assertSame(123, $this->token->getType()); + $this->assertSame('foobar', $this->token->getData()); } public function testGetData(): void From 78040a92af1a91a6a163a8eb62f1fdbc6c2caac6 Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Fri, 1 Dec 2023 15:34:59 +0100 Subject: [PATCH 07/13] raise phpstan level and improve type safety --- phpstan.neon.dist | 16 ++- phpstan.tests.neon.dist | 31 +++++- src/PHPCR/Util/CND/Parser/AbstractParser.php | 11 +- src/PHPCR/Util/CND/Parser/CndParser.php | 2 +- src/PHPCR/Util/CND/Scanner/GenericScanner.php | 3 +- src/PHPCR/Util/CND/Writer/CndWriter.php | 4 +- .../Util/Console/Command/BaseCommand.php | 21 +++- .../ConsoleDumperPropertyVisitor.php | 2 +- .../Util/QOM/Sql2ToQomQueryConverter.php | 5 - tests/PHPCR/Tests/Stubs/MockNode.php | 3 + .../PHPCR/Tests/Stubs/MockNodeTypeManager.php | 4 + tests/PHPCR/Tests/Stubs/MockRow.php | 3 + .../Tests/Util/CND/Reader/FileReaderTest.php | 2 +- .../Util/CND/Scanner/GenericScannerTest.php | 13 ++- .../Util/Console/Command/BaseCommandTest.php | 28 +++-- .../Console/Command/NodeDumpCommandTest.php | 2 +- .../Console/Command/NodeMoveCommandTest.php | 18 +++- .../Console/Command/NodeTouchCommandTest.php | 2 +- .../Command/NodeTypeListCommandTest.php | 2 +- .../Command/NodeTypeRegisterCommandTest.php | 2 +- .../Command/NodesUpdateCommandTest.php | 24 +++-- .../Command/WorkspaceQueryCommandTest.php | 2 +- .../Helper/PhpcrConsoleDumperHelperTest.php | 24 +++-- tests/PHPCR/Tests/Util/NodeHelperTest.php | 25 ++--- tests/PHPCR/Tests/Util/PathHelperTest.php | 102 ++++++++++++------ .../PHPCR/Tests/Util/QOM/QueryBuilderTest.php | 5 +- .../PHPCR/Tests/Util/QOM/Sql2ScannerTest.php | 3 + tests/PHPCR/Tests/Util/ValueConverterTest.php | 10 ++ 28 files changed, 255 insertions(+), 114 deletions(-) diff --git a/phpstan.neon.dist b/phpstan.neon.dist index 093e8156..6fc94366 100644 --- a/phpstan.neon.dist +++ b/phpstan.neon.dist @@ -1,4 +1,16 @@ parameters: - level: 2 + level: 5 paths: - - src + - src/ + + ignoreErrors: + # phpstan does not understand that the empty arrays are only the default + - + message: "#^Empty array passed to foreach\\.$#" + count: 5 + path: src/PHPCR/Util/Console/Helper/PhpcrHelper.php + # only formulated in phpdoc that the return value must be countable + - + message: "#expects array|Countable, Iterator given\\.$#" + count: 1 + path: src/PHPCR/Util/Console/Command/NodesUpdateCommand.php diff --git a/phpstan.tests.neon.dist b/phpstan.tests.neon.dist index 0efe94d4..b4deb820 100644 --- a/phpstan.tests.neon.dist +++ b/phpstan.tests.neon.dist @@ -1,4 +1,31 @@ parameters: - level: 1 + level: 7 paths: - - tests + - tests/ + + excludePaths: + analyse: + - tests/*/Fixtures/* + + ignoreErrors: + # not sure what is going on here + - + message: "#^Interface Iterator specifies template type TKey of interface Traversable as string but it's already specified as mixed\\.$#" + count: 1 + path: tests/PHPCR/Tests/Stubs/MockNodeTypeManager.php + + - + message: "#^Interface Iterator specifies template type TValue of interface Traversable as PHPCR\\\\NodeType\\\\NodeTypeInterface but it's already specified as mixed\\.$#" + count: 1 + path: tests/PHPCR/Tests/Stubs/MockNodeTypeManager.php + + # too pedantic for tests + - + message: "#^Parameter \\#1 \\.\\.\\.\\$arrays of function array_merge expects array, array\\\\|false given\\.$#" + count: 1 + path: tests/PHPCR/Tests/Util/CND/Reader/FileReaderTest.php + + - + message: "#^Parameter \\#3 \\.\\.\\.\\$arrays of function array_merge expects array, array\\\\|false given\\.$#" + count: 1 + path: tests/PHPCR/Tests/Util/CND/Reader/FileReaderTest.php diff --git a/src/PHPCR/Util/CND/Parser/AbstractParser.php b/src/PHPCR/Util/CND/Parser/AbstractParser.php index 1dfa587c..ace8eb21 100644 --- a/src/PHPCR/Util/CND/Parser/AbstractParser.php +++ b/src/PHPCR/Util/CND/Parser/AbstractParser.php @@ -5,6 +5,7 @@ namespace PHPCR\Util\CND\Parser; use PHPCR\Util\CND\Exception\ParserException; +use PHPCR\Util\CND\Scanner\GenericToken; use PHPCR\Util\CND\Scanner\GenericToken as Token; use PHPCR\Util\CND\Scanner\TokenQueue; @@ -29,12 +30,8 @@ abstract class AbstractParser * Check the next token without consuming it and return true if it matches the given type and data. * If the data is not provided (equal to null) then only the token type is checked. * Return false otherwise. - * - * @param int $type The expected token type - * @param string|null $data The expected data or null - * @param bool $ignoreCase whether to do string comparisons case insensitive or sensitive */ - protected function checkToken($type, string $data = null, bool $ignoreCase = false): bool + protected function checkToken(int $type, string $data = null, bool $ignoreCase = false): bool { if ($this->tokenQueue->isEof()) { return false; @@ -48,7 +45,7 @@ protected function checkToken($type, string $data = null, bool $ignoreCase = fal if ($data && $token->getData() !== $data) { if ($ignoreCase && is_string($data) && is_string($token->getData())) { - return strcasecmp($data, $token->getData()); + return 0 !== strcasecmp($data, $token->getData()); } return false; @@ -89,7 +86,7 @@ protected function expectToken(int $type, string $data = null): Token if (!$this->checkToken($type, $data)) { throw new ParserException($this->tokenQueue, sprintf("Expected token [%s, '%s']", Token::getTypeName($type), $data)); } - + \assert($token instanceof GenericToken); $this->tokenQueue->next(); return $token; diff --git a/src/PHPCR/Util/CND/Parser/CndParser.php b/src/PHPCR/Util/CND/Parser/CndParser.php index 58a76d8c..33dd38d5 100644 --- a/src/PHPCR/Util/CND/Parser/CndParser.php +++ b/src/PHPCR/Util/CND/Parser/CndParser.php @@ -71,7 +71,7 @@ final class CndParser extends AbstractParser private array $namespaces = []; /** - * @var string[] + * @var NodeTypeDefinitionInterface[] */ private array $nodeTypes = []; diff --git a/src/PHPCR/Util/CND/Scanner/GenericScanner.php b/src/PHPCR/Util/CND/Scanner/GenericScanner.php index d03bb90c..8161eb3a 100644 --- a/src/PHPCR/Util/CND/Scanner/GenericScanner.php +++ b/src/PHPCR/Util/CND/Scanner/GenericScanner.php @@ -28,8 +28,7 @@ public function scan(ReaderInterface $reader): TokenQueue $this->resetQueue(); while (!$reader->isEof()) { - $tokenFound = false; - $tokenFound = $tokenFound || $this->consumeComments($reader); + $tokenFound = $this->consumeComments($reader); $tokenFound = $tokenFound || $this->consumeNewLine($reader); $tokenFound = $tokenFound || $this->consumeSpaces($reader); $tokenFound = $tokenFound || $this->consumeString($reader); diff --git a/src/PHPCR/Util/CND/Writer/CndWriter.php b/src/PHPCR/Util/CND/Writer/CndWriter.php index 20f8d5e0..796f3997 100644 --- a/src/PHPCR/Util/CND/Writer/CndWriter.php +++ b/src/PHPCR/Util/CND/Writer/CndWriter.php @@ -119,9 +119,7 @@ protected function writeNodeType(NodeTypeDefinitionInterface $nodeType): string if ($nodeType->getPrimaryItemName()) { $attributes .= 'primaryitem '.$nodeType->getPrimaryItemName().' '; } - if ($attributes) { - $s .= trim($attributes)."\n"; - } + $s .= trim($attributes)."\n"; $s .= $this->writeProperties($nodeType->getDeclaredPropertyDefinitions()); diff --git a/src/PHPCR/Util/Console/Command/BaseCommand.php b/src/PHPCR/Util/Console/Command/BaseCommand.php index b5d86e1b..756dab9a 100644 --- a/src/PHPCR/Util/Console/Command/BaseCommand.php +++ b/src/PHPCR/Util/Console/Command/BaseCommand.php @@ -25,16 +25,31 @@ protected function getPhpcrSession(): SessionInterface protected function getPhpcrHelper(): PhpcrHelper { - return $this->getHelper('phpcr'); + $helper = $this->getHelper('phpcr'); + if (!$helper instanceof PhpcrHelper) { + throw new \RuntimeException('phpcr must be the PhpcrHelper'); + } + + return $helper; } protected function getPhpcrConsoleDumperHelper(): PhpcrConsoleDumperHelper { - return $this->getHelper('phpcr_console_dumper'); + $helper = $this->getHelper('phpcr_console_dumper'); + if (!$helper instanceof PhpcrConsoleDumperHelper) { + throw new \RuntimeException('phpcr_console_dumper must be the PhpcrConsoleDumperHelper'); + } + + return $helper; } protected function getQuestionHelper(): QuestionHelper { - return $this->getHelper('question'); + $helper = $this->getHelper('question'); + if (!$helper instanceof QuestionHelper) { + throw new \RuntimeException('question must be the QuestionHelper'); + } + + return $helper; } } diff --git a/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperPropertyVisitor.php b/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperPropertyVisitor.php index cd07faaf..4a4f41c3 100644 --- a/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperPropertyVisitor.php +++ b/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperPropertyVisitor.php @@ -47,7 +47,7 @@ public function __construct(OutputInterface $output, array $options = []) public function visit(ItemInterface $item): void { if (!$item instanceof PropertyInterface) { - throw new \Exception(sprintf('Internal error: did not expect to visit a non-property object: %s', is_object($item) ? $item::class : $item)); + throw new \Exception(sprintf('Internal error: did not expect to visit a non-property object: %s', $item::class)); } $value = $item->getString(); diff --git a/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php b/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php index 880a0f9e..bb1e88b4 100644 --- a/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php +++ b/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php @@ -429,11 +429,6 @@ protected function parseNot(): NotInterface protected function parseComparison(): ComparisonInterface { $op1 = $this->parseDynamicOperand(); - - if (null === $op1) { - throw new InvalidQueryException("Syntax error: dynamic operator expected in '{$this->sql2}'"); - } - $operator = $this->parseOperator(); $op2 = $this->parseStaticOperand(); diff --git a/tests/PHPCR/Tests/Stubs/MockNode.php b/tests/PHPCR/Tests/Stubs/MockNode.php index 68603a0a..5d27eac6 100644 --- a/tests/PHPCR/Tests/Stubs/MockNode.php +++ b/tests/PHPCR/Tests/Stubs/MockNode.php @@ -6,6 +6,9 @@ use PHPCR\NodeInterface; +/** + * @implements \Iterator + */ abstract class MockNode implements \Iterator, NodeInterface { } diff --git a/tests/PHPCR/Tests/Stubs/MockNodeTypeManager.php b/tests/PHPCR/Tests/Stubs/MockNodeTypeManager.php index b085ecf3..468fe9d4 100644 --- a/tests/PHPCR/Tests/Stubs/MockNodeTypeManager.php +++ b/tests/PHPCR/Tests/Stubs/MockNodeTypeManager.php @@ -4,8 +4,12 @@ namespace PHPCR\Tests\Stubs; +use PHPCR\NodeType\NodeTypeInterface; use PHPCR\NodeType\NodeTypeManagerInterface; +/** + * @implements \Iterator + */ abstract class MockNodeTypeManager implements \Iterator, NodeTypeManagerInterface { } diff --git a/tests/PHPCR/Tests/Stubs/MockRow.php b/tests/PHPCR/Tests/Stubs/MockRow.php index 27bc04e9..95112378 100644 --- a/tests/PHPCR/Tests/Stubs/MockRow.php +++ b/tests/PHPCR/Tests/Stubs/MockRow.php @@ -6,6 +6,9 @@ use PHPCR\Query\RowInterface; +/** + * @implements \Iterator + */ abstract class MockRow implements \Iterator, RowInterface { } diff --git a/tests/PHPCR/Tests/Util/CND/Reader/FileReaderTest.php b/tests/PHPCR/Tests/Util/CND/Reader/FileReaderTest.php index 00e8fc89..1e49cbb4 100644 --- a/tests/PHPCR/Tests/Util/CND/Reader/FileReaderTest.php +++ b/tests/PHPCR/Tests/Util/CND/Reader/FileReaderTest.php @@ -20,7 +20,7 @@ class FileReaderTest extends TestCase private $reader; /** - * @var array + * @var string[] */ private $lines; diff --git a/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php b/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php index 79360382..7021b05f 100644 --- a/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php +++ b/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php @@ -15,7 +15,7 @@ class GenericScannerTest extends TestCase { /** - * @var array + * @var array */ private array $expectedTokens = [ // @@ -108,7 +108,7 @@ class GenericScannerTest extends TestCase ]; /** - * @var Token[] + * @var array */ protected array $expectedTokensNoEmptyToken; @@ -146,7 +146,10 @@ public function testFilteredScan(): void $this->assertTokens($this->expectedTokensNoEmptyToken, $queue); } - protected function assertTokens($tokens, TokenQueue $queue): void + /** + * @param array $tokens + */ + protected function assertTokens(array $tokens, TokenQueue $queue): void { $queue->reset(); @@ -155,6 +158,8 @@ protected function assertTokens($tokens, TokenQueue $queue): void $token = $queue->peek(); while ($it->valid()) { + $this->assertInstanceOf(Token::class, $token); + $expectedToken = $it->current(); $this->assertFalse($queue->isEof(), 'There is no more tokens, expected = '.$expectedToken[1]); @@ -168,7 +173,7 @@ protected function assertTokens($tokens, TokenQueue $queue): void $this->assertTrue($queue->isEof(), 'There are more unexpected tokens.'); } - protected function assertToken($type, $data, Token|false $token): void + protected function assertToken(int $type, string $data, Token $token): void { $this->assertEquals( $type, diff --git a/tests/PHPCR/Tests/Util/Console/Command/BaseCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/BaseCommandTest.php index 84d430ec..a0300cec 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/BaseCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/BaseCommandTest.php @@ -27,37 +27,37 @@ abstract class BaseCommandTest extends TestCase { /** - * @var SessionInterface|MockObject + * @var SessionInterface&MockObject * */ public $session; /** - * @var WorkspaceInterface|MockObject + * @var WorkspaceInterface&MockObject */ public $workspace; /** - * @var RepositoryInterface|MockObject + * @var RepositoryInterface&MockObject */ public $repository; /** - * @var PhpcrConsoleDumperHelper|MockObject + * @var PhpcrConsoleDumperHelper&MockObject */ public $dumperHelper; /** - * @var NodeInterface|MockObject + * @var NodeInterface&MockObject */ public $node1; /** - * @var RowInterface|MockObject + * @var RowInterface&MockObject */ public $row1; /** - * @var QueryManagerInterface|MockObject + * @var QueryManagerInterface&MockObject */ public $queryManager; @@ -113,18 +113,14 @@ public function setUp(): void /** * Build and execute the command tester. * - * @param string $name command name - * @param array $args command arguments - * @param int $status expected return status - * - * @return CommandTester + * @param mixed[] $arguments */ - public function executeCommand($name, $args, $status = 0) + public function executeCommand(string $commandName, array $arguments, int $expectedReturnStatus = 0): CommandTester { - $command = $this->application->find($name); + $command = $this->application->find($commandName); $commandTester = new CommandTester($command); - $args = array_merge(['command' => $command->getName()], $args); - $this->assertEquals($status, $commandTester->execute($args)); + $arguments = array_merge(['command' => $command->getName()], $arguments); + $this->assertEquals($expectedReturnStatus, $commandTester->execute($arguments)); return $commandTester; } diff --git a/tests/PHPCR/Tests/Util/Console/Command/NodeDumpCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodeDumpCommandTest.php index d5228ea1..5e5da9a9 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodeDumpCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodeDumpCommandTest.php @@ -12,7 +12,7 @@ class NodeDumpCommandTest extends BaseCommandTest { - /** @var TreeWalker|MockObject */ + /** @var TreeWalker&MockObject */ protected $treeWalker; public function setUp(): void diff --git a/tests/PHPCR/Tests/Util/Console/Command/NodeMoveCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodeMoveCommandTest.php index 52d57760..4dee112a 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodeMoveCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodeMoveCommandTest.php @@ -8,15 +8,27 @@ class NodeMoveCommandTest extends BaseCommandTest { - public function provideCommand() + /** + * @return array> + */ + public function provideCommand(): array { - return [[['source' => '/foo', 'destination' => '/bar']]]; + return [ + [ + [ + 'source' => '/foo', + 'destination' => '/bar', + ], + ], + ]; } /** * @dataProvider provideCommand + * + * @param array $args */ - public function testCommand($args): void + public function testCommand(array $args): void { $this->session->expects($this->once()) ->method('move') diff --git a/tests/PHPCR/Tests/Util/Console/Command/NodeTouchCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodeTouchCommandTest.php index 41febd1b..afc746d3 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodeTouchCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodeTouchCommandTest.php @@ -17,7 +17,7 @@ class NodeTouchCommandTest extends BaseCommandTest { /** - * @var PhpcrHelper|MockObject + * @var PhpcrHelper&MockObject */ public $phpcrHelper; diff --git a/tests/PHPCR/Tests/Util/Console/Command/NodeTypeListCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodeTypeListCommandTest.php index 3359f872..fb25baf0 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodeTypeListCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodeTypeListCommandTest.php @@ -11,7 +11,7 @@ class NodeTypeListCommandTest extends BaseCommandTest { /** - * @var MockNodeTypeManager|MockObject + * @var MockNodeTypeManager&MockObject */ private $nodeTypeManager; diff --git a/tests/PHPCR/Tests/Util/Console/Command/NodeTypeRegisterCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodeTypeRegisterCommandTest.php index 76fc4e71..712b4a13 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodeTypeRegisterCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodeTypeRegisterCommandTest.php @@ -11,7 +11,7 @@ class NodeTypeRegisterCommandTest extends BaseCommandTest { /** - * @var MockNodeTypeManager|MockObject + * @var MockNodeTypeManager&MockObject */ private $nodeTypeManager; diff --git a/tests/PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php index 251655a2..6806109e 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php @@ -11,7 +11,7 @@ class NodesUpdateCommandTest extends BaseCommandTest { /** - * @var QueryInterface|MockObject + * @var QueryInterface&MockObject */ private $query; @@ -23,13 +23,20 @@ public function setUp(): void $this->query = $this->createMock(QueryInterface::class); } - public function provideNodeUpdate() + /** + * @return array>> + */ + public function provideNodeUpdate(): array { return [ // No query specified - [['exception' => \InvalidArgumentException::class]], + [[ + 'exception' => \InvalidArgumentException::class, + ]], // Specify query - [['query' => 'SELECT * FROM nt:unstructured WHERE foo="bar"']], + [[ + 'query' => 'SELECT * FROM nt:unstructured WHERE foo="bar"', + ]], // Set, remote properties and mixins [[ 'setProp' => [['foo', 'bar']], @@ -41,7 +48,10 @@ public function provideNodeUpdate() ]; } - protected function setupQueryManager($options): void + /** + * @param array $options + */ + protected function setupQueryManager(array $options): void { $options = array_merge(['query' => ''], $options); @@ -69,8 +79,10 @@ protected function setupQueryManager($options): void /** * @dataProvider provideNodeUpdate + * + * @param array $options */ - public function testNodeUpdate($options): void + public function testNodeUpdate(array $options): void { $options = array_merge([ 'query' => null, diff --git a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceQueryCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceQueryCommandTest.php index 184f9cb2..d7510126 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceQueryCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceQueryCommandTest.php @@ -11,7 +11,7 @@ class WorkspaceQueryCommandTest extends BaseCommandTest { /** - * @var QueryInterface|MockObject + * @var QueryInterface&MockObject */ protected $query; diff --git a/tests/PHPCR/Tests/Util/Console/Helper/PhpcrConsoleDumperHelperTest.php b/tests/PHPCR/Tests/Util/Console/Helper/PhpcrConsoleDumperHelperTest.php index 575fc28e..748fb872 100644 --- a/tests/PHPCR/Tests/Util/Console/Helper/PhpcrConsoleDumperHelperTest.php +++ b/tests/PHPCR/Tests/Util/Console/Helper/PhpcrConsoleDumperHelperTest.php @@ -2,14 +2,19 @@ declare(strict_types=1); +namespace PHPCR\Tests\Util\Console\Helper; + use PHPCR\Util\Console\Helper\PhpcrConsoleDumperHelper; use PHPCR\Util\Console\Helper\TreeDumper\ConsoleDumperPropertyVisitor; -use PHPCR\Util\TreeWalker; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Symfony\Component\Console\Output\OutputInterface; class PhpcrConsoleDumperHelperTest extends TestCase { + /** + * @var MockObject&OutputInterface + */ private $outputMock; /** * @var PhpcrConsoleDumperHelper @@ -22,15 +27,23 @@ public function setUp(): void $this->helper = new PhpcrConsoleDumperHelper(); } - public function provideHelper() + /** + * @return array>> + */ + public function provideHelper(): array { - return [[[]], [['show_props' => true]]]; + return [ + [[]], + [['show_props' => true]], + ]; } /** * @dataProvider provideHelper + * + * @param array $options */ - public function testGetTreeWalker($options): void + public function testGetTreeWalker(array $options): void { $options = array_merge([ 'dump_uuids' => false, @@ -40,9 +53,8 @@ public function testGetTreeWalker($options): void ], $options); $tw = $this->helper->getTreeWalker($this->outputMock, $options); - $this->assertInstanceOf(TreeWalker::class, $tw); - $reflection = new ReflectionClass($tw); + $reflection = new \ReflectionClass($tw); $propVisitorProp = $reflection->getProperty('propertyVisitor'); $propVisitorProp->setAccessible(true); $propVisitor = $propVisitorProp->getValue($tw); diff --git a/tests/PHPCR/Tests/Util/NodeHelperTest.php b/tests/PHPCR/Tests/Util/NodeHelperTest.php index 68e514a1..1878745e 100644 --- a/tests/PHPCR/Tests/Util/NodeHelperTest.php +++ b/tests/PHPCR/Tests/Util/NodeHelperTest.php @@ -7,7 +7,6 @@ use PHPCR\RepositoryException; use PHPCR\Tests\Stubs\MockNode; use PHPCR\Util\NodeHelper; -use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; require_once __DIR__.'/../Stubs/MockNode.php'; @@ -15,19 +14,19 @@ class NodeHelperTest extends TestCase { /** - * @var array + * @var array */ - private $namespaces = ['a' => 'http://phpcr/', 'b' => 'http://jcr/']; + private array $namespaces = ['a' => 'http://phpcr/', 'b' => 'http://jcr/']; /** - * @var array + * @var string[] */ - private $usedNames = ['a:x', 'b:y', 'c']; + private array $usedNames = ['a:x', 'b:y', 'c']; /** - * @return array + * @return array */ - public static function hints() + public static function hints(): array { return [ ['', true], @@ -41,9 +40,9 @@ public static function hints() } /** - * @return array + * @return array> */ - public static function invalidHints() + public static function invalidHints(): array { return [ ['::'], @@ -66,12 +65,13 @@ public function testGenerateAutoNodeNameNoHint(): void /** * @dataProvider hints */ - public function testGenerateAutoNodeName($hint, $expect): void + public function testGenerateAutoNodeName(string $hint, bool|string $expect): void { $result = NodeHelper::generateAutoNodeName($this->usedNames, $this->namespaces, 'a', $hint); if (true === $expect) { $this->assertStringNotContainsString(':', $result); } else { + $this->assertIsString($expect); $this->assertEquals($expect, substr($result, 0, strlen($expect))); } } @@ -79,7 +79,7 @@ public function testGenerateAutoNodeName($hint, $expect): void /** * @dataProvider invalidHints */ - public function testGenerateAutoNodeNameInvalid($hint): void + public function testGenerateAutoNodeNameInvalid(string $hint): void { $this->expectException(RepositoryException::class); NodeHelper::generateAutoNodeName($this->usedNames, $this->namespaces, 'a', $hint); @@ -87,7 +87,6 @@ public function testGenerateAutoNodeNameInvalid($hint): void public function testIsSystemItem(): void { - /** @var MockNode|MockObject $sys */ $sys = $this->createMock(MockNode::class); $sys->expects($this->once()) @@ -111,7 +110,6 @@ public function testIsSystemItem(): void $this->assertTrue(NodeHelper::isSystemItem($sys)); - /** @var MockNode|MockObject $top */ $top = $this->createMock(MockNode::class); $top->expects($this->once()) ->method('getDepth') @@ -123,7 +121,6 @@ public function testIsSystemItem(): void $this->assertFalse(NodeHelper::isSystemItem($top)); - /** @var MockNode|MockObject $deep */ $deep = $this->createMock(MockNode::class); $deep->expects($this->once()) ->method('getDepth') diff --git a/tests/PHPCR/Tests/Util/PathHelperTest.php b/tests/PHPCR/Tests/Util/PathHelperTest.php index 8e03eeab..5bafb693 100644 --- a/tests/PHPCR/Tests/Util/PathHelperTest.php +++ b/tests/PHPCR/Tests/Util/PathHelperTest.php @@ -16,12 +16,15 @@ class PathHelperTest extends TestCase /** * @dataProvider dataproviderValidAbsolutePaths */ - public function testAssertValidAbsolutePath($path, $destination = false): void + public function testAssertValidAbsolutePath(string $path, bool $destination = false): void { $this->assertTrue(PathHelper::assertValidAbsolutePath($path, $destination)); } - public function dataproviderValidAbsolutePaths() + /** + * @return array + */ + public static function dataproviderValidAbsolutePaths(): array { return [ ['/parent/child'], @@ -36,7 +39,7 @@ public function dataproviderValidAbsolutePaths() /** * @dataProvider dataproviderInvalidAbsolutePaths */ - public function testAssertInvalidAbsolutePath($path, $destination = false): void + public function testAssertInvalidAbsolutePath(string $path, bool $destination = false): void { $this->expectException(RepositoryException::class); @@ -46,12 +49,15 @@ public function testAssertInvalidAbsolutePath($path, $destination = false): void /** * @dataProvider dataproviderValidAbsolutePathsWithNamespaces */ - public function testAssertAbsolutePathNamespace($path): void + public function testAssertAbsolutePathNamespace(string $path): void { $this->assertTrue(PathHelper::assertValidAbsolutePath($path, false, true, ['jcr', 'nt'])); } - public function dataproviderValidAbsolutePathsWithNamespaces() + /** + * @return array + */ + public function dataproviderValidAbsolutePathsWithNamespaces(): array { return [ ['/parent/child'], @@ -77,12 +83,15 @@ public function testAssertInvalidNamespaceAbsolutePath(): void /** * @dataProvider dataproviderInvalidAbsolutePaths */ - public function testAssertInvalidAbsolutePathNoThrow($path, $destination = false): void + public function testAssertInvalidAbsolutePathNoThrow(string $path, bool $destination = false): void { $this->assertFalse(PathHelper::assertValidAbsolutePath($path, $destination, false)); } - public function dataproviderInvalidAbsolutePaths() + /** + * @return array + */ + public function dataproviderInvalidAbsolutePaths(): array { return [ ['/parent/child[7]', true], // destination last element with index @@ -110,14 +119,17 @@ public function testAssertValidLocalNameRootnode(): void /** * @dataProvider dataproviderInvalidLocalNames */ - public function testAssertInvalidLocalName($name): void + public function testAssertInvalidLocalName(string $name): void { $this->expectException(RepositoryException::class); PathHelper::assertValidLocalName($name); } - public function dataproviderInvalidLocalNames() + /** + * @return array + */ + public static function dataproviderInvalidLocalNames(): array { return [ ['jcr:nodename'], @@ -132,12 +144,15 @@ public function dataproviderInvalidLocalNames() /** * @dataProvider dataproviderNormalizePath */ - public function testNormalizePath($inputPath, $outputPath): void + public function testNormalizePath(string $inputPath, string $outputPath): void { $this->assertSame($outputPath, PathHelper::normalizePath($inputPath)); } - public static function dataproviderNormalizePath() + /** + * @return array + */ + public static function dataproviderNormalizePath(): array { return [ ['/', '/'], @@ -151,7 +166,7 @@ public static function dataproviderNormalizePath() /** * @dataProvider dataproviderNormalizePathInvalid */ - public function testNormalizePathInvalidThrow($input): void + public function testNormalizePathInvalidThrow(string $input): void { $this->expectException(RepositoryException::class); @@ -161,12 +176,15 @@ public function testNormalizePathInvalidThrow($input): void /** * @dataProvider dataproviderNormalizePathInvalid */ - public function testNormalizePathInvalidNoThrow($input): void + public function testNormalizePathInvalidNoThrow(string $input): void { $this->assertFalse(PathHelper::normalizePath($input, true, false)); } - public static function dataproviderNormalizePathInvalid() + /** + * @return array + */ + public static function dataproviderNormalizePathInvalid(): array { return [ ['foo/bar'], @@ -187,6 +205,9 @@ public function testAbsolutizePath(string $inputPath, string $context, string $o $this->assertSame($outputPath, PathHelper::absolutizePath($inputPath, $context)); } + /** + * @return array + */ public static function dataproviderAbsolutizePath(): array { return [ @@ -200,7 +221,7 @@ public static function dataproviderAbsolutizePath(): array /** * @dataProvider dataproviderAbsolutizePathInvalid */ - public function testAbsolutizePathInvalidThrow($inputPath, $context, $target): void + public function testAbsolutizePathInvalidThrow(string $inputPath, string $context, bool $target): void { $this->expectException(RepositoryException::class); PathHelper::absolutizePath($inputPath, $context, $target); @@ -209,12 +230,15 @@ public function testAbsolutizePathInvalidThrow($inputPath, $context, $target): v /** * @dataProvider dataproviderAbsolutizePathInvalid */ - public function testAbsolutizePathInvalidNoThrow($inputPath, $context, $target): void + public function testAbsolutizePathInvalidNoThrow(string $inputPath, string $context, bool $target): void { $this->assertFalse(PathHelper::absolutizePath($inputPath, $context, $target, false)); } - public static function dataproviderAbsolutizePathInvalid() + /** + * @return array + */ + public static function dataproviderAbsolutizePathInvalid(): array { return [ ['', '/context', false], @@ -229,12 +253,15 @@ public static function dataproviderAbsolutizePathInvalid() /** * @dataProvider dataproviderRelativizePath */ - public function testRelativizePath($inputPath, $context, $outputPath): void + public function testRelativizePath(string $inputPath, string $context, string $outputPath): void { $this->assertSame($outputPath, PathHelper::relativizePath($inputPath, $context)); } - public static function dataproviderRelativizePath() + /** + * @return array + */ + public static function dataproviderRelativizePath(): array { return [ ['/parent/path/child', '/parent', 'path/child'], @@ -245,7 +272,7 @@ public static function dataproviderRelativizePath() /** * @dataProvider dataproviderRelativizePathInvalid */ - public function testRelativizePathInvalidThrow($inputPath, $context): void + public function testRelativizePathInvalidThrow(string $inputPath, string $context): void { $this->expectException(RepositoryException::class); @@ -255,12 +282,15 @@ public function testRelativizePathInvalidThrow($inputPath, $context): void /** * @dataProvider dataproviderRelativizePathInvalid */ - public function testRelativizePathInvalidNoThrow($inputPath, $context): void + public function testRelativizePathInvalidNoThrow(string $inputPath, string $context): void { $this->assertFalse(PathHelper::relativizePath($inputPath, $context, false)); } - public static function dataproviderRelativizePathInvalid() + /** + * @return array + */ + public static function dataproviderRelativizePathInvalid(): array { return [ ['/path', '/context'], @@ -273,12 +303,15 @@ public static function dataproviderRelativizePathInvalid() /** * @dataProvider dataproviderParentPath */ - public function testGetParentPath($path, $parent): void + public function testGetParentPath(string $path, string $parent): void { $this->assertEquals($parent, PathHelper::getParentPath($path)); } - public function dataproviderParentPath() + /** + * @return array + */ + public function dataproviderParentPath(): array { return [ ['/parent/child', '/parent'], @@ -293,12 +326,15 @@ public function dataproviderParentPath() /** * @dataProvider dataproviderGetNodeName */ - public function testGetNodeName($path, $expected = null): void + public function testGetNodeName(string $path, string $expected): void { $this->assertEquals($expected, PathHelper::getNodeName($path)); } - public function dataproviderGetNodeName() + /** + * @return array + */ + public function dataproviderGetNodeName(): array { return [ ['/parent/child', 'child'], @@ -310,12 +346,15 @@ public function dataproviderGetNodeName() /** * @dataProvider dataproviderGetLocalNodeName */ - public function testGetLocalNodeName($path, $expected = null): void + public function testGetLocalNodeName(string $path, string $expected): void { $this->assertEquals($expected, PathHelper::getLocalNodeName($path)); } - public function dataproviderGetLocalNodeName() + /** + * @return array + */ + public function dataproviderGetLocalNodeName(): array { return [ ['/parent/child', 'child'], @@ -339,12 +378,15 @@ public function testGetNodeNameMustBeAbsolute(): void /** * @dataProvider dataproviderPathDepth */ - public function testGetPathDepth($path, $depth): void + public function testGetPathDepth(string $path, int $depth): void { $this->assertEquals($depth, PathHelper::getPathDepth($path)); } - public function dataproviderPathDepth() + /** + * @return array + */ + public function dataproviderPathDepth(): array { return [ ['/', 0], diff --git a/tests/PHPCR/Tests/Util/QOM/QueryBuilderTest.php b/tests/PHPCR/Tests/Util/QOM/QueryBuilderTest.php index 40aff3cb..b89f7e2a 100644 --- a/tests/PHPCR/Tests/Util/QOM/QueryBuilderTest.php +++ b/tests/PHPCR/Tests/Util/QOM/QueryBuilderTest.php @@ -19,7 +19,7 @@ class QueryBuilderTest extends TestCase { /** - * @var MockObject|QueryObjectModelFactoryInterface + * @var QueryObjectModelFactoryInterface&MockObject */ protected $qf; @@ -331,11 +331,10 @@ public function testGetQuery(): void } /** - * @return QueryObjectModelInterface|MockObject + * @return QueryObjectModelInterface&MockObject */ private function createQueryMock() { - /** @var QueryObjectModelInterface $query */ $query = $this->getMockBuilder(QueryObjectModelInterface::class) ->setMethods([]) ->setConstructorArgs([]) diff --git a/tests/PHPCR/Tests/Util/QOM/Sql2ScannerTest.php b/tests/PHPCR/Tests/Util/QOM/Sql2ScannerTest.php index 9b6ea95e..9918d94b 100644 --- a/tests/PHPCR/Tests/Util/QOM/Sql2ScannerTest.php +++ b/tests/PHPCR/Tests/Util/QOM/Sql2ScannerTest.php @@ -51,6 +51,9 @@ public function testStringTokenization(string $query): void $this->expectTokensFromScanner($scanner, $expected); } + /** + * @return array + */ public function dataTestStringTokenization(): array { $multilineQuery = <<<'SQL' diff --git a/tests/PHPCR/Tests/Util/ValueConverterTest.php b/tests/PHPCR/Tests/Util/ValueConverterTest.php index 4b871944..28f0b87c 100644 --- a/tests/PHPCR/Tests/Util/ValueConverterTest.php +++ b/tests/PHPCR/Tests/Util/ValueConverterTest.php @@ -25,25 +25,33 @@ public function setUp(): void $this->valueConverter = new ValueConverter(); } + /** + * @return array + */ public function dataConversionMatrix(): array { $stream = fopen('php://memory', '+rw'); + $this->assertIsResource($stream); fwrite($stream, 'test string'); rewind($stream); $dateStream = fopen('php://memory', '+rw'); + $this->assertIsResource($dateStream); fwrite($dateStream, '17.12.2010 GMT'); rewind($dateStream); $numberStream = fopen('php://memory', '+rw'); + $this->assertIsResource($numberStream); fwrite($numberStream, '123.456'); rewind($numberStream); $nameStream = fopen('php://memory', '+rw'); + $this->assertIsResource($nameStream); fwrite($nameStream, 'test'); rewind($nameStream); $uuidStream = fopen('php://memory', '+rw'); + $this->assertIsResource($uuidStream); fwrite($uuidStream, '38b7cf18-c417-477a-af0b-c1e92a290c9a'); rewind($uuidStream); @@ -305,10 +313,12 @@ public function testConvertTypeToBinary(): void $stream = $this->valueConverter->convertType($date, PropertyType::BINARY); $this->assertIsResource($stream); $string = stream_get_contents($stream); + $this->assertIsString($string); $readDate = new \DateTime($string); $this->assertEquals($date->getTimestamp(), $readDate->getTimestamp()); $stream = fopen('php://memory', '+rwb'); + $this->assertIsResource($stream); fwrite($stream, 'test string'); rewind($stream); From e3697403b27cea36f95cbc479a6a7a9b2bdfa2d4 Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Sat, 2 Dec 2023 11:08:31 +0100 Subject: [PATCH 08/13] prepare release --- CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8fde3596..1c4803f8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,8 +4,8 @@ Changelog 2.x --- -2.0.0 (unreleased) ------------------- +2.0.0 +----- * Support Symfony 7 * Drop support for Symfony 2 From aed4c29598141336f95a151d9780490c292b8a8d Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Sat, 2 Dec 2023 11:11:42 +0100 Subject: [PATCH 09/13] cleanup phpstan --- phpstan.tests.neon.dist | 11 ----------- tests/PHPCR/Tests/Stubs/MockNodeTypeManager.php | 2 +- 2 files changed, 1 insertion(+), 12 deletions(-) diff --git a/phpstan.tests.neon.dist b/phpstan.tests.neon.dist index b4deb820..d7889e1f 100644 --- a/phpstan.tests.neon.dist +++ b/phpstan.tests.neon.dist @@ -8,17 +8,6 @@ parameters: - tests/*/Fixtures/* ignoreErrors: - # not sure what is going on here - - - message: "#^Interface Iterator specifies template type TKey of interface Traversable as string but it's already specified as mixed\\.$#" - count: 1 - path: tests/PHPCR/Tests/Stubs/MockNodeTypeManager.php - - - - message: "#^Interface Iterator specifies template type TValue of interface Traversable as PHPCR\\\\NodeType\\\\NodeTypeInterface but it's already specified as mixed\\.$#" - count: 1 - path: tests/PHPCR/Tests/Stubs/MockNodeTypeManager.php - # too pedantic for tests - message: "#^Parameter \\#1 \\.\\.\\.\\$arrays of function array_merge expects array, array\\\\|false given\\.$#" diff --git a/tests/PHPCR/Tests/Stubs/MockNodeTypeManager.php b/tests/PHPCR/Tests/Stubs/MockNodeTypeManager.php index 468fe9d4..f3fe1df2 100644 --- a/tests/PHPCR/Tests/Stubs/MockNodeTypeManager.php +++ b/tests/PHPCR/Tests/Stubs/MockNodeTypeManager.php @@ -8,7 +8,7 @@ use PHPCR\NodeType\NodeTypeManagerInterface; /** - * @implements \Iterator + * @implements \Iterator */ abstract class MockNodeTypeManager implements \Iterator, NodeTypeManagerInterface { From 7b1cbcea67e0d26cdf3c983c730ea6b0acec3d6d Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Fri, 12 Jan 2024 14:41:14 +0100 Subject: [PATCH 10/13] escape single quotes in sql generator --- CHANGELOG.md | 7 +++++++ src/PHPCR/Util/QOM/BaseSqlGenerator.php | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1c4803f8..12aba85f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,13 @@ Changelog 2.x --- +2.0.1 +----- + +* The SQL generator now escapes single quotes `'`. This avoids SQL injection risks. If you escaped + strings manually (by duplicating the `'`) you will need to stop doing that as otherwise the query + will be run with duplicated single quotes. + 2.0.0 ----- diff --git a/src/PHPCR/Util/QOM/BaseSqlGenerator.php b/src/PHPCR/Util/QOM/BaseSqlGenerator.php index 2215ec74..98851fc7 100644 --- a/src/PHPCR/Util/QOM/BaseSqlGenerator.php +++ b/src/PHPCR/Util/QOM/BaseSqlGenerator.php @@ -214,7 +214,7 @@ public function evalLiteral(mixed $literal): string return $this->evalCastLiteral($string, 'DOUBLE'); } - return "'$literal'"; + return sprintf("'%s'", str_replace("'", "''", $literal)); } /** From 36c0654e1fac8a0a0ce1dea274c655a3c0b63646 Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Mon, 8 Apr 2024 11:20:46 +0200 Subject: [PATCH 11/13] cs fixer for php 8.3 --- src/PHPCR/Util/CND/Parser/AbstractParser.php | 6 ++--- src/PHPCR/Util/CND/Scanner/TokenQueue.php | 2 +- src/PHPCR/Util/NodeHelper.php | 2 +- .../Util/QOM/BaseQomToSqlQueryConverter.php | 4 ++-- src/PHPCR/Util/QOM/BaseSqlGenerator.php | 12 +++++----- src/PHPCR/Util/QOM/QueryBuilder.php | 4 ++-- src/PHPCR/Util/QOM/Sql1Generator.php | 12 +++++----- src/PHPCR/Util/QOM/Sql2Generator.php | 22 +++++++++---------- .../Util/QOM/Sql2ToQomQueryConverter.php | 6 ++--- src/PHPCR/Util/TreeWalker.php | 2 +- 10 files changed, 36 insertions(+), 36 deletions(-) diff --git a/src/PHPCR/Util/CND/Parser/AbstractParser.php b/src/PHPCR/Util/CND/Parser/AbstractParser.php index ace8eb21..638013fb 100644 --- a/src/PHPCR/Util/CND/Parser/AbstractParser.php +++ b/src/PHPCR/Util/CND/Parser/AbstractParser.php @@ -31,7 +31,7 @@ abstract class AbstractParser * If the data is not provided (equal to null) then only the token type is checked. * Return false otherwise. */ - protected function checkToken(int $type, string $data = null, bool $ignoreCase = false): bool + protected function checkToken(int $type, ?string $data = null, bool $ignoreCase = false): bool { if ($this->tokenQueue->isEof()) { return false; @@ -79,7 +79,7 @@ protected function checkTokenIn(int $type, array $data, bool $ignoreCase = false * * @throws ParserException */ - protected function expectToken(int $type, string $data = null): Token + protected function expectToken(int $type, ?string $data = null): Token { $token = $this->tokenQueue->peek(); @@ -99,7 +99,7 @@ protected function expectToken(int $type, string $data = null): Token * @param int $type The expected token type * @param string|null $data The expected token data or null */ - protected function checkAndExpectToken(int $type, string $data = null): false|Token + protected function checkAndExpectToken(int $type, ?string $data = null): false|Token { if ($this->checkToken($type, $data)) { $token = $this->tokenQueue->peek(); diff --git a/src/PHPCR/Util/CND/Scanner/TokenQueue.php b/src/PHPCR/Util/CND/Scanner/TokenQueue.php index 38c7fad0..08bf6020 100644 --- a/src/PHPCR/Util/CND/Scanner/TokenQueue.php +++ b/src/PHPCR/Util/CND/Scanner/TokenQueue.php @@ -54,7 +54,7 @@ public function peek($offset = 0): Token|false return $this->tokens[key($this->tokens) + $offset]; } - public function get($count = 1): Token|null + public function get($count = 1): ?Token { $item = null; for ($i = 1; $i <= $count; ++$i) { diff --git a/src/PHPCR/Util/NodeHelper.php b/src/PHPCR/Util/NodeHelper.php index 97924878..cccbc05f 100644 --- a/src/PHPCR/Util/NodeHelper.php +++ b/src/PHPCR/Util/NodeHelper.php @@ -137,7 +137,7 @@ public static function isSystemItem(ItemInterface $item): bool * $nameHint which does not exist and this implementation performs * this validation immediately */ - public static function generateAutoNodeName(array $usedNames, array $namespaces, string $defaultNamespace, string $nameHint = null): string + public static function generateAutoNodeName(array $usedNames, array $namespaces, string $defaultNamespace, ?string $nameHint = null): string { $usedNames = array_flip($usedNames); diff --git a/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php b/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php index f9444b71..928ac90f 100644 --- a/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php +++ b/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php @@ -130,7 +130,7 @@ protected function convertFullTextSearch(QOM\FullTextSearchInterface $constraint /** * FullTextSearchExpression ::= BindVariable | ''' FullTextSearchLiteral '''. * - * @param string|QOM\StaticOperandInterface $expr + * @param string|StaticOperandInterface $expr */ protected function convertFullTextSearchExpression($expr): string { @@ -169,7 +169,7 @@ protected function convertFullTextSearchExpression($expr): string * * @throws \InvalidArgumentException */ - protected function convertStaticOperand(QOM\StaticOperandInterface $operand): string + protected function convertStaticOperand(StaticOperandInterface $operand): string { if ($operand instanceof QOM\BindVariableValueInterface) { return $this->convertBindVariable($operand->getBindVariableName()); diff --git a/src/PHPCR/Util/QOM/BaseSqlGenerator.php b/src/PHPCR/Util/QOM/BaseSqlGenerator.php index 98851fc7..365d625f 100644 --- a/src/PHPCR/Util/QOM/BaseSqlGenerator.php +++ b/src/PHPCR/Util/QOM/BaseSqlGenerator.php @@ -228,7 +228,7 @@ abstract public function evalCastLiteral(string $literal, string $type): string; * @param string|null $selectorName The selector name. If it is different than the nodeTypeName, the alias is * declared if supported by the SQL dialect. */ - abstract public function evalSelector(string $nodeTypeName, string $selectorName = null): string; + abstract public function evalSelector(string $nodeTypeName, ?string $selectorName = null): string; /** * Evaluate a path. This is different between SQL1 and SQL2. @@ -244,15 +244,15 @@ abstract public function evalPath(string $path): string; */ abstract public function evalColumns(iterable $columns): string; - abstract public function evalColumn(string $selectorName, string $propertyName = null, string $colname = null): string; + abstract public function evalColumn(string $selectorName, ?string $propertyName = null, ?string $colname = null): string; abstract public function evalPropertyExistence(?string $selectorName, string $propertyName): string; - abstract public function evalPropertyValue(string $propertyName, string $selectorName = null); + abstract public function evalPropertyValue(string $propertyName, ?string $selectorName = null); - abstract public function evalChildNode(string $path, string $selectorName = null); + abstract public function evalChildNode(string $path, ?string $selectorName = null); - abstract public function evalDescendantNode(string $path, string $selectorName = null): string; + abstract public function evalDescendantNode(string $path, ?string $selectorName = null): string; - abstract public function evalFullTextSearch(string $selectorName, string $searchExpression, string $propertyName = null): string; + abstract public function evalFullTextSearch(string $selectorName, string $searchExpression, ?string $propertyName = null): string; } diff --git a/src/PHPCR/Util/QOM/QueryBuilder.php b/src/PHPCR/Util/QOM/QueryBuilder.php index f29faa9c..1018e7e0 100644 --- a/src/PHPCR/Util/QOM/QueryBuilder.php +++ b/src/PHPCR/Util/QOM/QueryBuilder.php @@ -296,7 +296,7 @@ public function setColumns(array $columns): static * Identifies a property in the specified or default selector to include in the tabular view of query results. * Replaces any previously specified columns to be selected if any. */ - public function select(string $selectorName, string $propertyName, string $columnName = null): static + public function select(string $selectorName, string $propertyName, ?string $columnName = null): static { $this->state = self::STATE_DIRTY; $this->columns = [$this->qomFactory->column($selectorName, $propertyName, $columnName)]; @@ -307,7 +307,7 @@ public function select(string $selectorName, string $propertyName, string $colum /** * Adds a property in the specified or default selector to include in the tabular view of query results. */ - public function addSelect(string $selectorName, string $propertyName, string $columnName = null): static + public function addSelect(string $selectorName, string $propertyName, ?string $columnName = null): static { $this->state = self::STATE_DIRTY; diff --git a/src/PHPCR/Util/QOM/Sql1Generator.php b/src/PHPCR/Util/QOM/Sql1Generator.php index bcd7b936..452a164c 100644 --- a/src/PHPCR/Util/QOM/Sql1Generator.php +++ b/src/PHPCR/Util/QOM/Sql1Generator.php @@ -19,7 +19,7 @@ class Sql1Generator extends BaseSqlGenerator * @param string $nodeTypeName The node type of the selector. If it does not contain starting and ending brackets ([]) they will be added automatically * @param string|null $selectorName (unused) */ - public function evalSelector(string $nodeTypeName, string $selectorName = null): string + public function evalSelector(string $nodeTypeName, ?string $selectorName = null): string { return $nodeTypeName; } @@ -43,7 +43,7 @@ protected function getPathForDescendantQuery(string $path): string /** * SameNode ::= 'jcr:path like Path/% and not jcr:path like Path/%/%'. */ - public function evalChildNode(string $path, string $selectorName = null): string + public function evalChildNode(string $path, ?string $selectorName = null): string { $path = $this->getPathForDescendantQuery($path); $sql1 = "jcr:path LIKE '".$path."'"; @@ -57,7 +57,7 @@ public function evalChildNode(string $path, string $selectorName = null): string * * @param string|null $selectorName Unused */ - public function evalDescendantNode(string $path, string $selectorName = null): string + public function evalDescendantNode(string $path, ?string $selectorName = null): string { $path = $this->getPathForDescendantQuery($path); @@ -84,7 +84,7 @@ public function evalPropertyExistence(?string $selectorName, string $propertyNam * * @param string $selectorName unusued */ - public function evalFullTextSearch(string $selectorName, string $searchExpression, string $propertyName = null): string + public function evalFullTextSearch(string $selectorName, string $searchExpression, ?string $propertyName = null): string { $propertyName = $propertyName ?: '*'; @@ -123,7 +123,7 @@ public function evalColumns(iterable $columns): string * * @param string|null $selectorName unused in SQL1 */ - public function evalPropertyValue(string $propertyName, string $selectorName = null): string + public function evalPropertyValue(string $propertyName, ?string $selectorName = null): string { return $propertyName; } @@ -137,7 +137,7 @@ public function evalPropertyValue(string $propertyName, string $selectorName = n * @param string $selectorName unused in SQL1 * @param string|null $colname unused in SQL1 */ - public function evalColumn(string $selectorName, string $propertyName = null, string $colname = null): string + public function evalColumn(string $selectorName, ?string $propertyName = null, ?string $colname = null): string { return $propertyName; } diff --git a/src/PHPCR/Util/QOM/Sql2Generator.php b/src/PHPCR/Util/QOM/Sql2Generator.php index e3278488..7c042f1d 100644 --- a/src/PHPCR/Util/QOM/Sql2Generator.php +++ b/src/PHPCR/Util/QOM/Sql2Generator.php @@ -24,7 +24,7 @@ class Sql2Generator extends BaseSqlGenerator * @param string|null $selectorName The selector name. If it is different than * the nodeTypeName, the alias is declared. */ - public function evalSelector(string $nodeTypeName, string $selectorName = null): string + public function evalSelector(string $nodeTypeName, ?string $selectorName = null): string { $sql2 = $this->addBracketsIfNeeded($nodeTypeName); @@ -83,7 +83,7 @@ public function evalEquiJoinCondition(string $sel1Name, string $prop1Name, strin * [',' selector2Path] ')' * selector2Path ::= Path. */ - public function evalSameNodeJoinCondition(string $sel1Name, string $sel2Name, string $sel2Path = null): string + public function evalSameNodeJoinCondition(string $sel1Name, string $sel2Name, ?string $sel2Path = null): string { $sql2 = 'ISSAMENODE(' .$this->addBracketsIfNeeded($sel1Name).', ' @@ -127,7 +127,7 @@ public function evalDescendantNodeJoinCondition(string $descendantSelectorName, /** * SameNode ::= 'ISSAMENODE(' [selectorName ','] Path ')'. */ - public function evalSameNode(string $path, string $selectorName = null): string + public function evalSameNode(string $path, ?string $selectorName = null): string { $sql2 = 'ISSAMENODE('; $sql2 .= null === $selectorName ? $path : $this->addBracketsIfNeeded($selectorName).', '.$path; @@ -139,7 +139,7 @@ public function evalSameNode(string $path, string $selectorName = null): string /** * SameNode ::= 'ISCHILDNODE(' [selectorName ','] Path ')'. */ - public function evalChildNode(string $path, string $selectorName = null): string + public function evalChildNode(string $path, ?string $selectorName = null): string { $sql2 = 'ISCHILDNODE('; $sql2 .= null === $selectorName ? $path : $this->addBracketsIfNeeded($selectorName).', '.$path; @@ -151,7 +151,7 @@ public function evalChildNode(string $path, string $selectorName = null): string /** * SameNode ::= 'ISDESCENDANTNODE(' [selectorName ','] Path ')'. */ - public function evalDescendantNode(string $path, string $selectorName = null): string + public function evalDescendantNode(string $path, ?string $selectorName = null): string { $sql2 = 'ISDESCENDANTNODE('; $sql2 .= null === $selectorName ? $path : $this->addBracketsIfNeeded($selectorName).', '.$path; @@ -179,7 +179,7 @@ public function evalPropertyExistence(?string $selectorName, string $propertyNam * FullTextSearchExpression ')' * FullTextSearchExpression ::= BindVariable | ''' FullTextSearchLiteral '''. */ - public function evalFullTextSearch(string $selectorName, string $searchExpression, string $propertyName = null): string + public function evalFullTextSearch(string $selectorName, string $searchExpression, ?string $propertyName = null): string { $propertyName = $propertyName ?: '*'; @@ -201,7 +201,7 @@ public function evalLength(string $propertyValue): string /** * NodeName ::= 'NAME(' [selectorName] ')'. */ - public function evalNodeName(string $selectorValue = null): string + public function evalNodeName(?string $selectorValue = null): string { return "NAME($selectorValue)"; } @@ -209,7 +209,7 @@ public function evalNodeName(string $selectorValue = null): string /** * NodeLocalName ::= 'LOCALNAME(' [selectorName] ')'. */ - public function evalNodeLocalName(string $selectorValue = null): string + public function evalNodeLocalName(?string $selectorValue = null): string { return "LOCALNAME($selectorValue)"; } @@ -217,7 +217,7 @@ public function evalNodeLocalName(string $selectorValue = null): string /** * FullTextSearchScore ::= 'SCORE(' [selectorName] ')'. */ - public function evalFullTextSearchScore(string $selectorValue = null): string + public function evalFullTextSearchScore(?string $selectorValue = null): string { return "SCORE($selectorValue)"; } @@ -225,7 +225,7 @@ public function evalFullTextSearchScore(string $selectorValue = null): string /** * PropertyValue ::= [selectorName'.'] propertyName // If only one selector exists. */ - public function evalPropertyValue(string $propertyName, string $selectorName = null): string + public function evalPropertyValue(string $propertyName, ?string $selectorName = null): string { $sql2 = null !== $selectorName ? $this->addBracketsIfNeeded($selectorName).'.' : ''; if ('*' !== $propertyName && !str_starts_with($propertyName, '[')) { @@ -267,7 +267,7 @@ public function evalColumns(iterable $columns): string * propertyName ::= Name * columnName ::= Name. */ - public function evalColumn(string $selectorName, string $propertyName = null, string $colname = null): string + public function evalColumn(string $selectorName, ?string $propertyName = null, ?string $colname = null): string { $sql2 = ''; if (null !== $selectorName && null === $propertyName && null === $colname) { diff --git a/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php b/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php index bb1e88b4..e0bd27b3 100644 --- a/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php +++ b/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php @@ -61,7 +61,7 @@ class Sql2ToQomQueryConverter /** * @param ValueConverter|null $valueConverter to override default converter */ - public function __construct(QueryObjectModelFactoryInterface $factory, ValueConverter $valueConverter = null) + public function __construct(QueryObjectModelFactoryInterface $factory, ?ValueConverter $valueConverter = null) { $this->factory = $factory; $this->valueConverter = $valueConverter ?: new ValueConverter(); @@ -313,7 +313,7 @@ protected function parseDescendantNodeJoinCondition(): DescendantNodeJoinConditi * * @throws \Exception */ - protected function parseConstraint(ConstraintInterface $lhs = null, int $minprec = 0): ConstraintInterface|null + protected function parseConstraint(?ConstraintInterface $lhs = null, int $minprec = 0): ?ConstraintInterface { if (null === $lhs) { $lhs = $this->parsePrimaryConstraint(); @@ -924,7 +924,7 @@ protected function updateImplicitSelectorName(string $selectorName): void * @throws InvalidQueryException if there was no explicit selector and * there is more than one selector available */ - protected function ensureSelectorName(?string $parsedName): string|null + protected function ensureSelectorName(?string $parsedName): ?string { if (null !== $parsedName) { if ((is_array($this->implicitSelectorName) && !isset($this->implicitSelectorName[$parsedName])) diff --git a/src/PHPCR/Util/TreeWalker.php b/src/PHPCR/Util/TreeWalker.php index 723b54ba..0588c94d 100644 --- a/src/PHPCR/Util/TreeWalker.php +++ b/src/PHPCR/Util/TreeWalker.php @@ -39,7 +39,7 @@ class TreeWalker * @param ItemVisitorInterface $nodeVisitor The visitor for the nodes * @param ItemVisitorInterface|null $propertyVisitor The visitor for the nodes properties */ - public function __construct(ItemVisitorInterface $nodeVisitor, ItemVisitorInterface $propertyVisitor = null) + public function __construct(ItemVisitorInterface $nodeVisitor, ?ItemVisitorInterface $propertyVisitor = null) { $this->nodeVisitor = $nodeVisitor; $this->propertyVisitor = $propertyVisitor; From 705baa543b506ecc1ae8305f5065d8fffb921f99 Mon Sep 17 00:00:00 2001 From: Alexander Schranz Date: Mon, 8 Apr 2024 14:18:01 +0200 Subject: [PATCH 12/13] Change native return type for QueryObjectModelInterface::getQuery --- src/PHPCR/Util/QOM/QueryBuilder.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/PHPCR/Util/QOM/QueryBuilder.php b/src/PHPCR/Util/QOM/QueryBuilder.php index 1018e7e0..046bc872 100644 --- a/src/PHPCR/Util/QOM/QueryBuilder.php +++ b/src/PHPCR/Util/QOM/QueryBuilder.php @@ -400,7 +400,7 @@ public function joinWithType(SourceInterface $rightSource, string $joinType, Joi /** * Gets the query built. */ - public function getQuery(): ?QueryObjectModelInterface + public function getQuery(): QueryObjectModelInterface { if (null !== $this->query && self::STATE_CLEAN === $this->state) { return $this->query; From e24912e58269f7d7c859b9c607262545066a60f7 Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Tue, 9 Apr 2024 16:46:42 +0200 Subject: [PATCH 13/13] prepare release --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 12aba85f..c560bbc8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,11 @@ Changelog 2.x --- +2.0.2 +----- + +* Return type for `PHPCR\Util\QOM\QueryBuilder::getQuery` is not nullable. + 2.0.1 -----