From 3336281eaa8cd1caceda5ceff10a66cf7744e977 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Miko=C5=82ajczuk?= Date: Wed, 28 Sep 2016 16:28:06 +0100 Subject: [PATCH 01/88] fix string to array conversion issue - it breaks on php 7.1 --- .travis.yml | 2 ++ composer.json | 2 +- src/PHPCR/Util/QOM/Sql2Scanner.php | 6 +++--- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index 575f3aa..92355f9 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,6 +4,8 @@ php: - 5.4 - 5.5 - 5.6 + - 7.0 + - 7.1 - hhvm env: diff --git a/composer.json b/composer.json index 2c41288..9892dbe 100644 --- a/composer.json +++ b/composer.json @@ -27,7 +27,7 @@ } ], "require": { - "php": ">=5.3.3", + "php": "^5.3.3|7.0.x|7.1.x", "phpcr/phpcr": "~2.1.0", "symfony/console": "~2.3|~3.0" }, diff --git a/src/PHPCR/Util/QOM/Sql2Scanner.php b/src/PHPCR/Util/QOM/Sql2Scanner.php index ac9a51c..10524be 100644 --- a/src/PHPCR/Util/QOM/Sql2Scanner.php +++ b/src/PHPCR/Util/QOM/Sql2Scanner.php @@ -159,12 +159,12 @@ protected function scan($sql2) $token = strtok(" \n\t"); } - $regexp = ''; + $regexpTokens = array(); foreach ($tokens as $token) { - $regexp[] = preg_quote($token, '/'); + $regexpTokens[] = preg_quote($token, '/'); } - $regexp = '/^'.implode('([ \t\n]+)', $regexp).'$/'; + $regexp = '/^'.implode('([ \t\n]+)', $regexpTokens).'$/'; preg_match($regexp, $sql2, $this->delimiters); $this->delimiters[0] = ''; From 1b0751ffc22cb788523734ebeef1726f8eaeea4e Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Fri, 30 Sep 2016 14:41:39 +0200 Subject: [PATCH 02/88] fix case error --- .travis.yml | 3 +++ tests/PHPCR/Tests/Util/ValueConverterTest.php | 4 ++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 92355f9..2692e18 100644 --- a/.travis.yml +++ b/.travis.yml @@ -17,6 +17,9 @@ matrix: include: - php: 5.3 env: PACKAGE_VERSION=low + allow_failures: + - php: 7.0 + - php: 7.1 before_script: - composer selfupdate diff --git a/tests/PHPCR/Tests/Util/ValueConverterTest.php b/tests/PHPCR/Tests/Util/ValueConverterTest.php index a4f5a86..48fe04a 100644 --- a/tests/PHPCR/Tests/Util/ValueConverterTest.php +++ b/tests/PHPCR/Tests/Util/ValueConverterTest.php @@ -52,7 +52,7 @@ public function dataConversionMatrix() ; $nodemock ->expects($this->any()) - ->method('isNodetype') + ->method('isNodeType') ->with('mix:referenceable') ->will($this->returnValue(true)) ; @@ -406,7 +406,7 @@ public function testConvertNonrefNode() ; $nodemock ->expects($this->once()) - ->method('isNodetype') + ->method('isNodeType') ->with('mix:referenceable') ->will($this->returnValue(false)) ; From 4273dd638e4ccca897712e0e2d66b8a92112b72d Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Tue, 6 Dec 2016 00:25:43 +0100 Subject: [PATCH 03/88] php 7 should not be allowed to fail --- .travis.yml | 3 --- 1 file changed, 3 deletions(-) diff --git a/.travis.yml b/.travis.yml index 2692e18..92355f9 100644 --- a/.travis.yml +++ b/.travis.yml @@ -17,9 +17,6 @@ matrix: include: - php: 5.3 env: PACKAGE_VERSION=low - allow_failures: - - php: 7.0 - - php: 7.1 before_script: - composer selfupdate From f212d3f27cce243de90d037c9d71135a27889d5f Mon Sep 17 00:00:00 2001 From: ElectricMaxxx Date: Mon, 5 Dec 2016 23:50:40 +0100 Subject: [PATCH 04/88] fix test --- .../Util/Console/Command/NodeDumpCommandTest.php | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/tests/PHPCR/Tests/Util/Console/Command/NodeDumpCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodeDumpCommandTest.php index 19c9844..e2c5c34 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodeDumpCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodeDumpCommandTest.php @@ -70,14 +70,13 @@ public function testCommandIdentifier() $this->executeCommand('phpcr:node:dump', array('identifier' => $uuid)); } + /** + * @expectedException \Exception + */ public function testInvalidRefFormat() { - try { - $this->executeCommand('phpcr:node:dump', array('--ref-format' => 'xy')); - $this->fail('invalid ref-format did not produce exception'); - } catch (\Exception $e) { - // success - } + $this->executeCommand('phpcr:node:dump', array('--ref-format' => 'xy')); + $this->fail('invalid ref-format did not produce exception'); } public function testNotFound() From 000848fcef35d334201c1cee4080f5da0ab43909 Mon Sep 17 00:00:00 2001 From: Pavel Vondrasek Date: Fri, 20 Jan 2017 11:22:16 +0100 Subject: [PATCH 05/88] small cleanup --- bin/phpcr | 41 +++++++++++-------- composer.json | 3 ++ .../Command/NodeTypeRegisterCommand.php | 17 ++++---- .../Command/WorkspaceImportCommand.php | 2 +- src/PHPCR/Util/Console/Helper/PhpcrHelper.php | 3 +- .../TreeDumper/ConsoleDumperNodeVisitor.php | 7 +++- .../ConsoleDumperPropertyVisitor.php | 7 +++- .../Helper/TreeDumper/SystemNodeFilter.php | 3 ++ src/PHPCR/Util/NodeHelper.php | 32 ++++++++++++--- src/PHPCR/Util/PathHelper.php | 8 +++- .../Util/QOM/BaseQomToSqlQueryConverter.php | 6 ++- src/PHPCR/Util/QOM/BaseSqlGenerator.php | 15 ++++++- .../QOM/NotSupportedConstraintException.php | 7 +++- .../Util/QOM/NotSupportedOperandException.php | 7 +++- .../Util/QOM/QomToSql1QueryConverter.php | 16 ++++++-- .../Util/QOM/QomToSql2QueryConverter.php | 20 +++++++-- src/PHPCR/Util/QOM/QueryBuilder.php | 32 +++++++++------ src/PHPCR/Util/QOM/Sql1Generator.php | 2 +- src/PHPCR/Util/QOM/Sql2Generator.php | 1 - src/PHPCR/Util/QOM/Sql2Scanner.php | 4 ++ .../Util/QOM/Sql2ToQomQueryConverter.php | 33 ++++++++++----- src/PHPCR/Util/TraversingItemVisitor.php | 4 +- src/PHPCR/Util/TreeWalker.php | 4 +- src/PHPCR/Util/TreeWalkerFilterInterface.php | 2 +- src/PHPCR/Util/ValueConverter.php | 27 ++++++------ 25 files changed, 210 insertions(+), 93 deletions(-) diff --git a/bin/phpcr b/bin/phpcr index 766fd73..3e49686 100755 --- a/bin/phpcr +++ b/bin/phpcr @@ -1,6 +1,10 @@ #!/usr/bin/env php setCatchExceptions(true); $cli->setHelperSet($helperSet); + $cli->addCommands(array( - new \PHPCR\Util\Console\Command\NodeDumpCommand(), - new \PHPCR\Util\Console\Command\NodeMoveCommand(), - new \PHPCR\Util\Console\Command\NodeRemoveCommand(), - new \PHPCR\Util\Console\Command\NodeTouchCommand(), - new \PHPCR\Util\Console\Command\NodesUpdateCommand(), - new \PHPCR\Util\Console\Command\NodeTypeListCommand(), - new \PHPCR\Util\Console\Command\NodeTypeRegisterCommand(), - new \PHPCR\Util\Console\Command\WorkspaceCreateCommand(), - new \PHPCR\Util\Console\Command\WorkspaceDeleteCommand(), - new \PHPCR\Util\Console\Command\WorkspaceExportCommand(), - new \PHPCR\Util\Console\Command\WorkspaceImportCommand(), - new \PHPCR\Util\Console\Command\WorkspacePurgeCommand(), - new \PHPCR\Util\Console\Command\WorkspaceQueryCommand(), + new Command\NodeDumpCommand(), + new Command\NodeMoveCommand(), + new Command\NodeRemoveCommand(), + new Command\NodeTouchCommand(), + new Command\NodesUpdateCommand(), + new Command\NodeTypeListCommand(), + new Command\NodeTypeRegisterCommand(), + new Command\WorkspaceCreateCommand(), + new Command\WorkspaceDeleteCommand(), + new Command\WorkspaceExportCommand(), + new Command\WorkspaceImportCommand(), + new Command\WorkspacePurgeCommand(), + new Command\WorkspaceQueryCommand(), )); + $cli->run(); diff --git a/composer.json b/composer.json index 9892dbe..070bf5e 100644 --- a/composer.json +++ b/composer.json @@ -31,6 +31,9 @@ "phpcr/phpcr": "~2.1.0", "symfony/console": "~2.3|~3.0" }, + "require-dev": { + "ramsey/uuid": "^3.5" + }, "suggest": { "ramsey/uuid": "A PHP 5.4+ library for generating RFC 4122 version 1, 3, 4, and 5 universally unique identifiers (UUID)." }, diff --git a/src/PHPCR/Util/Console/Command/NodeTypeRegisterCommand.php b/src/PHPCR/Util/Console/Command/NodeTypeRegisterCommand.php index 24727a5..138e400 100644 --- a/src/PHPCR/Util/Console/Command/NodeTypeRegisterCommand.php +++ b/src/PHPCR/Util/Console/Command/NodeTypeRegisterCommand.php @@ -2,9 +2,10 @@ namespace PHPCR\Util\Console\Command; +use InvalidArgumentException; +use PHPCR\RepositoryException; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; -use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use PHPCR\SessionInterface; @@ -62,15 +63,15 @@ protected function configure() /** * {@inheritDoc} + * + * @throws InvalidArgumentException */ protected function execute(InputInterface $input, OutputInterface $output) { $definitions = $input->getArgument('cnd-file'); if (count($definitions) == 0) { - throw new \InvalidArgumentException( - 'At least one definition (i.e. file or folder) must be specified' - ); + throw new InvalidArgumentException('At least one definition (i.e. file or folder) must be specified'); } $allowUpdate = $input->getOption('allow-update'); @@ -99,7 +100,7 @@ protected function execute(InputInterface $input, OutputInterface $output) * @param string $cnd the compact namespace and node type definition in string form * @param bool $allowUpdate whether to allow updating existing node types. * - * @throws \PHPCR\RepositoryException on other errors + * @throws RepositoryException on other errors */ protected function updateFromCnd(OutputInterface $output, SessionInterface $session, $cnd, $allowUpdate) { @@ -124,6 +125,8 @@ protected function updateFromCnd(OutputInterface $output, SessionInterface $sess * @param array $definitions List of files of folders * * @return array Array of full paths to all the type node definition files. + * + * @throws InvalidArgumentException */ protected function getFilePaths($definitions) { @@ -141,7 +144,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) ); } @@ -150,7 +153,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) ); } diff --git a/src/PHPCR/Util/Console/Command/WorkspaceImportCommand.php b/src/PHPCR/Util/Console/Command/WorkspaceImportCommand.php index 1bf356d..e67ff2c 100644 --- a/src/PHPCR/Util/Console/Command/WorkspaceImportCommand.php +++ b/src/PHPCR/Util/Console/Command/WorkspaceImportCommand.php @@ -61,7 +61,7 @@ protected function execute(InputInterface $input, OutputInterface $output) return 1; } - $session->importXml( + $session->importXML( $parentPath, $filename, ImportUUIDBehaviorInterface::IMPORT_UUID_CREATE_NEW diff --git a/src/PHPCR/Util/Console/Helper/PhpcrHelper.php b/src/PHPCR/Util/Console/Helper/PhpcrHelper.php index 33c75ef..889b7f2 100644 --- a/src/PHPCR/Util/Console/Helper/PhpcrHelper.php +++ b/src/PHPCR/Util/Console/Helper/PhpcrHelper.php @@ -2,6 +2,7 @@ namespace PHPCR\Util\Console\Helper; +use Exception; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Helper\Helper; use PHPCR\NodeInterface; @@ -177,7 +178,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/ConsoleDumperNodeVisitor.php b/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperNodeVisitor.php index e5ee0e8..70bc0d9 100644 --- a/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperNodeVisitor.php +++ b/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperNodeVisitor.php @@ -2,6 +2,7 @@ namespace PHPCR\Util\Console\Helper\TreeDumper; +use Exception; use Symfony\Component\Console\Output\OutputInterface; use PHPCR\ItemInterface; use PHPCR\NodeInterface; @@ -51,14 +52,16 @@ public function setShowFullPath($showFullPath) * Print information about the visited node. * * @param ItemInterface $item the node to visit + * + * @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: $item"); + throw new Exception("Internal error: did not expect to visit a non-node object: $item"); } - if ($item->getDepth() == 0) { + if ($item->getDepth() === 0) { $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 092d3e7..350b8b3 100644 --- a/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperPropertyVisitor.php +++ b/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperPropertyVisitor.php @@ -2,6 +2,7 @@ namespace PHPCR\Util\Console\Helper\TreeDumper; +use Exception; use Symfony\Component\Console\Output\OutputInterface; use PHPCR\ItemInterface; use PHPCR\PropertyInterface; @@ -30,7 +31,7 @@ class ConsoleDumperPropertyVisitor extends ConsoleDumperItemVisitor * Instantiate property visitor * * @param OutputInterface $output - * @param int $maxLineLength + * @param array $options */ public function __construct(OutputInterface $output, $options = array()) { @@ -49,11 +50,13 @@ public function __construct(OutputInterface $output, $options = array()) * Print information about this property * * @param ItemInterface $item the property to visit + * + * @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 860fb5c..96557eb 100644 --- a/src/PHPCR/Util/Console/Helper/TreeDumper/SystemNodeFilter.php +++ b/src/PHPCR/Util/Console/Helper/TreeDumper/SystemNodeFilter.php @@ -3,6 +3,7 @@ namespace PHPCR\Util\Console\Helper\TreeDumper; use PHPCR\ItemInterface; +use PHPCR\RepositoryException; use PHPCR\Util\TreeWalkerFilterInterface; use PHPCR\Util\NodeHelper; @@ -19,6 +20,8 @@ class SystemNodeFilter implements TreeWalkerFilterInterface * @param ItemInterface $item * * @return boolean + * + * @throws RepositoryException */ public function mustVisit(ItemInterface $item) { diff --git a/src/PHPCR/Util/NodeHelper.php b/src/PHPCR/Util/NodeHelper.php index 778e647..7102e09 100644 --- a/src/PHPCR/Util/NodeHelper.php +++ b/src/PHPCR/Util/NodeHelper.php @@ -2,13 +2,19 @@ namespace PHPCR\Util; +use InvalidArgumentException; +use PHPCR\ItemExistsException; use PHPCR\ItemInterface; +use PHPCR\Lock\LockException; use PHPCR\NodeInterface; +use PHPCR\NodeType\ConstraintViolationException; +use PHPCR\PathNotFoundException; use PHPCR\PropertyInterface; use PHPCR\SessionInterface; use PHPCR\RepositoryException; use PHPCR\ItemNotFoundException; use PHPCR\NamespaceException; +use PHPCR\Version\VersionException; /** * Helper with only static methods to work with PHPCR nodes @@ -35,6 +41,14 @@ private function __construct() * @param string $path full path, like /content/jobs/data * * @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 */ public static function createPath(SessionInterface $session, $path) { @@ -65,6 +79,8 @@ public static function createPath(SessionInterface $session, $path) * @param SessionInterface $session the session to remove all children of * the root node * + * @throws RepositoryException + * * @see isSystemItem */ public static function purgeWorkspace(SessionInterface $session) @@ -91,6 +107,8 @@ public static function purgeWorkspace(SessionInterface $session) * * @param SessionInterface $session * + * @throws RepositoryException + * * @deprecated */ public static function deleteAllNodes(SessionInterface $session) @@ -106,6 +124,8 @@ public static function deleteAllNodes(SessionInterface $session) * @param ItemInterface $item * * @return boolean true if $item is a system item, false otherwise + * + * @throws RepositoryException */ public static function isSystemItem(ItemInterface $item) { @@ -133,6 +153,8 @@ public static function isSystemItem(ItemInterface $item) * @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) { @@ -150,7 +172,7 @@ public static function generateAutoNodeName($usedNames, $namespaces, $defaultNam * be in the empty namespace and the local part of the name will be * generated by the repository. */ - if ('' === $nameHint || ':' == $nameHint || '{}' == $nameHint) { + if ('' === $nameHint || ':' === $nameHint || '{}' === $nameHint) { return self::generateWithPrefix($usedNames, ''); } @@ -158,7 +180,7 @@ public static function generateAutoNodeName($usedNames, $namespaces, $defaultNam * "somePrefix:" where somePrefix is a syntactically * valid namespace prefix */ - if (':' == $nameHint[strlen($nameHint)-1] + if (':' === $nameHint[strlen($nameHint)-1] && substr_count($nameHint, ':') === 1 && preg_match('#^[a-zA-Z][a-zA-Z0-9]*:$#', $nameHint) ) { @@ -175,8 +197,8 @@ public static function generateAutoNodeName($usedNames, $namespaces, $defaultNam * namespace URI */ if (strlen($nameHint) > 2 - && '{' == $nameHint[0] - && '}' == $nameHint[strlen($nameHint)-1] + && '{' === $nameHint[0] + && '}' === $nameHint[strlen($nameHint)-1] && filter_var(substr($nameHint, 1, -1), FILTER_VALIDATE_URL) ) { $prefix = array_search(substr($nameHint, 1, -1), $namespaces); @@ -328,7 +350,7 @@ public static function calculateOrderBefore(array $old, array $new) * * @return array The updated $nodes array with new order * - * @throws \PHPCR\ItemNotFoundException if $srcChildRelPath or $destChildRelPath are not found in $nodes + * @throws ItemNotFoundException if $srcChildRelPath or $destChildRelPath are not found in $nodes */ public static function orderBeforeArray($name, $destination, $list) { diff --git a/src/PHPCR/Util/PathHelper.php b/src/PHPCR/Util/PathHelper.php index ab8fde6..c82d9b1 100644 --- a/src/PHPCR/Util/PathHelper.php +++ b/src/PHPCR/Util/PathHelper.php @@ -47,7 +47,7 @@ private function __construct() public static function assertValidAbsolutePath($path, $destination = false, $throw = true, $namespacePrefixes = false) { if ((!is_string($path) && !is_numeric($path)) - || strlen($path) == 0 + || strlen($path) === 0 || '/' !== $path[0] || strlen($path) > 1 && '/' === $path[strlen($path) - 1] || preg_match('-//|/\./|/\.\./-', $path) @@ -94,7 +94,7 @@ public static function assertValidAbsolutePath($path, $destination = false, $thr */ public static function assertValidLocalName($name, $throw = true) { - if ('.' == $name || '..' == $name) { + if ('.' === $name || '..' === $name) { return self::error("Name may not be parent or self identifier: $name", $throw); } @@ -262,6 +262,8 @@ public static function getParentPath($path) * @param string $path a valid absolute path, like /content/jobs/data * * @return string the name, that is the string after the last "/" + * + * @throws RepositoryException */ public static function getNodeName($path) { @@ -283,6 +285,8 @@ public static function getNodeName($path) * @param string $path a valid absolute path * * @return string The localname + * + * @throws RepositoryException */ public static function getLocalNodeName($path) { diff --git a/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php b/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php index 836f4c0..a2ff90c 100644 --- a/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php +++ b/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php @@ -2,6 +2,7 @@ namespace PHPCR\Util\QOM; +use InvalidArgumentException; use PHPCR\Query\QOM; /** @@ -193,7 +194,10 @@ protected function convertFullTextSearchExpression($expr) * bindVariableName ::= Prefix * * @param QOM\StaticOperandInterface $operand + * * @return string + * + * @throws InvalidArgumentException */ protected function convertStaticOperand(QOM\StaticOperandInterface $operand) { @@ -205,7 +209,7 @@ protected function convertStaticOperand(QOM\StaticOperandInterface $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/BaseSqlGenerator.php b/src/PHPCR/Util/QOM/BaseSqlGenerator.php index 365984e..8b4b37f 100644 --- a/src/PHPCR/Util/QOM/BaseSqlGenerator.php +++ b/src/PHPCR/Util/QOM/BaseSqlGenerator.php @@ -2,7 +2,6 @@ namespace PHPCR\Util\QOM; -use PHPCR\Query\QOM; use PHPCR\Query\QOM\QueryObjectModelConstantsInterface as Constants; use PHPCR\PropertyType; use PHPCR\Util\ValueConverter; @@ -59,6 +58,8 @@ public function evalQuery($source, $columns, $constraint = '', $orderings = '') * * @param string $constraint1 * @param string $constraint2 + * + * @return string */ public function evalAnd($constraint1, $constraint2) { @@ -70,6 +71,8 @@ public function evalAnd($constraint1, $constraint2) * * @param string $constraint1 * @param string $constraint2 + * + * @return string */ public function evalOr($constraint1, $constraint2) { @@ -80,6 +83,8 @@ public function evalOr($constraint1, $constraint2) * Not ::= 'NOT' Constraint * * @param string $constraint + * + * @return string */ public function evalNot($constraint) { @@ -92,6 +97,8 @@ public function evalNot($constraint) * @param string $operand1 * @param string $operator * @param string $operand2 + * + * @return string */ public function evalComparison($operand1, $operator, $operand2) { @@ -104,6 +111,8 @@ public function evalComparison($operand1, $operator, $operand2) * GreaterThanOrEqualTo | Like * * @param string $operator + * + * @return string */ public function evalOperator($operator) { @@ -131,6 +140,8 @@ public function evalOperator($operator) * LowerCase ::= 'LOWER(' DynamicOperand ')' * * @param string $operand + * + * @return string */ public function evalLower($operand) { @@ -141,6 +152,8 @@ public function evalLower($operand) * LowerCase ::= 'UPPER(' DynamicOperand ')' * * @param string $operand + * + * @return string */ public function evalUpper($operand) { diff --git a/src/PHPCR/Util/QOM/NotSupportedConstraintException.php b/src/PHPCR/Util/QOM/NotSupportedConstraintException.php index d6bb670..23a67e8 100644 --- a/src/PHPCR/Util/QOM/NotSupportedConstraintException.php +++ b/src/PHPCR/Util/QOM/NotSupportedConstraintException.php @@ -2,13 +2,15 @@ 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 @@ -17,6 +19,7 @@ class NotSupportedConstraintException extends \RuntimeException */ public function __construct($constraint) { - parent::__construct(get_class($constraint) . " is not supported by this query language"); + $class = get_class($constraint); + parent::__construct("$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 18435c9..b0c369c 100644 --- a/src/PHPCR/Util/QOM/NotSupportedOperandException.php +++ b/src/PHPCR/Util/QOM/NotSupportedOperandException.php @@ -2,13 +2,15 @@ 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 @@ -17,6 +19,7 @@ class NotSupportedOperandException extends \RuntimeException */ public function __construct($operand) { - parent::__construct(get_class($operand) . " is not supported by this query language"); + $class = get_class($operand); + parent::__construct("$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 d79e5fc..c786df9 100644 --- a/src/PHPCR/Util/QOM/QomToSql1QueryConverter.php +++ b/src/PHPCR/Util/QOM/QomToSql1QueryConverter.php @@ -2,6 +2,7 @@ namespace PHPCR\Util\QOM; +use InvalidArgumentException; use PHPCR\Query\QOM; /** @@ -24,7 +25,7 @@ protected function convertSource(QOM\SourceInterface $source) return $this->convertSelector($source); } - throw new \InvalidArgumentException("Invalid Source"); + throw new InvalidArgumentException('Invalid Source'); } /** @@ -37,7 +38,11 @@ protected function convertSource(QOM\SourceInterface $source) * Not ::= 'NOT' Constraint * * @param QOM\ConstraintInterface $constraint + * * @return string + * + * @throws InvalidArgumentException + * @throws NotSupportedConstraintException */ protected function convertConstraint(QOM\ConstraintInterface $constraint) { @@ -75,7 +80,8 @@ protected function convertConstraint(QOM\ConstraintInterface $constraint) } // This should not happen, but who knows... - throw new \InvalidArgumentException("Invalid operand: " . get_class($constraint)); + $class = get_class($constraint); + throw new InvalidArgumentException("Invalid operand: $class"); } /** @@ -85,7 +91,11 @@ protected function convertConstraint(QOM\ConstraintInterface $constraint) * UpperCase ::= 'UPPER(' DynamicOperand ')' * * @param QOM\DynamicOperandInterface $operand + * * @return string + * + * @throws NotSupportedOperandException + * @throws InvalidArgumentException */ protected function convertDynamicOperand(QOM\DynamicOperandInterface $operand) { @@ -116,6 +126,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 a4b4163..764af27 100644 --- a/src/PHPCR/Util/QOM/QomToSql2QueryConverter.php +++ b/src/PHPCR/Util/QOM/QomToSql2QueryConverter.php @@ -2,6 +2,7 @@ namespace PHPCR\Util\QOM; +use InvalidArgumentException; use PHPCR\Query\QOM; /** @@ -18,6 +19,8 @@ class QomToSql2QueryConverter extends BaseQomToSqlQueryConverter * @param QOM\SourceInterface $source * * @return string + * + * @throws InvalidArgumentException */ protected function convertSource(QOM\SourceInterface $source) { @@ -28,7 +31,7 @@ protected function convertSource(QOM\SourceInterface $source) return $this->convertJoin($source); } - throw new \InvalidArgumentException("Invalid Source"); + throw new InvalidArgumentException('Invalid Source'); } /** @@ -61,7 +64,10 @@ protected function convertJoin(QOM\JoinInterface $join) * DescendantNodeJoinCondition * * @param QOM\JoinConditionInterface $condition + * * @return string + * + * @throws InvalidArgumentException */ protected function convertJoinCondition(QOM\JoinConditionInterface $condition) { @@ -75,7 +81,7 @@ protected function convertJoinCondition(QOM\JoinConditionInterface $condition) $sql2 = $this->convertDescendantNodeJoinCondition($condition); } else { // This should not happen, but who knows... - throw new \InvalidArgumentException("Invalid operand"); + throw new InvalidArgumentException('Invalid operand'); } return $sql2; @@ -175,7 +181,10 @@ protected function convertDescendantNodeJoinCondition(QOM\DescendantNodeJoinCond * specification of the selectorName is optional * * @param QOM\ConstraintInterface $constraint + * * @return string + * + * @throws InvalidArgumentException */ protected function convertConstraint(QOM\ConstraintInterface $constraint) { @@ -217,7 +226,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)); } /** @@ -233,7 +242,10 @@ protected function convertConstraint(QOM\ConstraintInterface $constraint) * UpperCase ::= 'UPPER(' DynamicOperand ')' * * @param QOM\DynamicOperandInterface $operand + * * @return string + * + * @throws InvalidArgumentException */ protected function convertDynamicOperand(QOM\DynamicOperandInterface $operand) { @@ -266,6 +278,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 8403fe7..607207d 100644 --- a/src/PHPCR/Util/QOM/QueryBuilder.php +++ b/src/PHPCR/Util/QOM/QueryBuilder.php @@ -2,6 +2,9 @@ namespace PHPCR\Util\QOM; +use InvalidArgumentException; +use PHPCR\Query\QOM\ColumnInterface; +use PHPCR\Query\QOM\OrderingInterface; use PHPCR\Query\QOM\QueryObjectModelFactoryInterface; use PHPCR\Query\QOM\DynamicOperandInterface; use PHPCR\Query\QOM\ConstraintInterface; @@ -10,6 +13,7 @@ use PHPCR\Query\QOM\QueryObjectModelConstantsInterface; use PHPCR\Query\QueryInterface; use PHPCR\Query\QOM\QueryObjectModelInterface; +use RuntimeException; /** * QueryBuilder class is responsible for dynamically create QOM queries. @@ -96,6 +100,8 @@ public function __construct(QueryObjectModelFactoryInterface $qomFactory) * @param string $language the query language * * @return QueryBuilder This QueryBuilder instance. + * + * @throws InvalidArgumentException */ public function setFromQuery($statement, $language) { @@ -105,7 +111,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; @@ -189,7 +195,7 @@ public function getMaxResults() /** * Gets the array of orderings. * - * @return \PHPCR\Query\QOM\OrderingInterface[] Orderings to apply. + * @return OrderingInterface[] Orderings to apply. */ public function getOrderings() { @@ -203,17 +209,19 @@ public function getOrderings() * @param string $order The ordering direction. * * @return QueryBuilder This QueryBuilder instance. + * + * @throws InvalidArgumentException */ public function addOrderBy(DynamicOperandInterface $sort, $order = 'ASC') { $order = strtoupper($order); if (!in_array($order, array('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 ($order === 'DESC') { $ordering = $this->qomFactory->descending($sort); } else { $ordering = $this->qomFactory->ascending($sort); @@ -327,7 +335,7 @@ public function orWhere(ConstraintInterface $constraint) /** * Returns the columns to be selected * - * @return \PHPCR\Query\QOM\ColumnInterface[] The columns to be selected + * @return ColumnInterface[] The columns to be selected */ public function getColumns() { @@ -337,7 +345,7 @@ public function getColumns() /** * Sets the columns to be selected * - * @param \PHPCR\Query\QOM\ColumnInterface[] $columns The columns to be selected + * @param ColumnInterface[] $columns The columns to be selected * * @return QueryBuilder This QueryBuilder instance. */ @@ -417,7 +425,7 @@ public function getSource() * * @return QueryBuilder This QueryBuilder instance. * - * @throws \RuntimeException if there is not an existing source. + * @throws RuntimeException if there is not an existing source. */ public function join(SourceInterface $rightSource, JoinConditionInterface $joinCondition) { @@ -432,7 +440,7 @@ public function join(SourceInterface $rightSource, JoinConditionInterface $joinC * * @return QueryBuilder This QueryBuilder instance. * - * @throws \RuntimeException if there is not an existing source. + * @throws RuntimeException if there is not an existing source. */ public function innerJoin(SourceInterface $rightSource, JoinConditionInterface $joinCondition) { @@ -447,7 +455,7 @@ public function innerJoin(SourceInterface $rightSource, JoinConditionInterface $ * * @return QueryBuilder This QueryBuilder instance. * - * @throws \RuntimeException if there is not an existing source. + * @throws RuntimeException if there is not an existing source. */ public function leftJoin(SourceInterface $rightSource, JoinConditionInterface $joinCondition) { @@ -462,7 +470,7 @@ public function leftJoin(SourceInterface $rightSource, JoinConditionInterface $j * * @return QueryBuilder This QueryBuilder instance. * - * @throws \RuntimeException if there is not an existing source. + * @throws RuntimeException if there is not an existing source. */ public function rightJoin(SourceInterface $rightSource, JoinConditionInterface $joinCondition) { @@ -478,12 +486,12 @@ public function rightJoin(SourceInterface $rightSource, JoinConditionInterface $ * * @return QueryBuilder This QueryBuilder instance. * - * @throws \RuntimeException if there is not an existing source. + * @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; $this->source = $this->qomFactory->join($this->source, $rightSource, $joinType, $joinCondition); diff --git a/src/PHPCR/Util/QOM/Sql1Generator.php b/src/PHPCR/Util/QOM/Sql1Generator.php index 7d6f046..d2b2749 100644 --- a/src/PHPCR/Util/QOM/Sql1Generator.php +++ b/src/PHPCR/Util/QOM/Sql1Generator.php @@ -34,7 +34,7 @@ public function evalSelector($nodeTypeName, $selectorName = null) */ protected function getPathForDescendantQuery($path) { - if ($path == '/') { + if ($path === '/') { $sql1 = '/%'; } else { $path = trim($path, "\"'/"); diff --git a/src/PHPCR/Util/QOM/Sql2Generator.php b/src/PHPCR/Util/QOM/Sql2Generator.php index b9793ee..21f29eb 100644 --- a/src/PHPCR/Util/QOM/Sql2Generator.php +++ b/src/PHPCR/Util/QOM/Sql2Generator.php @@ -2,7 +2,6 @@ namespace PHPCR\Util\QOM; -use PHPCR\Query\QOM; use PHPCR\Query\QOM\QueryObjectModelConstantsInterface as Constants; /** diff --git a/src/PHPCR/Util/QOM/Sql2Scanner.php b/src/PHPCR/Util/QOM/Sql2Scanner.php index 10524be..f55254f 100644 --- a/src/PHPCR/Util/QOM/Sql2Scanner.php +++ b/src/PHPCR/Util/QOM/Sql2Scanner.php @@ -101,6 +101,8 @@ public function fetchNextToken() * * @param string $token The expected token * @param boolean $case_insensitive + * + * @throws InvalidQueryException */ public function expectToken($token, $case_insensitive = true) { @@ -117,6 +119,8 @@ public function expectToken($token, $case_insensitive = true) * * @param array $tokens * @param boolean $case_insensitive + * + * @throws InvalidQueryException */ public function expectTokens($tokens, $case_insensitive = true) { diff --git a/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php b/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php index 48de564..78ff818 100644 --- a/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php +++ b/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php @@ -2,6 +2,10 @@ namespace PHPCR\Util\QOM; +use DateTime; +use Exception; +use InvalidArgumentException; +use LogicException; use PHPCR\PropertyType; use PHPCR\Query\InvalidQueryException; use PHPCR\Query\QOM\ChildNodeJoinConditionInterface; @@ -22,6 +26,7 @@ use PHPCR\Query\QOM\QueryObjectModelFactoryInterface; use PHPCR\Query\QOM\QueryObjectModelInterface; use PHPCR\Query\QOM\SameNodeJoinConditionInterface; +use PHPCR\Query\QOM\SelectorInterface; use PHPCR\Query\QOM\SourceInterface; use PHPCR\Query\QOM\StaticOperandInterface; use Jackalope\Query\QOM\Selector; @@ -85,6 +90,8 @@ public function __construct(QueryObjectModelFactoryInterface $factory, ValueConv * @param string $sql2 * * @return QueryObjectModelInterface + * + * @throws InvalidQueryException */ public function parse($sql2) { @@ -155,7 +162,7 @@ protected function parseSource() * 6.7.3. Selector * Parse an SQL2 selector and return a QOM\Selector * - * @return \PHPCR\Query\QOM\SelectorInterface + * @return SelectorInterface */ protected function parseSelector() { @@ -205,6 +212,8 @@ protected function parseJoin(SourceInterface $leftSelector) * 6.7.6. Join type * * @return string + * + * @throws InvalidQueryException */ protected function parseJoinType() { @@ -343,7 +352,7 @@ protected function parseDescendantNodeJoinCondition() * * @return ConstraintInterface * - * @throws \Exception + * @throws Exception */ protected function parseConstraint($lhs = null, $minprec = 0) { @@ -380,9 +389,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()); @@ -463,6 +470,8 @@ protected function parseNot() * 6.7.16 Comparison * * @return ComparisonInterface + * + * @throws InvalidQueryException */ protected function parseComparison() { @@ -740,7 +749,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('('); @@ -774,7 +783,7 @@ protected function parseCastLiteral($token) $type = $this->scanner->fetchNextToken(); try { $typeValue = PropertyType::valueFromName($type); - } catch (\InvalidArgumentException $e) { + } catch (InvalidArgumentException $e) { throw new InvalidQueryException("Syntax error: attempting to cast to an invalid type '$type'"); } @@ -782,7 +791,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'"); } @@ -829,13 +838,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') { + } elseif ($token === 'true') { $token = true; - } elseif ($token == 'false') { + } elseif ($token === 'false') { $token = false; } @@ -990,6 +999,8 @@ private function parseIdentifier($checkSelector = true) * Add a selector name to the known selector names. * * @param string $selectorName + * + * @throws InvalidQueryException */ protected function updateImplicitSelectorName($selectorName) { diff --git a/src/PHPCR/Util/TraversingItemVisitor.php b/src/PHPCR/Util/TraversingItemVisitor.php index 7d1e3ee..468495d 100644 --- a/src/PHPCR/Util/TraversingItemVisitor.php +++ b/src/PHPCR/Util/TraversingItemVisitor.php @@ -164,7 +164,7 @@ public function visit(ItemInterface $item) try { if ($this->breadthFirst === false) { $this->entering($item, $this->currentDepth); - if ($this->maxDepth == -1 || $this->currentDepth < $this->maxDepth) { + if ($this->maxDepth === -1 || $this->currentDepth < $this->maxDepth) { $this->currentDepth++; foreach ($item->getProperties() as $property) { /** @var $property PropertyInterface */ @@ -181,7 +181,7 @@ public function visit(ItemInterface $item) $this->entering($item, $this->currentDepth); $this->leaving($item, $this->currentDepth); - if ($this->maxDepth == -1 || $this->currentDepth < $this->maxDepth) { + if ($this->maxDepth === -1 || $this->currentDepth < $this->maxDepth) { foreach ($item->getProperties() as $property) { /** @var $property PropertyInterface */ $property->accept($this); diff --git a/src/PHPCR/Util/TreeWalker.php b/src/PHPCR/Util/TreeWalker.php index 4c9c30b..37bf9f0 100644 --- a/src/PHPCR/Util/TreeWalker.php +++ b/src/PHPCR/Util/TreeWalker.php @@ -3,8 +3,8 @@ namespace PHPCR\Util; use PHPCR\ItemVisitorInterface; -use \PHPCR\NodeInterface; -use \PHPCR\PropertyInterface; +use PHPCR\NodeInterface; +use PHPCR\PropertyInterface; /** * TODO: this should base on the TraversingItemVisitor diff --git a/src/PHPCR/Util/TreeWalkerFilterInterface.php b/src/PHPCR/Util/TreeWalkerFilterInterface.php index 299417d..fe681af 100644 --- a/src/PHPCR/Util/TreeWalkerFilterInterface.php +++ b/src/PHPCR/Util/TreeWalkerFilterInterface.php @@ -15,7 +15,7 @@ interface TreeWalkerFilterInterface /** * Whether to visit the passed item * - * @param \PHPCR\ItemInterface $item + * @param ItemInterface $item * * @return mixed */ diff --git a/src/PHPCR/Util/ValueConverter.php b/src/PHPCR/Util/ValueConverter.php index 4b3ef49..d4aca45 100644 --- a/src/PHPCR/Util/ValueConverter.php +++ b/src/PHPCR/Util/ValueConverter.php @@ -2,6 +2,7 @@ namespace PHPCR\Util; +use DateTime; use PHPCR\NodeInterface; use PHPCR\PropertyInterface; use PHPCR\PropertyType; @@ -124,7 +125,7 @@ public function convertType($value, $type, $srctype = PropertyType::UNDEFINED) return $ret; } - if (PropertyType::UNDEFINED == $srctype) { + if (PropertyType::UNDEFINED === $srctype) { $srctype = $this->determineType($value); } @@ -133,12 +134,12 @@ public function convertType($value, $type, $srctype = PropertyType::UNDEFINED) } // except on noop, stream needs to be read into string first - if (PropertyType::BINARY == $srctype && PropertyType::BINARY != $type && is_resource($value)) { + if (PropertyType::BINARY === $srctype && PropertyType::BINARY !== $type && is_resource($value)) { $t = stream_get_contents($value); rewind($value); $value = $t; $srctype = PropertyType::STRING; - } elseif ((PropertyType::REFERENCE == $srctype || PropertyType::WEAKREFERENCE == $srctype) + } elseif ((PropertyType::REFERENCE === $srctype || PropertyType::WEAKREFERENCE === $srctype) && $value instanceof NodeInterface ) { /** @var $value NodeInterface */ @@ -152,10 +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 */ + /** @var $value DateTime */ // Milliseconds formatting is not possible in PHP so we // construct it by cutting microseconds to 3 positions. // This might not be as accurate as "real" rounded milliseconds. @@ -199,10 +200,10 @@ public function convertType($value, $type, $srctype = PropertyType::UNDEFINED) case PropertyType::DECIMAL: return (integer) $value; case PropertyType::DATE: - if (! $value instanceof \DateTime) { + if (! $value instanceof DateTime) { throw new RepositoryException('something weird'); } - /** @var $value \DateTime */ + /** @var $value DateTime */ return $value->getTimestamp(); } @@ -220,11 +221,11 @@ public function convertType($value, $type, $srctype = PropertyType::UNDEFINED) case PropertyType::DECIMAL: return (double) $value; case PropertyType::DATE: - if (! $value instanceof \DateTime) { + if (! $value instanceof DateTime) { throw new RepositoryException('something weird'); } - /** @var $value \DateTime */ + /** @var $value DateTime */ return (double) $value->getTimestamp(); } @@ -237,18 +238,18 @@ 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); + return new DateTime($value); } catch (\Exception $e) { throw new ValueFormatException("String '$value' is not a valid date", null, $e); } case PropertyType::LONG: case PropertyType::DOUBLE: case PropertyType::DECIMAL: - $datetime = new \DateTime(); + $datetime = new DateTime(); $datetime = $datetime->setTimestamp($value); return $datetime; @@ -363,7 +364,7 @@ public function convertType($value, $type, $srctype = PropertyType::UNDEFINED) case PropertyType::DECIMAL: return (string) $value; case PropertyType::DATE: - /** @var $value \DateTime */ + /** @var $value DateTime */ return (string) $value->getTimestamp(); } From 5340198cfb595c8d071eb746d75696fbd77d3c67 Mon Sep 17 00:00:00 2001 From: Pavel Vondrasek Date: Fri, 20 Jan 2017 11:54:51 +0100 Subject: [PATCH 06/88] increased php version to 5.6 raised branch alias to 1.3 --- .travis.yml | 4 +--- composer.json | 4 ++-- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/.travis.yml b/.travis.yml index 92355f9..5a3f048 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,8 +1,6 @@ language: php php: - - 5.4 - - 5.5 - 5.6 - 7.0 - 7.1 @@ -15,7 +13,7 @@ sudo: false matrix: include: - - php: 5.3 + - php: 5.6 env: PACKAGE_VERSION=low before_script: diff --git a/composer.json b/composer.json index 070bf5e..2e2bf7c 100644 --- a/composer.json +++ b/composer.json @@ -27,7 +27,7 @@ } ], "require": { - "php": "^5.3.3|7.0.x|7.1.x", + "php": "^5.6|7.0.x|7.1.x", "phpcr/phpcr": "~2.1.0", "symfony/console": "~2.3|~3.0" }, @@ -48,7 +48,7 @@ "bin": ["bin/phpcr"], "extra": { "branch-alias": { - "dev-master": "1.2-dev" + "dev-master": "1.3-dev" } } } From c0d8ddc17d1422c7c158640d5affd44337fdd47c Mon Sep 17 00:00:00 2001 From: Pavel Vondrasek Date: Sat, 21 Jan 2017 01:05:58 +0100 Subject: [PATCH 07/88] syntax was updated to PHP 5.6 (::class string, short array syntax etc.) was added PHPUnit to dev-dependencies tests were updated to remove deprecations (please double-check it!!!) + BONUS: was added PHPStan to dev-dependencies it can help us to make better code and in future we can run it before tests to analyze code :) And finally joke: I think that CndParserTest is here (in this package) so that i made this refactoring I wan't to mark it as skipped in the end but I was very surprised :-D :-D --- .styleci.yml | 2 +- bin/phpcr | 8 +- composer.json | 4 +- .../Command/BaseNodeManipulationCommand.php | 4 + .../Util/Console/Command/NodeDumpCommand.php | 10 +- .../Util/Console/Command/NodeMoveCommand.php | 5 + .../Console/Command/NodeRemoveCommand.php | 9 +- .../Util/Console/Command/NodeTouchCommand.php | 5 + .../Console/Command/NodeTypeListCommand.php | 1 + .../Command/NodeTypeRegisterCommand.php | 4 +- .../Console/Command/NodesUpdateCommand.php | 24 +- .../Command/WorkspaceCreateCommand.php | 2 - .../Command/WorkspaceExportCommand.php | 1 - .../Command/WorkspaceImportCommand.php | 1 - .../Console/Command/WorkspaceListCommand.php | 1 - .../Console/Command/WorkspaceQueryCommand.php | 1 - src/PHPCR/Util/NodeHelper.php | 4 +- .../Util/QOM/BaseQomToSqlQueryConverter.php | 3 +- src/PHPCR/Util/QOM/BaseSqlGenerator.php | 7 +- .../Util/QOM/QomToSql1QueryConverter.php | 15 + .../Util/QOM/QomToSql2QueryConverter.php | 11 + src/PHPCR/Util/QOM/QueryBuilder.php | 22 +- src/PHPCR/Util/QOM/Sql1Generator.php | 5 +- src/PHPCR/Util/QOM/Sql2Scanner.php | 6 +- .../Util/QOM/Sql2ToQomQueryConverter.php | 24 +- src/PHPCR/Util/TraversingItemVisitor.php | 2 +- src/PHPCR/Util/TreeWalker.php | 4 +- src/PHPCR/Util/UUIDHelper.php | 2 +- src/PHPCR/Util/ValueConverter.php | 48 +- 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 | 7 +- .../Tests/Util/CND/Reader/FileReaderTest.php | 34 +- .../Util/CND/Scanner/GenericScannerTest.php | 142 ++--- .../Tests/Util/CND/Scanner/TokenQueueTest.php | 34 +- .../Tests/Util/CND/Scanner/TokenTest.php | 8 +- .../Util/Console/Command/BaseCommandTest.php | 65 +- .../Console/Command/NodeDumpCommandTest.php | 24 +- .../Console/Command/NodeMoveCommandTest.php | 12 +- .../Console/Command/NodeRemoveCommandTest.php | 12 +- .../Console/Command/NodeTouchCommandTest.php | 47 +- .../Command/NodeTypeListCommandTest.php | 31 +- .../Command/NodeTypeRegisterCommandTest.php | 30 +- .../Command/NodesUpdateCommandTest.php | 108 ++-- .../Command/WorkspaceCreateCommandTest.php | 27 +- .../Command/WorkspaceDeleteCommandTest.php | 15 +- .../Command/WorkspaceExportCommandTest.php | 10 +- .../Command/WorkspaceImportCommandTest.php | 8 +- .../Command/WorkspaceListCommandTest.php | 7 +- .../Command/WorkspacePurgeCommandTest.php | 12 +- .../Command/WorkspaceQueryCommandTest.php | 24 +- .../Helper/PhpcrConsoleDumperHelperTest.php | 30 +- tests/PHPCR/Tests/Util/NodeHelperTest.php | 118 ++-- tests/PHPCR/Tests/Util/PathHelperTest.php | 201 ++++--- .../Tests/Util/QOM/BaseSqlGeneratorTest.php | 9 +- .../PHPCR/Tests/Util/QOM/QueryBuilderTest.php | 248 ++++++-- .../Tests/Util/QOM/Sql1GeneratorTest.php | 33 +- .../Tests/Util/QOM/Sql2GeneratorTest.php | 6 +- .../Util/QOM/Sql2ToQomQueryConverterTest.php | 25 +- .../Tests/Util/TraversingItemVisitorTest.php | 4 +- tests/PHPCR/Tests/Util/UUIDHelperTest.php | 3 +- tests/PHPCR/Tests/Util/ValueConverterTest.php | 558 +++++++++--------- 63 files changed, 1271 insertions(+), 865 deletions(-) diff --git a/.styleci.yml b/.styleci.yml index 4e1109e..0f86e26 100644 --- a/.styleci.yml +++ b/.styleci.yml @@ -1,5 +1,5 @@ preset: psr2 enabled: - - long_array_syntax + - short_array_syntax - duplicate_semicolon \ No newline at end of file diff --git a/bin/phpcr b/bin/phpcr index 3e49686..9b361f7 100755 --- a/bin/phpcr +++ b/bin/phpcr @@ -5,7 +5,7 @@ use Symfony\Component\Console\Application; use Symfony\Component\Console\Helper\HelperSet; use PHPCR\Util\Console\Command; -if (!class_exists('\Symfony\Component\Console\Application')) { +if (!class_exists(Application::class)) { if (is_file(__DIR__.'/../vendor/autoload.php')) { require __DIR__.'/../vendor/autoload.php'; } elseif (is_file(__DIR__.'/../../../autoload.php')) { @@ -30,7 +30,7 @@ if (file_exists($configFile)) { require $configFile; foreach ($GLOBALS as $helperSetCandidate) { - if ($helperSetCandidate instanceof \Symfony\Component\Console\Helper\HelperSet) { + if ($helperSetCandidate instanceof HelperSet) { $helperSet = $helperSetCandidate; break; } @@ -48,7 +48,7 @@ $cli = new Application('PHPCR Command Line Interface', '0.1'); $cli->setCatchExceptions(true); $cli->setHelperSet($helperSet); -$cli->addCommands(array( +$cli->addCommands([ new Command\NodeDumpCommand(), new Command\NodeMoveCommand(), new Command\NodeRemoveCommand(), @@ -62,7 +62,7 @@ $cli->addCommands(array( new Command\WorkspaceImportCommand(), new Command\WorkspacePurgeCommand(), new Command\WorkspaceQueryCommand(), -)); +]); $cli->run(); diff --git a/composer.json b/composer.json index 2e2bf7c..4a32c02 100644 --- a/composer.json +++ b/composer.json @@ -32,7 +32,9 @@ "symfony/console": "~2.3|~3.0" }, "require-dev": { - "ramsey/uuid": "^3.5" + "ramsey/uuid": "^3.5", + "phpunit/phpunit": "^5.7", + "phpstan/phpstan": "^0.6.0" }, "suggest": { "ramsey/uuid": "A PHP 5.4+ library for generating RFC 4122 version 1, 3, 4, and 5 universally unique identifiers (UUID)." diff --git a/src/PHPCR/Util/Console/Command/BaseNodeManipulationCommand.php b/src/PHPCR/Util/Console/Command/BaseNodeManipulationCommand.php index 6531f12..a797b2f 100644 --- a/src/PHPCR/Util/Console/Command/BaseNodeManipulationCommand.php +++ b/src/PHPCR/Util/Console/Command/BaseNodeManipulationCommand.php @@ -21,18 +21,22 @@ protected function configureNodeManipulationInput() InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Set node property on nodes use foo=bar' ); + $this->addOption('remove-prop', 'r', InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Remove property from nodes' ); + $this->addOption('add-mixin', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Add a mixin to the nodes' ); + $this->addOption('remove-mixin', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Remove mixin from the nodes' ); + $this->addOption('apply-closure', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Apply a closure to each node, closures are passed PHPCR\Session and PHPCR\NodeInterface' diff --git a/src/PHPCR/Util/Console/Command/NodeDumpCommand.php b/src/PHPCR/Util/Console/Command/NodeDumpCommand.php index ba57b29..dbc3bcf 100644 --- a/src/PHPCR/Util/Console/Command/NodeDumpCommand.php +++ b/src/PHPCR/Util/Console/Command/NodeDumpCommand.php @@ -2,10 +2,12 @@ namespace PHPCR\Util\Console\Command; +use Exception; use PHPCR\ItemNotFoundException; use PHPCR\RepositoryException; use PHPCR\PathNotFoundException; use PHPCR\Util\UUIDHelper; +use Symfony\Component\Console\Exception\InvalidArgumentException; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; @@ -24,6 +26,8 @@ class NodeDumpCommand extends BaseCommand { /** * {@inheritDoc} + * + * @throws InvalidArgumentException */ protected function configure() { @@ -54,6 +58,10 @@ protected function configure() /** * {@inheritDoc} + * + * @throws InvalidArgumentException + * @throws Exception + * @throws RepositoryException */ protected function execute(InputInterface $input, OutputInterface $output) { @@ -72,7 +80,7 @@ protected function execute(InputInterface $input, OutputInterface $output) $options['max_line_length'] = $input->getOption('max_line_length'); if (null !== $options['ref_format'] && !in_array($options['ref_format'], array('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/NodeMoveCommand.php b/src/PHPCR/Util/Console/Command/NodeMoveCommand.php index 08579bd..3374ad0 100644 --- a/src/PHPCR/Util/Console/Command/NodeMoveCommand.php +++ b/src/PHPCR/Util/Console/Command/NodeMoveCommand.php @@ -3,6 +3,7 @@ namespace PHPCR\Util\Console\Command; use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Exception\InvalidArgumentException; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; @@ -19,6 +20,8 @@ class NodeMoveCommand extends BaseCommand { /** * {@inheritDoc} + * + * @throws InvalidArgumentException */ protected function configure() { @@ -42,6 +45,8 @@ protected function configure() /** * {@inheritDoc} + * + * @throws InvalidArgumentException */ protected function execute(InputInterface $input, OutputInterface $output) { diff --git a/src/PHPCR/Util/Console/Command/NodeRemoveCommand.php b/src/PHPCR/Util/Console/Command/NodeRemoveCommand.php index 206401a..6f217f6 100644 --- a/src/PHPCR/Util/Console/Command/NodeRemoveCommand.php +++ b/src/PHPCR/Util/Console/Command/NodeRemoveCommand.php @@ -2,7 +2,9 @@ namespace PHPCR\Util\Console\Command; +use InvalidArgumentException; use PHPCR\NodeInterface; +use Symfony\Component\Console\Exception\InvalidArgumentException as CliInvalidArgumentException; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; @@ -22,6 +24,8 @@ class NodeRemoveCommand extends BaseCommand { /** * {@inheritDoc} + * + * @throws CliInvalidArgumentException */ protected function configure() { @@ -51,6 +55,9 @@ protected function configure() /** * {@inheritDoc} + * + * @throws CliInvalidArgumentException + * @throws InvalidArgumentException */ protected function execute(InputInterface $input, OutputInterface $output) { @@ -63,7 +70,7 @@ protected function execute(InputInterface $input, OutputInterface $output) 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 6901b7a..b856db8 100644 --- a/src/PHPCR/Util/Console/Command/NodeTouchCommand.php +++ b/src/PHPCR/Util/Console/Command/NodeTouchCommand.php @@ -3,6 +3,7 @@ namespace PHPCR\Util\Console\Command; use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Exception\InvalidArgumentException; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; @@ -23,6 +24,8 @@ class NodeTouchCommand extends BaseNodeManipulationCommand { /** * {@inheritDoc} + * + * @throws InvalidArgumentException */ protected function configure() { @@ -68,6 +71,8 @@ protected function configure() /** * {@inheritDoc} + * + * @throws InvalidArgumentException */ protected function execute(InputInterface $input, OutputInterface $output) { diff --git a/src/PHPCR/Util/Console/Command/NodeTypeListCommand.php b/src/PHPCR/Util/Console/Command/NodeTypeListCommand.php index 2c9f80c..f31baff 100644 --- a/src/PHPCR/Util/Console/Command/NodeTypeListCommand.php +++ b/src/PHPCR/Util/Console/Command/NodeTypeListCommand.php @@ -3,6 +3,7 @@ namespace PHPCR\Util\Console\Command; use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Exception\InvalidArgumentException; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; diff --git a/src/PHPCR/Util/Console/Command/NodeTypeRegisterCommand.php b/src/PHPCR/Util/Console/Command/NodeTypeRegisterCommand.php index 138e400..6dbb39b 100644 --- a/src/PHPCR/Util/Console/Command/NodeTypeRegisterCommand.php +++ b/src/PHPCR/Util/Console/Command/NodeTypeRegisterCommand.php @@ -130,7 +130,7 @@ protected function updateFromCnd(OutputInterface $output, SessionInterface $sess */ protected function getFilePaths($definitions) { - $filePaths = array(); + $filePaths = []; foreach ($definitions as $definition) { if (is_dir($definition)) { @@ -167,7 +167,7 @@ protected function getFilePaths($definitions) protected function fileIsNodeType($filename) { - if (substr($filename, -4) == '.cnd') { + if (substr($filename, -4) === '.cnd') { return true; } diff --git a/src/PHPCR/Util/Console/Command/NodesUpdateCommand.php b/src/PHPCR/Util/Console/Command/NodesUpdateCommand.php index 4f1a4ae..881406e 100644 --- a/src/PHPCR/Util/Console/Command/NodesUpdateCommand.php +++ b/src/PHPCR/Util/Console/Command/NodesUpdateCommand.php @@ -2,8 +2,10 @@ namespace PHPCR\Util\Console\Command; +use InvalidArgumentException; use PHPCR\Query\QueryResultInterface; use PHPCR\Query\RowInterface; +use Symfony\Component\Console\Exception\InvalidArgumentException as CliInvalidArgumentException; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; @@ -21,6 +23,8 @@ class NodesUpdateCommand extends BaseNodeManipulationCommand { /** * {@inheritDoc} + * + * @throws CliInvalidArgumentException */ protected function configure() { @@ -79,12 +83,15 @@ protected function configure() /** * {@inheritDoc} + * + * @throws CliInvalidArgumentException + * @throws InvalidArgumentException */ protected function execute(InputInterface $input, OutputInterface $output) { $query = $input->getOption('query'); $queryLanguage = strtoupper($input->getOption('query-language')); - $persistCounter = intval($input->getOption('persist-counter')); + $persistCounter = (int) $input->getOption('persist-counter'); $setProp = $input->getOption('set-prop'); $removeProp = $input->getOption('remove-prop'); $addMixins = $input->getOption('add-mixin'); @@ -95,16 +102,13 @@ protected function execute(InputInterface $input, OutputInterface $output) $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(sprintf( - 'Query doesn\'t look like a SELECT query: "%s"', - $query - )); + if (strtoupper(substr($query, 0, 6)) !== 'SELECT') { + throw new InvalidArgumentException("Query doesn't look like a SELECT query: '$query'"); } $query = $helper->createQuery($queryLanguage, $query); @@ -161,7 +165,7 @@ private function shouldExecute(InputInterface $input, OutputInterface $output, Q count($result->getRows()) ))); - if ($response == 'L') { + if ($response === 'L') { /** @var $row RowInterface */ foreach ($result as $i => $row) { $output->writeln(sprintf(' - [%d] %s', $i, $row->getPath())); @@ -170,11 +174,11 @@ private function shouldExecute(InputInterface $input, OutputInterface $output, Q return $this->shouldExecute($input, $output, $result); } - if ($response == 'N') { + if ($response === 'N') { return false; } - if ($response == 'Y') { + if ($response === 'Y') { return true; } diff --git a/src/PHPCR/Util/Console/Command/WorkspaceCreateCommand.php b/src/PHPCR/Util/Console/Command/WorkspaceCreateCommand.php index 7c54763..7effe84 100644 --- a/src/PHPCR/Util/Console/Command/WorkspaceCreateCommand.php +++ b/src/PHPCR/Util/Console/Command/WorkspaceCreateCommand.php @@ -3,8 +3,6 @@ namespace PHPCR\Util\Console\Command; use PHPCR\RepositoryInterface; -use PHPCR\SessionInterface; -use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; diff --git a/src/PHPCR/Util/Console/Command/WorkspaceExportCommand.php b/src/PHPCR/Util/Console/Command/WorkspaceExportCommand.php index 7fd0da8..b0a8929 100644 --- a/src/PHPCR/Util/Console/Command/WorkspaceExportCommand.php +++ b/src/PHPCR/Util/Console/Command/WorkspaceExportCommand.php @@ -2,7 +2,6 @@ namespace PHPCR\Util\Console\Command; -use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; diff --git a/src/PHPCR/Util/Console/Command/WorkspaceImportCommand.php b/src/PHPCR/Util/Console/Command/WorkspaceImportCommand.php index e67ff2c..b6b8f5c 100644 --- a/src/PHPCR/Util/Console/Command/WorkspaceImportCommand.php +++ b/src/PHPCR/Util/Console/Command/WorkspaceImportCommand.php @@ -2,7 +2,6 @@ namespace PHPCR\Util\Console\Command; -use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; diff --git a/src/PHPCR/Util/Console/Command/WorkspaceListCommand.php b/src/PHPCR/Util/Console/Command/WorkspaceListCommand.php index 2b4a996..14312ca 100644 --- a/src/PHPCR/Util/Console/Command/WorkspaceListCommand.php +++ b/src/PHPCR/Util/Console/Command/WorkspaceListCommand.php @@ -2,7 +2,6 @@ namespace PHPCR\Util\Console\Command; -use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; diff --git a/src/PHPCR/Util/Console/Command/WorkspaceQueryCommand.php b/src/PHPCR/Util/Console/Command/WorkspaceQueryCommand.php index 64a3acf..8c4bbd0 100644 --- a/src/PHPCR/Util/Console/Command/WorkspaceQueryCommand.php +++ b/src/PHPCR/Util/Console/Command/WorkspaceQueryCommand.php @@ -2,7 +2,6 @@ namespace PHPCR\Util\Console\Command; -use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; diff --git a/src/PHPCR/Util/NodeHelper.php b/src/PHPCR/Util/NodeHelper.php index 7102e09..dcc28c1 100644 --- a/src/PHPCR/Util/NodeHelper.php +++ b/src/PHPCR/Util/NodeHelper.php @@ -240,7 +240,7 @@ public static function generateAutoNodeName($usedNames, $namespaces, $defaultNam * as a basis. The way in which the local name is constructed from the hint * may vary across implementations. */ - $matches = array(); + $matches = []; if (preg_match('#^\\{([^\\}]+)\\}([a-zA-Z][a-zA-Z0-9]*)$#', $nameHint, $matches)) { $ns = $matches[1]; $name = $matches[2]; @@ -294,7 +294,7 @@ private static function generateWithPrefix($usedNames, $prefix, $namepart = '') */ public static function calculateOrderBefore(array $old, array $new) { - $reorders = array(); + $reorders = []; //check for deleted items $newIndex = array_flip($new); diff --git a/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php b/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php index a2ff90c..67e7bca 100644 --- a/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php +++ b/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php @@ -301,7 +301,8 @@ protected function convertLiteral($literal) */ protected function convertColumns(array $columns) { - $list = array(); + $list = []; + /** @var $column QOM\ColumnInterface */ foreach ($columns as $column) { $selector = $column->getSelectorName(); diff --git a/src/PHPCR/Util/QOM/BaseSqlGenerator.php b/src/PHPCR/Util/QOM/BaseSqlGenerator.php index 8b4b37f..6e34e59 100644 --- a/src/PHPCR/Util/QOM/BaseSqlGenerator.php +++ b/src/PHPCR/Util/QOM/BaseSqlGenerator.php @@ -2,6 +2,7 @@ namespace PHPCR\Util\QOM; +use DateTime; use PHPCR\Query\QOM\QueryObjectModelConstantsInterface as Constants; use PHPCR\PropertyType; use PHPCR\Util\ValueConverter; @@ -240,11 +241,11 @@ public function evalBindVariable($var) */ public function evalFullText($string) { - $illegalCharacters = array( + $illegalCharacters = [ '!' => '\\!', '(' => '\\(', ':' => '\\:', '^' => '\\^', '[' => '\\[', ']' => '\\]', '{' => '\\{', '}' => '\\}', '\"' => '\\\"', '?' => '\\?', "'" => "''", - ); + ]; return strtr($string, $illegalCharacters); } @@ -258,7 +259,7 @@ public function evalFullText($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'); diff --git a/src/PHPCR/Util/QOM/QomToSql1QueryConverter.php b/src/PHPCR/Util/QOM/QomToSql1QueryConverter.php index c786df9..7962fff 100644 --- a/src/PHPCR/Util/QOM/QomToSql1QueryConverter.php +++ b/src/PHPCR/Util/QOM/QomToSql1QueryConverter.php @@ -18,6 +18,8 @@ class QomToSql1QueryConverter extends BaseQomToSqlQueryConverter * * @param QOM\SourceInterface $source * @return string + * + * @throws InvalidArgumentException */ protected function convertSource(QOM\SourceInterface $source) { @@ -51,29 +53,36 @@ protected function convertConstraint(QOM\ConstraintInterface $constraint) $this->convertConstraint($constraint->getConstraint1()), $this->convertConstraint($constraint->getConstraint2())); } + if ($constraint instanceof QOM\OrInterface) { return $this->generator->evalOr( $this->convertConstraint($constraint->getConstraint1()), $this->convertConstraint($constraint->getConstraint2())); } + if ($constraint instanceof QOM\NotInterface) { return $this->generator->evalNot($this->convertConstraint($constraint->getConstraint())); } + if ($constraint instanceof QOM\ComparisonInterface) { return $this->convertComparison($constraint); } + if ($constraint instanceof QOM\PropertyExistenceInterface) { return $this->convertPropertyExistence($constraint); } elseif ($constraint instanceof QOM\FullTextSearchInterface) { return $this->convertFullTextSearch($constraint); } + if ($constraint instanceof QOM\SameNodeInterface) { throw new NotSupportedConstraintException($constraint); } + if ($constraint instanceof QOM\ChildNodeInterface) { return $this->generator->evalChildNode( $this->convertPath($constraint->getParentPath())); } + if ($constraint instanceof QOM\DescendantNodeInterface) { return $this->generator->evalDescendantNode( $this->convertPath($constraint->getAncestorPath())); @@ -102,23 +111,29 @@ protected function convertDynamicOperand(QOM\DynamicOperandInterface $operand) if ($operand instanceof QOM\PropertyValueInterface) { return $this->convertPropertyValue($operand); } + if ($operand instanceof QOM\LengthInterface) { throw new NotSupportedOperandException($operand); } + if ($operand instanceof QOM\NodeNameInterface) { throw new NotSupportedOperandException($operand); } + if ($operand instanceof QOM\NodeLocalNameInterface) { throw new NotSupportedOperandException($operand); } + if ($operand instanceof QOM\FullTextSearchScoreInterface) { throw new NotSupportedOperandException($operand); } + if ($operand instanceof QOM\LowerCaseInterface) { $operand = $this->convertDynamicOperand($operand->getOperand()); return $this->generator->evalLower($operand); } + if ($operand instanceof QOM\UpperCaseInterface) { $operand = $this->convertDynamicOperand($operand->getOperand()); diff --git a/src/PHPCR/Util/QOM/QomToSql2QueryConverter.php b/src/PHPCR/Util/QOM/QomToSql2QueryConverter.php index 764af27..45f2601 100644 --- a/src/PHPCR/Util/QOM/QomToSql2QueryConverter.php +++ b/src/PHPCR/Util/QOM/QomToSql2QueryConverter.php @@ -193,32 +193,39 @@ protected function convertConstraint(QOM\ConstraintInterface $constraint) $this->convertConstraint($constraint->getConstraint1()), $this->convertConstraint($constraint->getConstraint2())); } + if ($constraint instanceof QOM\OrInterface) { return $this->generator->evalOr( $this->convertConstraint($constraint->getConstraint1()), $this->convertConstraint($constraint->getConstraint2())); } + if ($constraint instanceof QOM\NotInterface) { return $this->generator->evalNot($this->convertConstraint($constraint->getConstraint())); } + if ($constraint instanceof QOM\ComparisonInterface) { return $this->convertComparison($constraint); } + if ($constraint instanceof QOM\PropertyExistenceInterface) { return $this->convertPropertyExistence($constraint); } elseif ($constraint instanceof QOM\FullTextSearchInterface) { return $this->convertFullTextSearch($constraint); } + if ($constraint instanceof QOM\SameNodeInterface) { return $this->generator->evalSameNode( $this->convertPath($constraint->getPath()), $constraint->getSelectorName()); } + if ($constraint instanceof QOM\ChildNodeInterface) { return $this->generator->evalChildNode( $this->convertPath($constraint->getParentPath()), $constraint->getSelectorName()); } + if ($constraint instanceof QOM\DescendantNodeInterface) { return $this->generator->evalDescendantNode( $this->convertPath($constraint->getAncestorPath()), @@ -252,6 +259,7 @@ protected function convertDynamicOperand(QOM\DynamicOperandInterface $operand) if ($operand instanceof QOM\PropertyValueInterface) { return $this->convertPropertyValue($operand); } + if ($operand instanceof QOM\LengthInterface) { return $this->generator->evalLength($this->convertPropertyValue($operand->getPropertyValue())); } @@ -263,14 +271,17 @@ protected function convertDynamicOperand(QOM\DynamicOperandInterface $operand) if ($operand instanceof QOM\NodeLocalNameInterface) { return $this->generator->evalNodeLocalName($operand->getSelectorName()); } + if ($operand instanceof QOM\FullTextSearchScoreInterface) { return $this->generator->evalFullTextSearchScore($operand->getSelectorName()); } + if ($operand instanceof QOM\LowerCaseInterface) { $operand = $this->convertDynamicOperand($operand->getOperand()); return $this->generator->evalLower($operand); } + if ($operand instanceof QOM\UpperCaseInterface) { $operand = $this->convertDynamicOperand($operand->getOperand()); diff --git a/src/PHPCR/Util/QOM/QueryBuilder.php b/src/PHPCR/Util/QOM/QueryBuilder.php index 607207d..5626ca4 100644 --- a/src/PHPCR/Util/QOM/QueryBuilder.php +++ b/src/PHPCR/Util/QOM/QueryBuilder.php @@ -13,6 +13,7 @@ use PHPCR\Query\QOM\QueryObjectModelConstantsInterface; use PHPCR\Query\QueryInterface; use PHPCR\Query\QOM\QueryObjectModelInterface; +use PHPCR\Query\QueryResultInterface; use RuntimeException; /** @@ -54,7 +55,7 @@ class QueryBuilder /** * @var array with the orderings that determine the order of the result */ - private $orderings = array(); + private $orderings = []; /** * @var ConstraintInterface to apply to the query. @@ -64,7 +65,7 @@ class QueryBuilder /** * @var array with the columns to be selected. */ - private $columns = array(); + private $columns = []; /** * @var SourceInterface source of the query. @@ -81,7 +82,7 @@ class QueryBuilder /** * @var array The query parameters. */ - private $params = array(); + private $params = []; /** * Initializes a new QueryBuilder @@ -216,7 +217,7 @@ public function addOrderBy(DynamicOperandInterface $sort, $order = 'ASC') { $order = strtoupper($order); - if (!in_array($order, array('ASC', 'DESC'))) { + if (!in_array($order, ['ASC', 'DESC'])) { throw new InvalidArgumentException('Order must be one of "ASC" or "DESC"'); } @@ -294,6 +295,7 @@ public function getConstraint() public function andWhere(ConstraintInterface $constraint) { $this->state = self::STATE_DIRTY; + if ($this->constraint) { $this->constraint = $this->qomFactory->andConstraint($this->constraint, $constraint); } else { @@ -323,6 +325,7 @@ public function andWhere(ConstraintInterface $constraint) public function orWhere(ConstraintInterface $constraint) { $this->state = self::STATE_DIRTY; + if ($this->constraint) { $this->constraint = $this->qomFactory->orConstraint($this->constraint, $constraint); } else { @@ -369,7 +372,7 @@ public function setColumns(array $columns) public function select($selectorName, $propertyName, $columnName = null) { $this->state = self::STATE_DIRTY; - $this->columns = array($this->qomFactory->column($selectorName, $propertyName, $columnName)); + $this->columns = [$this->qomFactory->column($selectorName, $propertyName, $columnName)]; return $this; } @@ -386,6 +389,7 @@ public function select($selectorName, $propertyName, $columnName = null) public function addSelect($selectorName, $propertyName, $columnName = null) { $this->state = self::STATE_DIRTY; + $this->columns[] = $this->qomFactory->column($selectorName, $propertyName, $columnName); return $this; @@ -493,6 +497,7 @@ public function joinWithType(SourceInterface $rightSource, $joinType, JoinCondit if (!$this->source) { throw new RuntimeException('Cannot perform a join without a previous call to from'); } + $this->state = self::STATE_DIRTY; $this->source = $this->qomFactory->join($this->source, $rightSource, $joinType, $joinCondition); @@ -509,6 +514,7 @@ public function getQuery() if ($this->query !== null && $this->state === self::STATE_CLEAN) { return $this->query; } + $this->state = self::STATE_CLEAN; $this->query = $this->qomFactory->createQuery($this->source, $this->constraint, $this->orderings, $this->columns); @@ -526,7 +532,7 @@ public function getQuery() /** * Executes the query setting firstResult and maxResults. * - * @return \PHPCR\Query\QueryResultInterface + * @return QueryResultInterface */ public function execute() { @@ -538,9 +544,7 @@ public function execute() $this->query->bindValue($key, $value); } - $queryResult = $this->query->execute(); - - return $queryResult; + return $this->query->execute(); } /** diff --git a/src/PHPCR/Util/QOM/Sql1Generator.php b/src/PHPCR/Util/QOM/Sql1Generator.php index d2b2749..2f9d6c4 100644 --- a/src/PHPCR/Util/QOM/Sql1Generator.php +++ b/src/PHPCR/Util/QOM/Sql1Generator.php @@ -2,8 +2,6 @@ namespace PHPCR\Util\QOM; -use PHPCR\Query\QOM; - /** * Generate SQL1 statements. * @@ -72,9 +70,8 @@ public function evalChildNode($path, $selectorName = null) public function evalDescendantNode($path) { $path = $this->getPathForDescendantQuery($path); - $sql1 = "jcr:path LIKE '" . $path . "'"; - return $sql1; + return "jcr:path LIKE '" . $path . "'"; } /** diff --git a/src/PHPCR/Util/QOM/Sql2Scanner.php b/src/PHPCR/Util/QOM/Sql2Scanner.php index f55254f..e69ef25 100644 --- a/src/PHPCR/Util/QOM/Sql2Scanner.php +++ b/src/PHPCR/Util/QOM/Sql2Scanner.php @@ -156,14 +156,14 @@ public function tokenIs($token, $value, $case_insensitive = true) */ protected function scan($sql2) { - $tokens = array(); + $tokens = []; $token = strtok($sql2, " \n\t"); while ($token !== false) { $this->tokenize($tokens, $token); $token = strtok(" \n\t"); } - $regexpTokens = array(); + $regexpTokens = []; foreach ($tokens as $token) { $regexpTokens[] = preg_quote($token, '/'); } @@ -187,7 +187,7 @@ protected function tokenize(&$tokens, $token) $buffer = ''; for ($i = 0; $i < strlen($token); $i++) { $char = trim(substr($token, $i, 1)); - if (in_array($char, array('.', ',', '(', ')', '='))) { + if (in_array($char, ['.', ',', '(', ')', '='])) { if ($buffer !== '') { $tokens[] = $buffer; $buffer = ''; diff --git a/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php b/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php index 78ff818..f08ecf9 100644 --- a/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php +++ b/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php @@ -150,7 +150,8 @@ protected function parseSource() $next = $this->scanner->lookupNextToken(); $left = $selector; - while (in_array(strtoupper($next), array('JOIN', 'INNER', 'RIGHT', 'LEFT'))) { + + while (in_array(strtoupper($next), ['JOIN', 'INNER', 'RIGHT', 'LEFT'])) { $left = $this->parseJoin($left); $next = $this->scanner->lookupNextToken(); } @@ -317,7 +318,7 @@ protected function parseSameNodeJoinCondition() */ protected function parseChildNodeJoinCondition() { - $this->scanner->expectTokens(array('ISCHILDNODE', '(')); + $this->scanner->expectTokens(['ISCHILDNODE', '(']); $child = $this->fetchTokenWithoutBrackets(); $this->scanner->expectToken(','); $parent = $this->fetchTokenWithoutBrackets(); @@ -532,7 +533,7 @@ protected function parsePropertyExistence() return $this->factory->notConstraint($this->factory->propertyExistence($selectorName, $prop)); } - $this->scanner->expectTokens(array('NOT', 'NULL')); + $this->scanner->expectTokens(['NOT', 'NULL']); return $this->factory->propertyExistence($selectorName, $prop); } @@ -544,7 +545,7 @@ protected function parsePropertyExistence() */ protected function parseFullTextSearch() { - $this->scanner->expectTokens(array('CONTAINS', '(')); + $this->scanner->expectTokens(['CONTAINS', '(']); list($selectorName, $propertyName) = $this->parseIdentifier(); $this->scanner->expectToken(','); @@ -559,7 +560,7 @@ protected function parseFullTextSearch() */ protected function parseSameNode() { - $this->scanner->expectTokens(array('ISSAMENODE', '(')); + $this->scanner->expectTokens(['ISSAMENODE', '(']); if ($this->scanner->tokenIs($this->scanner->lookupNextToken(1), ',')) { $selectorName = $this->scanner->fetchNextToken(); $this->scanner->expectToken(','); @@ -578,7 +579,7 @@ protected function parseSameNode() */ protected function parseChildNode() { - $this->scanner->expectTokens(array('ISCHILDNODE', '(')); + $this->scanner->expectTokens(['ISCHILDNODE', '(']); if ($this->scanner->tokenIs($this->scanner->lookupNextToken(1), ',')) { $selectorName = $this->scanner->fetchNextToken(); $this->scanner->expectToken(','); @@ -597,7 +598,7 @@ protected function parseChildNode() */ protected function parseDescendantNode() { - $this->scanner->expectTokens(array('ISDESCENDANTNODE', '(')); + $this->scanner->expectTokens(['ISDESCENDANTNODE', '(']); if ($this->scanner->tokenIs($this->scanner->lookupNextToken(1), ',')) { $selectorName = $this->scanner->fetchNextToken(); $this->scanner->expectToken(','); @@ -856,8 +857,9 @@ protected function parseLiteralValue() */ protected function parseOrderings() { - $orderings = array(); + $orderings = []; $continue = true; + while ($continue) { $orderings[] = $this->parseOrdering(); if ($this->scanner->tokenIs($this->scanner->lookupNextToken(), ',')) { @@ -911,10 +913,10 @@ protected function scanColumns() if ($this->scanner->lookupNextToken() === '*') { $this->scanner->fetchNextToken(); - return array(); + return []; } - $columns = array(); + $columns = []; $hasNext = true; while ($hasNext) { @@ -940,7 +942,7 @@ protected function scanColumns() */ protected function buildColumns($data) { - $columns = array(); + $columns = []; foreach ($data as $col) { $columns[] = $this->buildColumn($col); } diff --git a/src/PHPCR/Util/TraversingItemVisitor.php b/src/PHPCR/Util/TraversingItemVisitor.php index 468495d..f2695b4 100644 --- a/src/PHPCR/Util/TraversingItemVisitor.php +++ b/src/PHPCR/Util/TraversingItemVisitor.php @@ -153,7 +153,7 @@ abstract protected function leaving(ItemInterface $item, $depth); */ public function visit(ItemInterface $item) { - if ($this->currentDepth == 0) { + if ($this->currentDepth === 0) { $this->currentDepth = $item->getDepth(); } if ($item instanceof PropertyInterface) { diff --git a/src/PHPCR/Util/TreeWalker.php b/src/PHPCR/Util/TreeWalker.php index 37bf9f0..5c2b22b 100644 --- a/src/PHPCR/Util/TreeWalker.php +++ b/src/PHPCR/Util/TreeWalker.php @@ -35,14 +35,14 @@ class TreeWalker * * @var TreeWalkerFilterInterface[] */ - protected $nodeFilters = array(); + protected $nodeFilters = []; /** * Filters to apply to decide whether a property needs to be visited * * @var TreeWalkerFilterInterface[] */ - protected $propertyFilters = array(); + protected $propertyFilters = []; /** * Instantiate a tree walker diff --git a/src/PHPCR/Util/UUIDHelper.php b/src/PHPCR/Util/UUIDHelper.php index 28b2899..faaa39f 100644 --- a/src/PHPCR/Util/UUIDHelper.php +++ b/src/PHPCR/Util/UUIDHelper.php @@ -41,7 +41,7 @@ public static function isUUID($id) */ public static function generateUUID() { - if (class_exists('Ramsey\Uuid\Uuid')) { + if (class_exists(Uuid::class)) { $uuid4 = Uuid::uuid4(); return $uuid4->toString(); diff --git a/src/PHPCR/Util/ValueConverter.php b/src/PHPCR/Util/ValueConverter.php index d4aca45..155d068 100644 --- a/src/PHPCR/Util/ValueConverter.php +++ b/src/PHPCR/Util/ValueConverter.php @@ -3,6 +3,8 @@ namespace PHPCR\Util; use DateTime; +use Exception; +use InvalidArgumentException; use PHPCR\NodeInterface; use PHPCR\PropertyInterface; use PHPCR\PropertyType; @@ -104,29 +106,29 @@ public function determineType($value, $weak = false) * * @param mixed $value The value or value array to check and convert * @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) + * @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) * * @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 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) + public function convertType($value, $type, $srcType = PropertyType::UNDEFINED) { if (is_array($value)) { $ret = array(); foreach ($value as $v) { - $ret[] = self::convertType($v, $type, $srctype); + $ret[] = self::convertType($v, $type, $srcType); } return $ret; } - if (PropertyType::UNDEFINED === $srctype) { - $srctype = $this->determineType($value); + if (PropertyType::UNDEFINED === $srcType) { + $srcType = $this->determineType($value); } if ($value instanceof PropertyInterface) { @@ -134,12 +136,12 @@ public function convertType($value, $type, $srctype = PropertyType::UNDEFINED) } // except on noop, stream needs to be read into string first - if (PropertyType::BINARY === $srctype && PropertyType::BINARY !== $type && is_resource($value)) { + if (PropertyType::BINARY === $srcType && PropertyType::BINARY !== $type && is_resource($value)) { $t = stream_get_contents($value); rewind($value); $value = $t; - $srctype = PropertyType::STRING; - } elseif ((PropertyType::REFERENCE === $srctype || PropertyType::WEAKREFERENCE === $srctype) + $srcType = PropertyType::STRING; + } elseif ((PropertyType::REFERENCE === $srcType || PropertyType::WEAKREFERENCE === $srcType) && $value instanceof NodeInterface ) { /** @var $value NodeInterface */ @@ -151,7 +153,7 @@ public function convertType($value, $type, $srctype = PropertyType::UNDEFINED) switch ($type) { case PropertyType::STRING: - switch ($srctype) { + switch ($srcType) { case PropertyType::DATE: if (! $value instanceof DateTime) { throw new RepositoryException('Cannot convert a date that is not a \DateTime instance to string'); @@ -183,7 +185,7 @@ public function convertType($value, $type, $srctype = PropertyType::UNDEFINED) return $value; } if (! is_string($value)) { - $value = $this->convertType($value, PropertyType::STRING, $srctype); + $value = $this->convertType($value, PropertyType::STRING, $srcType); } $f = fopen('php://memory', 'rwb+'); fwrite($f, $value); @@ -192,7 +194,7 @@ public function convertType($value, $type, $srctype = PropertyType::UNDEFINED) return $f; case PropertyType::LONG: - switch ($srctype) { + switch ($srcType) { case PropertyType::STRING: case PropertyType::LONG: case PropertyType::DOUBLE: @@ -213,7 +215,7 @@ public function convertType($value, $type, $srctype = PropertyType::UNDEFINED) throw new ValueFormatException('Cannot convert "'.var_export($value, true).'" to a LONG'); case PropertyType::DOUBLE: - switch ($srctype) { + switch ($srcType) { case PropertyType::STRING: case PropertyType::LONG: case PropertyType::DOUBLE: @@ -235,7 +237,7 @@ public function convertType($value, $type, $srctype = PropertyType::UNDEFINED) throw new ValueFormatException('Cannot convert "'.var_export($value, true).'" to a DOUBLE'); case PropertyType::DATE: - switch ($srctype) { + switch ($srcType) { case PropertyType::STRING: case PropertyType::DATE: if ($value instanceof DateTime) { @@ -243,7 +245,7 @@ public function convertType($value, $type, $srctype = PropertyType::UNDEFINED) } try { return new DateTime($value); - } catch (\Exception $e) { + } catch (Exception $e) { throw new ValueFormatException("String '$value' is not a valid date", null, $e); } case PropertyType::LONG: @@ -260,14 +262,14 @@ public function convertType($value, $type, $srctype = PropertyType::UNDEFINED) throw new ValueFormatException('Cannot convert "'.var_export($value, true).'" to DATE'); case PropertyType::BOOLEAN: - switch ($srctype) { + switch ($srcType) { case PropertyType::STRING: case PropertyType::LONG: case PropertyType::DOUBLE: case PropertyType::BOOLEAN: return (boolean) $value; case PropertyType::DATE: - /** @var $value \DateTime */ + /** @var $value DateTime */ return (boolean) $value->getTimestamp(); case PropertyType::DECIMAL: @@ -279,7 +281,7 @@ public function convertType($value, $type, $srctype = PropertyType::UNDEFINED) throw new ValueFormatException('Cannot convert "'.var_export($value, true).'" to a BOOLEAN'); case PropertyType::NAME: - switch ($srctype) { + switch ($srcType) { case PropertyType::STRING: case PropertyType::PATH: case PropertyType::NAME: @@ -295,7 +297,7 @@ public function convertType($value, $type, $srctype = PropertyType::UNDEFINED) throw new ValueFormatException('Cannot convert "'.var_export($value, true).'" to NAME'); case PropertyType::PATH: - switch ($srctype) { + switch ($srcType) { case PropertyType::STRING: // TODO: check if valid return $value; @@ -313,7 +315,7 @@ public function convertType($value, $type, $srctype = PropertyType::UNDEFINED) case PropertyType::REFERENCE: case PropertyType::WEAKREFERENCE: - switch ($srctype) { + switch ($srcType) { case PropertyType::STRING: case PropertyType::REFERENCE: case PropertyType::WEAKREFERENCE: @@ -330,7 +332,7 @@ public function convertType($value, $type, $srctype = PropertyType::UNDEFINED) throw new ValueFormatException('Cannot convert "'.var_export($value, true).'" to unique id'); case PropertyType::URI: - switch ($srctype) { + switch ($srcType) { case PropertyType::STRING: // TODO: check if valid return $value; @@ -354,7 +356,7 @@ public function convertType($value, $type, $srctype = PropertyType::UNDEFINED) throw new ValueFormatException('Cannot convert "'.var_export($value, true).'" to URI'); case PropertyType::DECIMAL: - switch ($srctype) { + switch ($srcType) { case PropertyType::STRING: // TODO: validate return $value; @@ -374,7 +376,7 @@ public function convertType($value, $type, $srctype = PropertyType::UNDEFINED) throw new ValueFormatException('Cannot convert "'.var_export($value, true).'" to a DECIMAL'); default: - throw new ValueFormatException('Unexpected target type "' . $type . '" in conversion'); + throw new ValueFormatException("Unexpected target type '$type' in conversion"); } } } diff --git a/tests/PHPCR/Tests/Stubs/MockNode.php b/tests/PHPCR/Tests/Stubs/MockNode.php index ea93721..e024939 100644 --- a/tests/PHPCR/Tests/Stubs/MockNode.php +++ b/tests/PHPCR/Tests/Stubs/MockNode.php @@ -2,8 +2,9 @@ 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 97f696f..7cd4660 100644 --- a/tests/PHPCR/Tests/Stubs/MockNodeTypeManager.php +++ b/tests/PHPCR/Tests/Stubs/MockNodeTypeManager.php @@ -2,8 +2,9 @@ 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 298e2be..4507722 100644 --- a/tests/PHPCR/Tests/Stubs/MockRow.php +++ b/tests/PHPCR/Tests/Stubs/MockRow.php @@ -2,8 +2,9 @@ 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 699f3bd..442019b 100644 --- a/tests/PHPCR/Tests/Util/CND/Reader/BufferReaderTest.php +++ b/tests/PHPCR/Tests/Util/CND/Reader/BufferReaderTest.php @@ -3,15 +3,16 @@ namespace PHPCR\Tests\Util\CND\Reader; use PHPCR\Util\CND\Reader\BufferReader; +use PHPUnit_Framework_TestCase; -class BufferReaderTest extends \PHPUnit_Framework_TestCase +class BufferReaderTest extends PHPUnit_Framework_TestCase { public function test__construct() { $buffer = "Some random\nor\r\nstring"; $reader = new BufferReader($buffer); - $this->assertInstanceOf('\PHPCR\Util\CND\Reader\BufferReader', $reader); + $this->assertInstanceOf(BufferReader::class, $reader); $this->assertAttributeEquals(str_replace("\r\n", "\n", $buffer) . $reader->getEofMarker(), 'buffer', $reader); $this->assertAttributeEquals(0, 'startPos', $reader); $this->assertAttributeEquals(0, 'forwardPos', $reader); @@ -89,7 +90,7 @@ public function test__constructEmptyString() { $reader = new BufferReader(''); - $this->assertInstanceOf('\PHPCR\Util\CND\Reader\BufferReader', $reader); + $this->assertInstanceOf(BufferReader::class, $reader); $this->assertAttributeEquals($reader->getEofMarker(), 'buffer', $reader); $this->assertAttributeEquals(0, 'startPos', $reader); $this->assertAttributeEquals(0, 'forwardPos', $reader); diff --git a/tests/PHPCR/Tests/Util/CND/Reader/FileReaderTest.php b/tests/PHPCR/Tests/Util/CND/Reader/FileReaderTest.php index 4b90f69..c6926d7 100644 --- a/tests/PHPCR/Tests/Util/CND/Reader/FileReaderTest.php +++ b/tests/PHPCR/Tests/Util/CND/Reader/FileReaderTest.php @@ -2,36 +2,52 @@ namespace PHPCR\Tests\Util\CND\Reader; +use InvalidArgumentException; use PHPCR\Util\CND\Reader\FileReader; +use PHPUnit_Framework_TestCase; -class FileReaderTest extends \PHPUnit_Framework_TestCase +class FileReaderTest extends PHPUnit_Framework_TestCase { + /** + * @var string + */ + private $filepath; + + /** + * @var FileReader + */ + private $reader; + + /** + * @var array + */ + private $lines; + public function setUp() { $this->filepath = __DIR__ . '/../Fixtures/files/TestFile.txt'; $this->reader = new FileReader($this->filepath); - $this->lines = array( + $this->lines = [ 'This is a test file...', '', '...containing dummy content.', '' - ); + ]; $this->chars = array_merge( preg_split('//', $this->lines[0], -1, PREG_SPLIT_NO_EMPTY), - array("\n", "\n"), + ["\n", "\n"], preg_split('//', $this->lines[2], -1, PREG_SPLIT_NO_EMPTY), - array("\n", "\n") + ["\n", "\n"] ); } - /** - * @expectedException \InvalidArgumentException - */ public function test__construct_fileNotFound() { - $reader = new FileReader('unexisting_file'); + $this->expectException(InvalidArgumentException::class); + + new FileReader('unexisting_file'); } public function testGetPath() diff --git a/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php b/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php index f77c299..9c21956 100644 --- a/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php +++ b/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php @@ -2,111 +2,115 @@ namespace PHPCR\Tests\Util\CND\Scanner; +use ArrayIterator; use PHPCR\Util\CND\Scanner\GenericScanner; use PHPCR\Util\CND\Reader\FileReader; use PHPCR\Util\CND\Scanner\GenericToken as Token; use PHPCR\Util\CND\Scanner\TokenQueue; use PHPCR\Util\CND\Scanner\TokenFilter; use PHPCR\Util\CND\Scanner\Context\DefaultScannerContext; +use PHPUnit_Framework_TestCase; +use Test; +use TestClass; -class GenericScannerTest extends \PHPUnit_Framework_TestCase +class GenericScannerTest extends PHPUnit_Framework_TestCase { - protected $expectedTokens = array( + protected $expectedTokens = [ // - array(Token::TK_SYMBOL, '<'), - array(Token::TK_SYMBOL, '?'), - array(Token::TK_IDENTIFIER, 'php'), - array(Token::TK_NEWLINE, ''), - array(Token::TK_NEWLINE, ''), + [Token::TK_SYMBOL, '<'], + [Token::TK_SYMBOL, '?'], + [Token::TK_IDENTIFIER, 'php'], + [Token::TK_NEWLINE, ''], + [Token::TK_NEWLINE, ''], // namespace Test\Foobar; - array(Token::TK_IDENTIFIER, 'namespace'), - array(Token::TK_WHITESPACE, ''), - array(Token::TK_IDENTIFIER, 'Test'), - array(Token::TK_SYMBOL, '\\'), - array(Token::TK_IDENTIFIER, 'Foobar'), - array(Token::TK_SYMBOL, ';'), - array(Token::TK_NEWLINE, ''), - array(Token::TK_NEWLINE, ''), + [Token::TK_IDENTIFIER, 'namespace'], + [Token::TK_WHITESPACE, ''], + [Token::TK_IDENTIFIER, Test::class], + [Token::TK_SYMBOL, '\\'], + [Token::TK_IDENTIFIER, 'Foobar'], + [Token::TK_SYMBOL, ';'], + [Token::TK_NEWLINE, ''], + [Token::TK_NEWLINE, ''], // class TestClass { - array(Token::TK_IDENTIFIER, 'class'), - array(Token::TK_WHITESPACE, ''), - array(Token::TK_IDENTIFIER, 'TestClass'), - array(Token::TK_NEWLINE, ''), - array(Token::TK_SYMBOL, '{'), - array(Token::TK_NEWLINE, ''), + [Token::TK_IDENTIFIER, 'class'], + [Token::TK_WHITESPACE, ''], + [Token::TK_IDENTIFIER, TestClass::class], + [Token::TK_NEWLINE, ''], + [Token::TK_SYMBOL, '{'], + [Token::TK_NEWLINE, ''], // /** ... */ - array(Token::TK_WHITESPACE, ''), - array(Token::TK_COMMENT, "/**\n * Block comment\n */"), - array(Token::TK_NEWLINE, ''), + [Token::TK_WHITESPACE, ''], + [Token::TK_COMMENT, "/**\n * Block comment\n */"], + [Token::TK_NEWLINE, ''], // public function testMethod($testParam) { - array(Token::TK_WHITESPACE, ''), - array(Token::TK_IDENTIFIER, 'public'), - array(Token::TK_WHITESPACE, ''), - array(Token::TK_IDENTIFIER, 'function'), - array(Token::TK_WHITESPACE, ''), - array(Token::TK_IDENTIFIER, 'testMethod'), - array(Token::TK_SYMBOL, '('), - array(Token::TK_SYMBOL, '$'), - array(Token::TK_IDENTIFIER, 'testParam'), - array(Token::TK_SYMBOL, ')'), - array(Token::TK_NEWLINE, ''), - array(Token::TK_WHITESPACE, ''), - array(Token::TK_SYMBOL, '{'), - array(Token::TK_NEWLINE, ''), + [Token::TK_WHITESPACE, ''], + [Token::TK_IDENTIFIER, 'public'], + [Token::TK_WHITESPACE, ''], + [Token::TK_IDENTIFIER, 'function'], + [Token::TK_WHITESPACE, ''], + [Token::TK_IDENTIFIER, 'testMethod'], + [Token::TK_SYMBOL, '('], + [Token::TK_SYMBOL, '$'], + [Token::TK_IDENTIFIER, 'testParam'], + [Token::TK_SYMBOL, ')'], + [Token::TK_NEWLINE, ''], + [Token::TK_WHITESPACE, ''], + [Token::TK_SYMBOL, '{'], + [Token::TK_NEWLINE, ''], // // Line comment - array(Token::TK_WHITESPACE, ''), - array(Token::TK_COMMENT, '// Line comment'), - array(Token::TK_NEWLINE, ''), + [Token::TK_WHITESPACE, ''], + [Token::TK_COMMENT, '// Line comment'], + [Token::TK_NEWLINE, ''], // $string = 'This is a "Test // string"'; - array(Token::TK_WHITESPACE, ''), - array(Token::TK_SYMBOL, '$'), - array(Token::TK_IDENTIFIER, 'string'), - array(Token::TK_WHITESPACE, ''), - array(Token::TK_SYMBOL, '='), - array(Token::TK_WHITESPACE, ''), - array(Token::TK_STRING, '\'This is a "Test // string"\''), - array(Token::TK_SYMBOL, ';'), - array(Token::TK_NEWLINE, ''), + [Token::TK_WHITESPACE, ''], + [Token::TK_SYMBOL, '$'], + [Token::TK_IDENTIFIER, 'string'], + [Token::TK_WHITESPACE, ''], + [Token::TK_SYMBOL, '='], + [Token::TK_WHITESPACE, ''], + [Token::TK_STRING, '\'This is a "Test // string"\''], + [Token::TK_SYMBOL, ';'], + [Token::TK_NEWLINE, ''], // empty line before return - array(Token::TK_NEWLINE, ''), + [Token::TK_NEWLINE, ''], // return "Test string"; - array(Token::TK_WHITESPACE, ''), - array(Token::TK_IDENTIFIER, 'return'), - array(Token::TK_WHITESPACE, ''), - array(Token::TK_STRING, '"Test string"'), - array(Token::TK_SYMBOL, ';'), - array(Token::TK_NEWLINE, ''), + [Token::TK_WHITESPACE, ''], + [Token::TK_IDENTIFIER, 'return'], + [Token::TK_WHITESPACE, ''], + [Token::TK_STRING, '"Test string"'], + [Token::TK_SYMBOL, ';'], + [Token::TK_NEWLINE, ''], // } - array(Token::TK_WHITESPACE, ''), - array(Token::TK_SYMBOL, '}'), - array(Token::TK_NEWLINE, ''), - array(Token::TK_NEWLINE, ''), + [Token::TK_WHITESPACE, ''], + [Token::TK_SYMBOL, '}'], + [Token::TK_NEWLINE, ''], + [Token::TK_NEWLINE, ''], // // String in "comment" - array(Token::TK_WHITESPACE, ''), - array(Token::TK_COMMENT, '// String in "comment"'), - array(Token::TK_NEWLINE, ''), + [Token::TK_WHITESPACE, ''], + [Token::TK_COMMENT, '// String in "comment"'], + [Token::TK_NEWLINE, ''], // } - array(Token::TK_SYMBOL, '}'), - array(Token::TK_NEWLINE, ''), - ); + [Token::TK_SYMBOL, '}'], + [Token::TK_NEWLINE, ''], + ]; protected $expectedTokensNoEmptyToken; public function setUp() { - $this->expectedTokensNoEmptyToken = array(); + $this->expectedTokensNoEmptyToken = []; foreach ($this->expectedTokens as $token) { if ($token[0] !== Token::TK_NEWLINE && $token[0] !== Token::TK_WHITESPACE) { $this->expectedTokensNoEmptyToken[] = $token; @@ -142,7 +146,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/TokenQueueTest.php b/tests/PHPCR/Tests/Util/CND/Scanner/TokenQueueTest.php index 17455df..30501f7 100644 --- a/tests/PHPCR/Tests/Util/CND/Scanner/TokenQueueTest.php +++ b/tests/PHPCR/Tests/Util/CND/Scanner/TokenQueueTest.php @@ -4,9 +4,35 @@ use PHPCR\Util\CND\Scanner\Token; use PHPCR\Util\CND\Scanner\TokenQueue; +use PHPUnit_Framework_TestCase; -class TokenQueueTest extends \PHPUnit_Framework_TestCase +class TokenQueueTest extends PHPUnit_Framework_TestCase { + /** + * @var Token + */ + private $token0; + + /** + * @var Token + */ + private $token1; + + /** + * @var Token + */ + private $token2; + + /** + * @var Token + */ + private $token3; + + /** + * @var TokenQueue + */ + private $queue; + public function setUp() { $this->token0 = new Token(0, 'token 0'); @@ -24,13 +50,13 @@ public function setUp() public function testAdd() { $queue = new TokenQueue(); - $this->assertAttributeEquals(array(), 'tokens', $queue); + $this->assertAttributeEquals([], 'tokens', $queue); $queue->add($this->token0); - $this->assertAttributeEquals(array($this->token0), 'tokens', $queue); + $this->assertAttributeEquals([$this->token0], 'tokens', $queue); $queue->add($this->token1); - $this->assertAttributeEquals(array($this->token0, $this->token1), 'tokens', $queue); + $this->assertAttributeEquals([$this->token0, $this->token1], 'tokens', $queue); } public function testResetAndPeek() diff --git a/tests/PHPCR/Tests/Util/CND/Scanner/TokenTest.php b/tests/PHPCR/Tests/Util/CND/Scanner/TokenTest.php index c4fdf55..442b3df 100644 --- a/tests/PHPCR/Tests/Util/CND/Scanner/TokenTest.php +++ b/tests/PHPCR/Tests/Util/CND/Scanner/TokenTest.php @@ -3,9 +3,15 @@ namespace PHPCR\Tests\Util\CND\Scanner; use PHPCR\Util\CND\Scanner\Token; +use PHPUnit_Framework_TestCase; -class TokenTest extends \PHPUnit_Framework_TestCase +class TokenTest extends PHPUnit_Framework_TestCase { + /** + * @var Token + */ + private $token; + public function setUp() { $this->token = new Token(123, 'foobar'); diff --git a/tests/PHPCR/Tests/Util/Console/Command/BaseCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/BaseCommandTest.php index ce963a1..ce50cdc 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/BaseCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/BaseCommandTest.php @@ -6,6 +6,10 @@ use PHPCR\Query\QueryManagerInterface; use PHPCR\Query\RowInterface; use PHPCR\RepositoryInterface; +use PHPCR\Tests\Stubs\MockNode; +use PHPCR\Tests\Stubs\MockRow; +use PHPUnit_Framework_MockObject_MockObject; +use PHPUnit_Framework_TestCase; use Symfony\Component\Console\Application; use Symfony\Component\Console\Tester\CommandTester; use Symfony\Component\Console\Helper\HelperSet; @@ -14,44 +18,44 @@ use PHPCR\Util\Console\Helper\PhpcrConsoleDumperHelper; use PHPCR\Util\Console\Helper\PhpcrHelper; -require_once(__DIR__.'/../../../Stubs/MockNode.php'); -require_once(__DIR__.'/../../../Stubs/MockNodeTypeManager.php'); -require_once(__DIR__.'/../../../Stubs/MockRow.php'); +require_once __DIR__.'/../../../Stubs/MockNode.php'; +require_once __DIR__.'/../../../Stubs/MockNodeTypeManager.php'; +require_once __DIR__.'/../../../Stubs/MockRow.php'; -abstract class BaseCommandTest extends \PHPUnit_Framework_TestCase +abstract class BaseCommandTest extends PHPUnit_Framework_TestCase { /** - * @var SessionInterface|\PHPUnit_Framework_MockObject_MockObject + * @var SessionInterface|PHPUnit_Framework_MockObject_MockObject * */ public $session; /** - * @var WorkspaceInterface|\PHPUnit_Framework_MockObject_MockObject + * @var WorkspaceInterface|PHPUnit_Framework_MockObject_MockObject */ public $workspace; /** - * @var RepositoryInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RepositoryInterface|PHPUnit_Framework_MockObject_MockObject */ public $repository; /** - * @var PhpcrConsoleDumperHelper|\PHPUnit_Framework_MockObject_MockObject + * @var PhpcrConsoleDumperHelper|PHPUnit_Framework_MockObject_MockObject */ public $dumperHelper; /** - * @var NodeInterface|\PHPUnit_Framework_MockObject_MockObject + * @var NodeInterface|PHPUnit_Framework_MockObject_MockObject */ public $node1; /** - * @var RowInterface|\PHPUnit_Framework_MockObject_MockObject + * @var RowInterface|PHPUnit_Framework_MockObject_MockObject */ public $row1; /** - * @var QueryManagerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var QueryManagerInterface|PHPUnit_Framework_MockObject_MockObject */ public $queryManager; @@ -67,38 +71,43 @@ abstract class BaseCommandTest extends \PHPUnit_Framework_TestCase public function setUp() { - $this->session = $this->getMock('PHPCR\SessionInterface'); - $this->workspace = $this->getMock('PHPCR\WorkspaceInterface'); - $this->repository = $this->getMock('PHPCR\RepositoryInterface'); - $this->queryManager = $this->getMock('PHPCR\Query\QueryManagerInterface'); + $this->session = $this->createMock(SessionInterface::class); + $this->workspace = $this->createMock(WorkspaceInterface::class); + $this->repository = $this->createMock(RepositoryInterface::class); + $this->queryManager = $this->createMock(QueryManagerInterface::class); - $this->row1 = $this->getMock('PHPCR\Tests\Stubs\MockRow'); - $this->node1 = $this->getMock('PHPCR\Tests\Stubs\MockNode'); + $this->row1 = $this->createMock(MockRow::class); + $this->node1 = $this->createMock(MockNode::class); - $this->dumperHelper = $this->getMockBuilder( - 'PHPCR\Util\Console\Helper\PhpcrConsoleDumperHelper' - )->disableOriginalConstructor()->getMock(); + $this->dumperHelper = $this->getMockBuilder(PhpcrConsoleDumperHelper::class) + ->disableOriginalConstructor() + ->getMock() + ; - $this->helperSet = new HelperSet(array( + $this->helperSet = new HelperSet([ 'phpcr' => new PhpcrHelper($this->session), 'phpcr_console_dumper' => $this->dumperHelper, - )); + ]); $this->session->expects($this->any()) ->method('getWorkspace') - ->will($this->returnValue($this->workspace)); + ->will($this->returnValue($this->workspace)) + ; $this->workspace->expects($this->any()) ->method('getName') - ->will($this->returnValue('test')); + ->will($this->returnValue('test')) + ; $this->workspace->expects($this->any()) ->method('getQueryManager') - ->will($this->returnValue($this->queryManager)); + ->will($this->returnValue($this->queryManager)) + ; $this->queryManager->expects($this->any()) ->method('getSupportedQueryLanguages') - ->will($this->returnValue(array('JCR-SQL2'))); + ->will($this->returnValue(['JCR-SQL2'])) + ; $this->application = new Application(); $this->application->setHelperSet($this->helperSet); @@ -117,9 +126,7 @@ public function executeCommand($name, $args, $status = 0) { $command = $this->application->find($name); $commandTester = new CommandTester($command); - $args = array_merge(array( - 'command' => $command->getName(), - ), $args); + $args = array_merge(['command' => $command->getName()], $args); $this->assertEquals($status, $commandTester->execute($args)); return $commandTester; diff --git a/tests/PHPCR/Tests/Util/Console/Command/NodeDumpCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodeDumpCommandTest.php index e2c5c34..84727e3 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodeDumpCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodeDumpCommandTest.php @@ -2,9 +2,9 @@ namespace PHPCR\Tests\Util\Console\Command; +use Exception; use PHPCR\ItemNotFoundException; use PHPCR\Util\UUIDHelper; -use Symfony\Component\Console\Application; use PHPCR\Util\TreeWalker; use PHPCR\Util\Console\Command\NodeDumpCommand; @@ -16,9 +16,10 @@ class NodeDumpCommandTest extends BaseCommandTest public function setUp() { parent::setUp(); - $this->treeWalker = $this->getMockBuilder( - 'PHPCR\Util\TreeWalker' - )->disableOriginalConstructor()->getMock(); + $this->treeWalker = $this->getMockBuilder(TreeWalker::class) + ->disableOriginalConstructor() + ->getMock() + ; $ndCommand = new NodeDumpCommand(); $this->application->add($ndCommand); @@ -31,12 +32,14 @@ public function testCommand() ->method('getTreeWalker') ->will($this->returnValue($this->treeWalker)) ; + $this->session ->expects($this->once()) ->method('getNode') ->with('/') ->will($this->returnValue($this->node1)) ; + $this->treeWalker ->expects($this->once()) ->method('traverse') @@ -55,27 +58,28 @@ public function testCommandIdentifier() ->method('getTreeWalker') ->will($this->returnValue($this->treeWalker)) ; + $this->session ->expects($this->once()) ->method('getNodeByIdentifier') ->with($uuid) ->will($this->returnValue($this->node1)) ; + $this->treeWalker ->expects($this->once()) ->method('traverse') ->with($this->node1) ; - $this->executeCommand('phpcr:node:dump', array('identifier' => $uuid)); + $this->executeCommand('phpcr:node:dump', ['identifier' => $uuid]); } - /** - * @expectedException \Exception - */ public function testInvalidRefFormat() { - $this->executeCommand('phpcr:node:dump', array('--ref-format' => 'xy')); + $this->expectException(Exception::class); + + $this->executeCommand('phpcr:node:dump', ['--ref-format' => 'xy']); $this->fail('invalid ref-format did not produce exception'); } @@ -88,7 +92,7 @@ public function testNotFound() ->will($this->throwException(new ItemNotFoundException())) ; - $ct = $this->executeCommand('phpcr:node:dump', array(), 1); + $ct = $this->executeCommand('phpcr:node:dump', [], 1); $this->assertContains('does not exist', $ct->getDisplay()); } } diff --git a/tests/PHPCR/Tests/Util/Console/Command/NodeMoveCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodeMoveCommandTest.php index 487b2f7..3f0fcf5 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodeMoveCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodeMoveCommandTest.php @@ -2,16 +2,13 @@ namespace PHPCR\Tests\Util\Console\Command; -use Symfony\Component\Console\Application; use PHPCR\Util\Console\Command\NodeMoveCommand; class NodeMoveCommandTest extends BaseCommandTest { public function provideCommand() { - return array( - array(array('source' => '/foo', 'destination' => '/bar')) - ); + return [[['source' => '/foo', 'destination' => '/bar']]]; } /** @@ -21,9 +18,12 @@ public function testCommand($args) { $this->session->expects($this->once()) ->method('move') - ->with($args['source'], $args['destination']); + ->with($args['source'], $args['destination']) + ; + $this->session->expects($this->once()) - ->method('save'); + ->method('save') + ; $this->application->add(new NodeMoveCommand()); $this->executeCommand('phpcr:node:move', $args); diff --git a/tests/PHPCR/Tests/Util/Console/Command/NodeRemoveCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodeRemoveCommandTest.php index 4dcd02c..ac5e100 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodeRemoveCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodeRemoveCommandTest.php @@ -2,7 +2,7 @@ namespace PHPCR\Tests\Util\Console\Command; -use Symfony\Component\Console\Application; +use LogicException; use PHPCR\Util\Console\Command\NodeRemoveCommand; class NodeRemoveCommandTest extends BaseCommandTest @@ -10,6 +10,7 @@ class NodeRemoveCommandTest extends BaseCommandTest public function setUp() { parent::setUp(); + $this->application->add(new NodeRemoveCommand()); } @@ -19,18 +20,17 @@ public function testRemove() ->method('removeItem') ->with('/cms'); - $ct = $this->executeCommand('phpcr:node:remove', array( + $this->executeCommand('phpcr:node:remove', array( '--force' => true, 'path' => '/cms', )); } - /** - * @expectedException \LogicException - */ public function testRemoveRoot() { - $ct = $this->executeCommand('phpcr:node:remove', array( + $this->expectException(LogicException::class); + + $this->executeCommand('phpcr:node:remove', array( '--force' => true, 'path' => '/', )); diff --git a/tests/PHPCR/Tests/Util/Console/Command/NodeTouchCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodeTouchCommandTest.php index 5a4c63d..4d3d7d6 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodeTouchCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodeTouchCommandTest.php @@ -2,9 +2,11 @@ namespace PHPCR\Tests\Util\Console\Command; +use Exception; +use PHPCR\NodeType\NodeTypeInterface; use PHPCR\PathNotFoundException; +use PHPCR\Tests\Stubs\MockNode; use PHPCR\Util\Console\Helper\PhpcrHelper; -use Symfony\Component\Console\Application; use PHPCR\Util\Console\Command\NodeTouchCommand; /** @@ -20,29 +22,33 @@ class NodeTouchCommandTest extends BaseCommandTest public function setUp() { parent::setUp(); + $command = new NodeTouchCommand; $this->application->add($command); - // override default concrete instance with mock - $this->phpcrHelper = $this->getMockBuilder('PHPCR\Util\Console\Helper\PhpcrHelper') + // Override default concrete instance with mock + $this->phpcrHelper = $this->getMockBuilder(PhpcrHelper::class) ->disableOriginalConstructor() ->getMock() ; + $this->phpcrHelper->expects($this->any()) ->method('getSession') ->will($this->returnValue($this->session)) ; + $this->phpcrHelper->expects($this->any()) ->method('getName') ->will($this->returnValue('phpcr')) ; + $this->helperSet->set($this->phpcrHelper); } public function testTouch() { $node = $this->node1; - $child = $this->getMock('PHPCR\Tests\Stubs\MockNode'); + $child = $this->createMock(MockNode::class); $this->session->expects($this->exactly(2)) ->method('getNode') @@ -53,7 +59,7 @@ public function testTouch() case '/cms': throw new PathNotFoundException(); } - throw new \Exception('Unexpected ' . $path); + throw new Exception('Unexpected ' . $path); })); $this->node1->expects($this->once()) @@ -65,14 +71,12 @@ public function testTouch() $this->session->expects($this->once()) ->method('save'); - $this->executeCommand('phpcr:node:touch', array( - 'path' => '/cms', - )); + $this->executeCommand('phpcr:node:touch', ['path' => '/cms']); } public function testUpdate() { - $nodeType = $this->getMock('PHPCR\NodeType\NodeTypeInterface'); + $nodeType = $this->createMock(NodeTypeInterface::class); $nodeType->expects($this->once()) ->method('getName') ->will($this->returnValue('nt:unstructured')) @@ -83,6 +87,7 @@ public function testUpdate() ->with('/cms') ->will($this->returnValue($this->node1)) ; + $this->node1->expects($this->once()) ->method('getPrimaryNodeType') ->will($this->returnValue($nodeType)) @@ -94,22 +99,22 @@ public function testUpdate() ->method('processNode') ->will($this->returnCallback(function ($output, $node, $options) use ($me) { $me->assertEquals($me->node1, $node); - $me->assertEquals(array( - 'setProp' => array('foo=bar'), - 'removeProp' => array('bar'), - 'addMixins' => array('foo:bar'), - 'removeMixins' => array('bar:foo'), + $me->assertEquals([ + 'setProp' => ['foo=bar'], + 'removeProp' => ['bar'], + 'addMixins' => ['foo:bar'], + 'removeMixins' => ['bar:foo'], 'dump' => true, - ), $options); + ], $options); })); - $this->executeCommand('phpcr:node:touch', array( + $this->executeCommand('phpcr:node:touch', [ 'path' => '/cms', - '--set-prop' => array('foo=bar'), - '--remove-prop' => array('bar'), - '--add-mixin' => array('foo:bar'), - '--remove-mixin' => array('bar:foo'), + '--set-prop' => ['foo=bar'], + '--remove-prop' => ['bar'], + '--add-mixin' => ['foo:bar'], + '--remove-mixin' => ['bar:foo'], '--dump' => true, - )); + ]); } } diff --git a/tests/PHPCR/Tests/Util/Console/Command/NodeTypeListCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodeTypeListCommandTest.php index e7b28f9..d25dd73 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodeTypeListCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodeTypeListCommandTest.php @@ -2,32 +2,45 @@ namespace PHPCR\Tests\Util\Console\Command; -use Symfony\Component\Console\Application; +use PHPCR\Tests\Stubs\MockNodeTypeManager; use PHPCR\Util\Console\Command\NodeTypeListCommand; +use PHPUnit_Framework_MockObject_MockObject; class NodeTypeListCommandTest extends BaseCommandTest { + /** + * @var MockNodeTypeManager|PHPUnit_Framework_MockObject_MockObject + */ + private $nodeTypeManager; + public function setUp() { parent::setUp(); + $this->application->add(new NodeTypeListCommand()); - $this->nodeTypeManager = $this->getMockBuilder( - 'PHPCR\Tests\Stubs\MockNodeTypeManager' - )->disableOriginalConstructor()->getMock(); + $this->nodeTypeManager = $this->getMockBuilder(MockNodeTypeManager::class) + ->disableOriginalConstructor() + ->getMock() + ; } public function testNodeTypeList() { $this->session->expects($this->once()) ->method('getWorkspace') - ->will($this->returnValue($this->workspace)); + ->will($this->returnValue($this->workspace)) + ; + $this->workspace->expects($this->once()) ->method('getNodeTypeManager') - ->will($this->returnValue($this->nodeTypeManager)); + ->will($this->returnValue($this->nodeTypeManager)) + ; + $this->nodeTypeManager->expects($this->once()) ->method('getAllNodeTypes') - ->will($this->returnValue(array())); - $ct = $this->executeCommand('phpcr:node-type:list', array( - )); + ->will($this->returnValue([])) + ; + + $this->executeCommand('phpcr:node-type:list', []); } } diff --git a/tests/PHPCR/Tests/Util/Console/Command/NodeTypeRegisterCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodeTypeRegisterCommandTest.php index 6c7adfb..06e3f7b 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodeTypeRegisterCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodeTypeRegisterCommandTest.php @@ -2,33 +2,45 @@ namespace PHPCR\Tests\Util\Console\Command; -use Symfony\Component\Console\Application; +use PHPCR\Tests\Stubs\MockNodeTypeManager; use PHPCR\Util\Console\Command\NodeTypeRegisterCommand; +use PHPUnit_Framework_MockObject_MockObject; class NodeTypeRegisterCommandTest extends BaseCommandTest { + /** + * @var MockNodeTypeManager|PHPUnit_Framework_MockObject_MockObject + */ + private $nodeTypeManager; + public function setUp() { parent::setUp(); + $this->application->add(new NodeTypeRegisterCommand()); - $this->nodeTypeManager = $this->getMockBuilder( - 'PHPCR\Tests\Stubs\MockNodeTypeManager' - )->disableOriginalConstructor()->getMock(); + $this->nodeTypeManager = $this->getMockBuilder(MockNodeTypeManager::class) + ->disableOriginalConstructor() + ->getMock() + ; } public function testNodeTypeRegister() { $this->session->expects($this->once()) ->method('getWorkspace') - ->will($this->returnValue($this->workspace)); + ->will($this->returnValue($this->workspace)) + ; + $this->workspace->expects($this->once()) ->method('getNodeTypeManager') - ->will($this->returnValue($this->nodeTypeManager)); + ->will($this->returnValue($this->nodeTypeManager)) + ; + $this->nodeTypeManager->expects($this->once()) ->method('registerNodeTypesCnd'); - $ct = $this->executeCommand('phpcr:node-type:register', array( - 'cnd-file' => array(__DIR__.'/fixtures/cnd_dummy.cnd'), - )); + $this->executeCommand('phpcr:node-type:register', [ + 'cnd-file' => [__DIR__.'/fixtures/cnd_dummy.cnd'], + ]); } } diff --git a/tests/PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php index db523a2..381cdf5 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php @@ -2,69 +2,75 @@ namespace PHPCR\Tests\Util\Console\Command; -use PHPCR\Util\Console\Helper\PhpcrHelper; -use Symfony\Component\Console\Application; +use InvalidArgumentException; +use PHPCR\Query\QueryInterface; use PHPCR\Util\Console\Command\NodesUpdateCommand; +use PHPUnit_Framework_MockObject_MockObject; class NodesUpdateCommandTest extends BaseCommandTest { + /** + * @var QueryInterface|PHPUnit_Framework_MockObject_MockObject + */ + private $query; + public function setUp() { parent::setUp(); + $this->application->add(new NodesUpdateCommand()); - $this->query = $this->getMock('PHPCR\Query\QueryInterface'); + $this->query = $this->createMock(QueryInterface::class); } public function provideNodeUpdate() { - return array( - - // no query specified - array(array( - 'exception' => 'InvalidArgumentException', - )), - - // specify query - array(array( - 'query' => 'SELECT * FROM nt:unstructured WHERE foo="bar"', - )), - - // set, remote properties and mixins - array(array( - 'setProp' => array(array('foo', 'bar')), - 'removeProp' => array('bar'), - 'addMixin' => array('mixin1'), - 'removeMixin' => array('mixin1'), + return [ + // No query specified + [['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'], + 'removeMixin' => ['mixin1'], 'query' => 'SELECT * FROM nt:unstructured', - )), - ); + ]], + ]; } protected function setupQueryManager($options) { - $options = array_merge(array( - 'query' => '', - ), $options); + $options = array_merge(['query' => ''], $options); $this->session->expects($this->any()) ->method('getWorkspace') - ->will($this->returnValue($this->workspace)); + ->will($this->returnValue($this->workspace)) + ; + $this->workspace->expects($this->any()) ->method('getQueryManager') - ->will($this->returnValue($this->queryManager)); + ->will($this->returnValue($this->queryManager)) + ; $this->queryManager->expects($this->any()) ->method('createQuery') ->with($options['query'], 'JCR-SQL2') - ->will($this->returnValue($this->query)); + ->will($this->returnValue($this->query)) + ; + $this->query->expects($this->any()) ->method('execute') - ->will($this->returnValue(array( + ->will($this->returnValue([ $this->row1, - ))); + ])) + ; + $this->row1->expects($this->any()) ->method('getNode') - ->will($this->returnValue($this->node1)); + ->will($this->returnValue($this->node1)) + ; } /** @@ -72,30 +78,30 @@ protected function setupQueryManager($options) */ public function testNodeUpdate($options) { - $options = array_merge(array( + $options = array_merge([ 'query' => null, - 'setProp' => array(), - 'removeProp' => array(), - 'addMixin' => array(), - 'removeMixin' => array(), + 'setProp' => [], + 'removeProp' => [], + 'addMixin' => [], + 'removeMixin' => [], 'exception' => null, - ), $options); + ], $options); if ($options['exception']) { - $this->setExpectedException($options['exception']); + $this->expectException($options['exception']); } $this->setupQueryManager($options); - $args = array( + $args = [ '--query-language' => null, '--query' => $options['query'], '--no-interaction' => true, - '--set-prop' => array(), - '--remove-prop' => array(), - '--add-mixin' => array(), - '--remove-mixin' => array(), - ); + '--set-prop' => [], + '--remove-prop' => [], + '--add-mixin' => [], + '--remove-mixin' => [], + ]; foreach ($options['setProp'] as $setProp) { list($prop, $value) = $setProp; @@ -130,7 +136,7 @@ public function testNodeUpdate($options) $args['--remove-mixin'][] = $mixin; } - $ct = $this->executeCommand('phpcr:nodes:update', $args); + $this->executeCommand('phpcr:nodes:update', $args); } public function testApplyClosure() @@ -146,16 +152,18 @@ function ($session, $node) { ), ); - $this->setupQueryManager(array('query' => 'SELECT foo FROM bar')); + $this->setupQueryManager(['query' => 'SELECT foo FROM bar']); $this->node1->expects($this->exactly(2)) ->method('setProperty') - ->with('foo', 'bar'); + ->with('foo', 'bar') + ; $this->session->expects($this->once()) ->method('getNodeByIdentifier') - ->with('/foo'); + ->with('/foo') + ; - $ct = $this->executeCommand('phpcr:nodes:update', $args); + $this->executeCommand('phpcr:nodes:update', $args); } } diff --git a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceCreateCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceCreateCommandTest.php index cf48139..ce07824 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceCreateCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceCreateCommandTest.php @@ -2,8 +2,6 @@ namespace PHPCR\Tests\Util\Console\Command; -use PHPCR\RepositoryException; -use Symfony\Component\Console\Application; use PHPCR\Util\Console\Command\WorkspaceCreateCommand; use PHPCR\RepositoryInterface; @@ -12,6 +10,7 @@ class WorkspaceCreateCommandTest extends BaseCommandTest public function setUp() { parent::setUp(); + $this->application->add(new WorkspaceCreateCommand()); } @@ -21,27 +20,31 @@ public function testCreate() ->method('getWorkspace') ->will($this->returnValue($this->workspace)) ; + $this->session->expects($this->once()) ->method('getRepository') ->will($this->returnValue($this->repository)) ; + $this->repository->expects($this->once()) ->method('getDescriptor') ->with(RepositoryInterface::OPTION_WORKSPACE_MANAGEMENT_SUPPORTED) ->will($this->returnValue(true)) ; + $this->workspace->expects($this->once()) ->method('createWorkspace') ->with('test_workspace') ; + $this->workspace->expects($this->once()) ->method('getAccessibleWorkspaceNames') - ->will($this->returnValue(array('default'))) + ->will($this->returnValue(['default'])) ; - $this->executeCommand('phpcr:workspace:create', array( + $this->executeCommand('phpcr:workspace:create', [ 'name' => 'test_workspace' - )); + ]); } /** @@ -53,22 +56,26 @@ public function testCreateExisting() ->method('getWorkspace') ->will($this->returnValue($this->workspace)) ; + $this->session->expects($this->exactly(2)) ->method('getRepository') - ->will($this->returnValue($this->repository)); + ->will($this->returnValue($this->repository)) + ; + $this->repository->expects($this->exactly(2)) ->method('getDescriptor') ->with(RepositoryInterface::OPTION_WORKSPACE_MANAGEMENT_SUPPORTED) ->will($this->returnValue(true)) ; + $this->workspace->expects($this->exactly(2)) ->method('getAccessibleWorkspaceNames') - ->will($this->returnValue(array('default', 'test'))) + ->will($this->returnValue(['default', 'test'])) ; $tester = $this->executeCommand( 'phpcr:workspace:create', - array('name' => 'test'), + ['name' => 'test'], 2 ); @@ -76,10 +83,10 @@ public function testCreateExisting() $tester = $this->executeCommand( 'phpcr:workspace:create', - array( + [ '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 e4b446a..5b1f16e 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceDeleteCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceDeleteCommandTest.php @@ -2,7 +2,6 @@ namespace PHPCR\Tests\Util\Console\Command; -use Symfony\Component\Console\Application; use PHPCR\Util\Console\Command\WorkspaceDeleteCommand; use PHPCR\RepositoryInterface; @@ -11,6 +10,7 @@ class WorkspaceDeleteCommandTest extends BaseCommandTest public function setUp() { parent::setUp(); + $this->application->add(new WorkspaceDeleteCommand()); } @@ -20,19 +20,23 @@ public function testDelete() ->method('getWorkspace') ->will($this->returnValue($this->workspace)) ; + $this->workspace->expects($this->once()) ->method('getAccessibleWorkspaceNames') - ->will($this->returnValue(array('default', 'test_workspace', 'other'))) + ->will($this->returnValue(['default', 'test_workspace', 'other'])) ; + $this->session->expects($this->once()) ->method('getRepository') ->will($this->returnValue($this->repository)) ; + $this->repository->expects($this->once()) ->method('getDescriptor') ->with(RepositoryInterface::OPTION_WORKSPACE_MANAGEMENT_SUPPORTED) ->will($this->returnValue(true)) ; + $this->workspace->expects($this->once()) ->method('deleteWorkspace') ->with('test_workspace') @@ -52,15 +56,16 @@ public function testDeleteNonexistent() ->method('getWorkspace') ->will($this->returnValue($this->workspace)) ; + $this->workspace->expects($this->once()) ->method('getAccessibleWorkspaceNames') - ->will($this->returnValue(array('default', 'other'))) + ->will($this->returnValue(['default', 'other'])) ; - $ct = $this->executeCommand('phpcr:workspace:delete', array( + $ct = $this->executeCommand('phpcr:workspace:delete', [ 'name' => 'test_workspace', '--force' => 'true', - )); + ]); $this->assertContains("Workspace 'test_workspace' does not exist.", $ct->getDisplay()); } diff --git a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceExportCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceExportCommandTest.php index 759421c..578c79b 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceExportCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceExportCommandTest.php @@ -2,7 +2,6 @@ namespace PHPCR\Tests\Util\Console\Command; -use Symfony\Component\Console\Application; use PHPCR\Util\Console\Command\WorkspaceExportCommand; use PHPCR\RepositoryInterface; @@ -11,6 +10,7 @@ class WorkspaceExportCommandTest extends BaseCommandTest public function setUp() { parent::setUp(); + $this->application->add(new WorkspaceExportCommand()); } @@ -24,21 +24,23 @@ public function testNodeTypeList() $this->session->expects($this->once()) ->method('getRepository') ->will($this->returnValue($this->repository)); + $this->repository->expects($this->once()) ->method('getDescriptor') ->with(RepositoryInterface::OPTION_XML_EXPORT_SUPPORTED) ->will($this->returnValue(true)); + $this->session->expects($this->once()) ->method('exportSystemView'); $this->assertFileNotExists('test', 'test export file must not exist, it will be overwritten'); - $ct = $this->executeCommand('phpcr:workspace:export', array( + $ct = $this->executeCommand('phpcr:workspace:export', [ 'filename' => 'test' - )); + ]); if (method_exists($ct, 'getStatusCode')) { - // only available since symfony 2.4 + // Only available since symfony 2.4 $this->assertEquals(0, $ct->getStatusCode()); } $this->assertFileExists('test'); diff --git a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceImportCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceImportCommandTest.php index d4641a5..99679d9 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceImportCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceImportCommandTest.php @@ -2,7 +2,6 @@ namespace PHPCR\Tests\Util\Console\Command; -use Symfony\Component\Console\Application; use PHPCR\Util\Console\Command\WorkspaceImportCommand; use PHPCR\RepositoryInterface; @@ -11,6 +10,7 @@ class WorkspaceImportCommandTest extends BaseCommandTest public function setUp() { parent::setUp(); + $this->application->add(new WorkspaceImportCommand()); } @@ -19,16 +19,18 @@ public function testNodeTypeList() $this->session->expects($this->once()) ->method('getRepository') ->will($this->returnValue($this->repository)); + $this->repository->expects($this->once()) ->method('getDescriptor') ->with(RepositoryInterface::OPTION_XML_IMPORT_SUPPORTED) ->will($this->returnValue(true)); + $this->session->expects($this->once()) ->method('importXml'); - $ct = $this->executeCommand('phpcr:workspace:import', array( + $ct = $this->executeCommand('phpcr:workspace:import', [ 'filename' => 'test_import.xml' - )); + ]); $this->assertContains('Successfully imported', $ct->getDisplay()); } diff --git a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceListCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceListCommandTest.php index 53f2264..ecbc36d 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceListCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceListCommandTest.php @@ -2,7 +2,6 @@ namespace PHPCR\Tests\Util\Console\Command; -use Symfony\Component\Console\Application; use PHPCR\Util\Console\Command\WorkspaceListCommand; class WorkspaceListCommandTest extends BaseCommandTest @@ -10,6 +9,7 @@ class WorkspaceListCommandTest extends BaseCommandTest public function setUp() { parent::setUp(); + $this->application->add(new WorkspaceListCommand()); } @@ -18,11 +18,12 @@ public function testNodeTypeList() $this->session->expects($this->once()) ->method('getWorkspace') ->will($this->returnValue($this->workspace)); + $this->workspace->expects($this->once()) ->method('getAccessibleWorkspaceNames') - ->will($this->returnValue(array( + ->will($this->returnValue([ 'foo', 'bar' - ))); + ])); $ct = $this->executeCommand('phpcr:workspace:list', array( )); diff --git a/tests/PHPCR/Tests/Util/Console/Command/WorkspacePurgeCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/WorkspacePurgeCommandTest.php index b83fbb4..b85fab0 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/WorkspacePurgeCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/WorkspacePurgeCommandTest.php @@ -2,7 +2,6 @@ namespace PHPCR\Tests\Util\Console\Command; -use Symfony\Component\Console\Application; use PHPCR\Util\Console\Command\WorkspacePurgeCommand; class WorkspacePurgeCommandTest extends BaseCommandTest @@ -10,6 +9,7 @@ class WorkspacePurgeCommandTest extends BaseCommandTest public function setUp() { parent::setUp(); + $this->application->add(new WorkspacePurgeCommand()); } @@ -18,15 +18,17 @@ public function testNodeTypePurge() $this->session->expects($this->once()) ->method('getRootNode') ->will($this->returnValue($this->node1)); + $this->node1->expects($this->once()) ->method('getProperties') - ->will($this->returnValue(array())); + ->will($this->returnValue([])); + $this->node1->expects($this->once()) ->method('getNodes') - ->will($this->returnValue(array())); + ->will($this->returnValue([])); - $ct = $this->executeCommand('phpcr:workspace:purge', array( + $this->executeCommand('phpcr:workspace:purge', [ '--force' => true, - )); + ]); } } diff --git a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceQueryCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceQueryCommandTest.php index 274d953..edee537 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceQueryCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceQueryCommandTest.php @@ -2,42 +2,54 @@ namespace PHPCR\Tests\Util\Console\Command; -use Symfony\Component\Console\Application; +use PHPCR\Query\QueryInterface; use PHPCR\Util\Console\Command\WorkspaceQueryCommand; +use PHPUnit_Framework_MockObject_MockObject; class WorkspaceQueryCommandTest extends BaseCommandTest { + /** + * @var QueryInterface|PHPUnit_Framework_MockObject_MockObject + */ + protected $query; + public function setUp() { parent::setUp(); + $this->application->add(new WorkspaceQueryCommand()); - $this->query = $this->getMock('PHPCR\Query\QueryInterface'); + $this->query = $this->createMock(QueryInterface::class); } public function testQuery() { $this->queryManager->expects($this->any()) ->method('getSupportedQueryLanguages') - ->will($this->returnValue(array('JCR-SQL2'))); + ->will($this->returnValue(['JCR-SQL2'])); + $this->session->expects($this->any()) ->method('getWorkspace') ->will($this->returnValue($this->workspace)); + $this->workspace->expects($this->any()) ->method('getQueryManager') ->will($this->returnValue($this->queryManager)); + $this->queryManager->expects($this->once()) ->method('createQuery') ->with('SELECT foo FROM foo', 'JCR-SQL2') ->will($this->returnValue($this->query)); + $this->query->expects($this->once()) ->method('getLanguage') ->will($this->returnValue('FOOBAR')); + $this->query->expects($this->once()) ->method('execute') - ->will($this->returnValue(array())); + ->will($this->returnValue([])); - $ct = $this->executeCommand('phpcr:workspace:query', array( + $this->executeCommand('phpcr:workspace:query', [ 'query' => 'SELECT foo FROM foo', - )); + ]); } } diff --git a/tests/PHPCR/Tests/Util/Console/Helper/PhpcrConsoleDumperHelperTest.php b/tests/PHPCR/Tests/Util/Console/Helper/PhpcrConsoleDumperHelperTest.php index 54d40f5..8ec131b 100644 --- a/tests/PHPCR/Tests/Util/Console/Helper/PhpcrConsoleDumperHelperTest.php +++ b/tests/PHPCR/Tests/Util/Console/Helper/PhpcrConsoleDumperHelperTest.php @@ -1,6 +1,9 @@ outputMock = $this->getMock('Symfony\Component\Console\Output\OutputInterface'); + $this->outputMock = $this->createMock(OutputInterface::class); $this->helper = new PhpcrConsoleDumperHelper; } public function provideHelper() { - return array( - array(array()), - array(array( - 'show_props' => true, - )), - ); + return [[[]], [['show_props' => true]]]; } /** @@ -31,29 +29,23 @@ public function provideHelper() */ public function testGetTreeWalker($options) { - $options = array_merge(array( + $options = array_merge([ 'dump_uuids' => false, 'ref_format' => 'uuid', 'show_props' => false, 'show_sys_nodes' => false, - ), $options); + ], $options); $tw = $this->helper->getTreeWalker($this->outputMock, $options); - $this->assertInstanceOf( - 'PHPCR\Util\TreeWalker', - $tw - ); + $this->assertInstanceOf(TreeWalker::class, $tw); - $refl = new \ReflectionClass($tw); - $propVisitorProp = $refl->getProperty('propertyVisitor'); + $reflection = new ReflectionClass($tw); + $propVisitorProp = $reflection->getProperty('propertyVisitor'); $propVisitorProp->setAccessible(true); $propVisitor = $propVisitorProp->getValue($tw); if ($options['show_props'] === true) { - $this->assertInstanceOf( - 'PHPCR\Util\Console\Helper\TreeDumper\ConsoleDumperPropertyVisitor', - $propVisitor - ); + $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 33179c7..7c0612d 100644 --- a/tests/PHPCR/Tests/Util/NodeHelperTest.php +++ b/tests/PHPCR/Tests/Util/NodeHelperTest.php @@ -2,40 +2,56 @@ namespace PHPCR\Tests\Util; +use PHPCR\Tests\Stubs\MockNode; use PHPCR\Util\NodeHelper; +use PHPUnit_Framework_MockObject_MockObject; +use PHPUnit_Framework_TestCase; -require_once(__DIR__.'/../Stubs/MockNode.php'); +require_once __DIR__.'/../Stubs/MockNode.php'; -class NodeHelperTest extends \PHPUnit_Framework_TestCase +class NodeHelperTest extends PHPUnit_Framework_TestCase { - private $namespaces = array('a' => 'http://phpcr/', 'b' => 'http://jcr/'); - private $usedNames = array('a:x', 'b:y', 'c'); + /** + * @var array + */ + private $namespaces = ['a' => 'http://phpcr/', 'b' => 'http://jcr/']; + + /** + * @var array + */ + private $usedNames = ['a:x', 'b:y', 'c']; + /** + * @return array + */ public static function hints() { - return array( - array('', true), - array(':', true), - array('{}', true), - array('b:', 'b:'), - array('{http://jcr}', 'b:'), - array('b:z', 'b:z'), - array('{http://phpcr}bar', 'a:bar'), - ); + return [ + ['', true], + [':', true], + ['{}', true], + ['b:', 'b:'], + ['{http://jcr}', 'b:'], + ['b:z', 'b:z'], + ['{http://phpcr}bar', 'a:bar'], + ]; } + /** + * @return array + */ public static function invalidHints() { - return array( - array('::'), - array('a'), // no colon - array('a:foo:'), - array('{foo'), - array('x:'), // not an existing namespace prefix - array('{http://xy}'), // not an existing namespace uri - array('x:a'), // not an existing namespace prefix with a local name prefix - array('{http://xy}a'), // not an existing namespace uri with a local name prefix - ); + return [ + ['::'], + ['a'], // no colon + ['a:foo:'], + ['{foo'], + ['x:'], // not an existing namespace prefix + ['{http://xy}'], // not an existing namespace uri + ['x:a'], // not an existing namespace prefix with a local name prefix + ['{http://xy}a'], // not an existing namespace uri with a local name prefix + ]; } public function testGenerateAutoNodeNameNoHint() @@ -68,101 +84,115 @@ public function testGenerateAutoNodeNameInvalid($hint) public function testIsSystemItem() { - $sys = $this->getMock('PHPCR\Tests\Stubs\MockNode'); + /** @var MockNode|PHPUnit_Framework_MockObject_MockObject $sys */ + $sys = $this->createMock(MockNode::class); + $sys->expects($this->once()) ->method('getDepth') ->will($this->returnValue(0)) ; + $sys->expects($this->once()) ->method('getName') ->will($this->returnValue('jcr:root')) ; + $this->assertTrue(NodeHelper::isSystemItem($sys)); - $sys = $this->getMock('PHPCR\Tests\Stubs\MockNode'); + $sys = $this->createMock(MockNode::class); $sys->expects($this->once()) ->method('getDepth') ->will($this->returnValue(1)) ; + $sys->expects($this->once()) ->method('getName') ->will($this->returnValue('jcr:system')) ; + $this->assertTrue(NodeHelper::isSystemItem($sys)); - $top = $this->getMock('PHPCR\Tests\Stubs\MockNode'); + /** @var MockNode|PHPUnit_Framework_MockObject_MockObject $top */ + $top = $this->createMock(MockNode::class); $top->expects($this->once()) ->method('getDepth') ->will($this->returnValue(1)) ; + $top->expects($this->once()) ->method('getName') ->will($this->returnValue('jcrname')) // this is NOT in the jcr namespace ; + $this->assertFalse(NodeHelper::isSystemItem($top)); - $deep = $this->getMock('PHPCR\Tests\Stubs\MockNode'); + /** @var MockNode|PHPUnit_Framework_MockObject_MockObject $deep */ + $deep = $this->createMock(MockNode::class); $deep->expects($this->once()) ->method('getDepth') ->will($this->returnValue(2)) ; + $this->assertFalse(NodeHelper::isSystemItem($deep)); } public function testCalculateOrderBeforeSwapLast() { - $old = array('one', 'two', 'three', 'four'); - $new = array('one', 'two', 'four', 'three'); + $old = ['one', 'two', 'three', 'four']; + $new = ['one', 'two', 'four', 'three']; $reorders = NodeHelper::calculateOrderBefore($old, $new); - $expected = array( + $expected = [ 'three' => null, 'two' => 'four', // TODO: this is an unnecessary but harmless NOOP. we should try to eliminate - ); + ]; + $this->assertEquals($expected, $reorders); } public function testCalculateOrderBeforeSwap() { - $old = array('one', 'two', 'three', 'four'); - $new = array('one', 'four', 'three', 'two'); + $old = ['one', 'two', 'three', 'four']; + $new = ['one', 'four', 'three', 'two']; $reorders = NodeHelper::calculateOrderBefore($old, $new); - $expected = array( + $expected = [ 'three' => 'two', 'two' => null, - ); + ]; + $this->assertEquals($expected, $reorders); } public function testCalculateOrderBeforeReverse() { - $old = array('one', 'two', 'three', 'four'); - $new = array('four', 'three', 'two', 'one'); + $old = ['one', 'two', 'three', 'four']; + $new = ['four', 'three', 'two', 'one']; $reorders = NodeHelper::calculateOrderBefore($old, $new); - $expected = array( + $expected = [ 'three' => 'two', 'two' => 'one', 'one' => null, - ); + ]; $this->assertEquals($expected, $reorders); } public function testCalculateOrderBeforeDeleted() { - $old = array('one', 'two', 'three', 'four'); - $new = array('one', 'three', 'two'); + $old = ['one', 'two', 'three', 'four']; + $new = ['one', 'three', 'two']; $reorders = NodeHelper::calculateOrderBefore($old, $new); - $expected = array( + $expected = [ 'two' => null, 'one' => 'three', // TODO: this is an unnecessary but harmless NOOP. we should try to eliminate - ); + ]; + $this->assertEquals($expected, $reorders); } @@ -171,7 +201,7 @@ public function testCalculateOrderBeforeDeleted() */ public function testBenchmarkOrderBeforeArray() { - $nodes = array(); + $nodes = []; 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 25c99fb..155eb1f 100644 --- a/tests/PHPCR/Tests/Util/PathHelperTest.php +++ b/tests/PHPCR/Tests/Util/PathHelperTest.php @@ -2,7 +2,10 @@ namespace PHPCR\Tests\Util; +use PHPCR\NamespaceException; +use PHPCR\RepositoryException; use PHPCR\Util\PathHelper; +use stdClass; class PathHelperTest extends \PHPUnit_Framework_TestCase { @@ -18,22 +21,23 @@ public function testAssertValidAbsolutePath($path, $destination = false) public function dataproviderValidAbsolutePaths() { - return array( - array('/parent/child'), - array('/'), - array('/jcr:foo_/b-a/0^.txt'), - array('/parent[7]/child'), - array('/parent[7]/child', true), // index is allowed in destination parent path, only not in last element - array('/parent[7]/child[3]'), - ); + return [ + ['/parent/child'], + ['/'], + ['/jcr:foo_/b-a/0^.txt'], + ['/parent[7]/child'], + ['/parent[7]/child', true], // index is allowed in destination parent path, only not in last element + ['/parent[7]/child[3]'], + ]; } /** * @dataProvider dataproviderInvalidAbsolutePaths - * @expectedException \PHPCR\RepositoryException */ public function testAssertInvalidAbsolutePath($path, $destination = false) { + $this->expectException(RepositoryException::class); + PathHelper::assertValidAbsolutePath($path, $destination); } @@ -42,31 +46,32 @@ public function testAssertInvalidAbsolutePath($path, $destination = false) */ public function testAssertAbsolutePathNamespace($path) { - $this->assertTrue(PathHelper::assertValidAbsolutePath($path, false, true, array('jcr', 'nt'))); + $this->assertTrue(PathHelper::assertValidAbsolutePath($path, false, true, ['jcr', 'nt'])); } public function dataproviderValidAbsolutePathsWithNamespaces() { - return array( - array('/parent/child'), - array('/jcr:localname'), - array('/jcr:localname/test'), - array('/jcr:localname/test/nt:node'), - array('/jcr:localname/test/nt:node/bla'), - array('/'), - array('/jcr:foo_/b-a/0^.txt'), - array('/parent[7]/child'), - array('/jcr:localname[3]/test'), - ); + return [ + ['/parent/child'], + ['/jcr:localname'], + ['/jcr:localname/test'], + ['/jcr:localname/test/nt:node'], + ['/jcr:localname/test/nt:node/bla'], + ['/'], + ['/jcr:foo_/b-a/0^.txt'], + ['/parent[7]/child'], + ['/jcr:localname[3]/test'], + ]; } /** - * @expectedException \PHPCR\NamespaceException * @expectedExceptionMessage invalidprefix and other-ns */ public function testAssertInvalidNamespaceAbsolutePath() { - PathHelper::assertValidAbsolutePath('/invalidprefix:localname/other-ns:test/invalidprefix:node/bla', false, true, array('jcr', 'nt')); + $this->expectException(NamespaceException::class); + + PathHelper::assertValidAbsolutePath('/invalidprefix:localname/other-ns:test/invalidprefix:node/bla', false, true, ['jcr', 'nt']); } /** @@ -79,15 +84,15 @@ public function testAssertInvalidAbsolutePathNoThrow($path, $destination = false public function dataproviderInvalidAbsolutePaths() { - return array( - array('/parent/child[7]', true), // destination last element with index - array('parent'), // not absolute - array('/parent//child'), - array('//'), - array('/parent/../child'), - array('/parent/./child'), - array('/parent/child/'), - ); + return [ + ['/parent/child[7]', true], // destination last element with index + ['parent'], // not absolute + ['/parent//child'], + ['//'], + ['/parent/../child'], + ['/parent/./child'], + ['/parent/child/'], + ]; } // assertValidLocalName tests @@ -104,21 +109,22 @@ public function testAssertValidLocalNameRootnode() /** * @dataProvider dataproviderInvalidLocalNames - * @expectedException \PHPCR\RepositoryException */ public function testAssertInvalidLocalName($name) { + $this->expectException(RepositoryException::class); + PathHelper::assertValidLocalName($name); } public function dataproviderInvalidLocalNames() { - return array( - array('jcr:nodename'), - array('/path'), - array('.'), - array('..') - ); + return [ + ['jcr:nodename'], + ['/path'], + ['.'], + ['..'] + ]; } // normalizePath tests @@ -133,21 +139,22 @@ public function testNormalizePath($inputPath, $outputPath) public static function dataproviderNormalizePath() { - return array( - array('/', '/'), - array('/../foo', '/foo'), - array('/../', '/'), - array('/foo/../bar', '/bar'), - array('/foo/./bar', '/foo/bar'), - ); + return [ + ['/', '/'], + ['/../foo', '/foo'], + ['/../', '/'], + ['/foo/../bar', '/bar'], + ['/foo/./bar', '/foo/bar'], + ]; } /** * @dataProvider dataproviderNormalizePathInvalid - * @expectedException \PHPCR\RepositoryException */ public function testNormalizePathInvalidThrow($input) { + $this->expectException(RepositoryException::class); + PathHelper::normalizePath($input); } @@ -161,13 +168,13 @@ public function testNormalizePathInvalidNoThrow($input) public static function dataproviderNormalizePathInvalid() { - return array( - array('foo/bar'), - array('bar'), - array('/foo/bar/'), - array(''), - array(new \stdClass()), - ); + return [ + ['foo/bar'], + ['bar'], + ['/foo/bar/'], + [''], + [new stdClass()], + ]; } // absolutizePath tests @@ -182,12 +189,12 @@ public function testAbsolutizePath($inputPath, $context, $outputPath) public static function dataproviderAbsolutizePath() { - return array( - array('/../foo', '/', '/foo'), - array('../', '/', '/'), - array('../foo/bar', '/baz', '/foo/bar'), - array('foo/./bar', '/baz', '/baz/foo/bar'), - ); + return [ + ['/../foo', '/', '/foo'], + ['../', '/', '/'], + ['../foo/bar', '/baz', '/foo/bar'], + ['foo/./bar', '/baz', '/baz/foo/bar'], + ]; } /** @@ -209,13 +216,13 @@ public function testAbsolutizePathInvalidNoThrow($inputPath, $context, $target) public static function dataproviderAbsolutizePathInvalid() { - return array( - array('', '/context', false), - array(null, '/context', false), - array('foo', null, false), - array(new \stdClass(), '/context', false), - array('foo[2]', '/bar', true), - ); + return [ + ['', '/context', false], + [null, '/context', false], + ['foo', null, false], + [new stdClass(), '/context', false], + ['foo[2]', '/bar', true], + ]; } // relativizePath tests @@ -230,18 +237,19 @@ public function testRelativizePath($inputPath, $context, $outputPath) public static function dataproviderRelativizePath() { - return array( - array('/parent/path/child', '/parent', 'path/child'), - array('/child', '/', 'child'), - ); + return [ + ['/parent/path/child', '/parent', 'path/child'], + ['/child', '/', 'child'], + ]; } /** - * @expectedException \PHPCR\RepositoryException * @dataProvider dataproviderRelativizePathInvalid */ public function testRelativizePathInvalidThrow($inputPath, $context) { + $this->expectException(RepositoryException::class); + PathHelper::relativizePath($inputPath, $context); } @@ -255,10 +263,10 @@ public function testRelativizePathInvalidNoThrow($inputPath, $context) public static function dataproviderRelativizePathInvalid() { - return array( - array('/path', '/context'), - array('/parent', '/parent/child'), - ); + return [ + ['/path', '/context'], + ['/parent', '/parent/child'], + ]; } // getParentPath tests @@ -273,12 +281,12 @@ public function testGetParentPath($path, $parent) public function dataproviderParentPath() { - return array( - array('/parent/child', '/parent'), - array('/jcr:parent/ns:child', '/jcr:parent'), - array('/child', '/'), - array('/', '/'), - ); + return [ + ['/parent/child', '/parent'], + ['/jcr:parent/ns:child', '/jcr:parent'], + ['/child', '/'], + ['/', '/'], + ]; } // getNodeName tests @@ -310,21 +318,22 @@ public function testGetLocalNodeName($path, $expected = null) public function dataproviderGetLocalNodeName() { - return array( - array('/parent/child', 'child'), - array('/foo:child', 'child'), - array('/parent/ns:child', 'child'), - array('/ns:parent/child:foo', 'foo'), - array('/', ''), - ); + return [ + ['/parent/child', 'child'], + ['/foo:child', 'child'], + ['/parent/ns:child', 'child'], + ['/ns:parent/child:foo', 'foo'], + ['/', ''], + ]; } /** - * @expectedException \PHPCR\RepositoryException * @expectedExceptionMessage must be an absolute path */ public function testGetNodeNameMustBeAbsolute() { + $this->expectException(RepositoryException::class); + PathHelper::getNodeName('foobar'); } @@ -340,11 +349,11 @@ public function testGetPathDepth($path, $depth) public function dataproviderPathDepth() { - return array( - array('/', 0), - array('/foo', 1), - array('/foo/bar', 2), - array('/foo/bar/', 2), - ); + return [ + ['/', 0], + ['/foo', 1], + ['/foo/bar', 2], + ['/foo/bar/', 2], + ]; } } diff --git a/tests/PHPCR/Tests/Util/QOM/BaseSqlGeneratorTest.php b/tests/PHPCR/Tests/Util/QOM/BaseSqlGeneratorTest.php index d5984db..6c20bd3 100644 --- a/tests/PHPCR/Tests/Util/QOM/BaseSqlGeneratorTest.php +++ b/tests/PHPCR/Tests/Util/QOM/BaseSqlGeneratorTest.php @@ -2,14 +2,13 @@ namespace PHPCR\Tests\Util\QOM; -use PHPCR\Util\QOM\Sql1Generator; -use PHPCR\Util\ValueConverter; +use PHPUnit_Framework_TestCase; -abstract class BaseSqlGeneratorTest extends \PHPUnit_Framework_TestCase +abstract class BaseSqlGeneratorTest extends PHPUnit_Framework_TestCase { public function testNot() { - $string = $this->generator->evalNot("foo = bar"); - $this->assertSame("(NOT foo = bar)", $string); + $string = $this->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 7f87534..54914a6 100644 --- a/tests/PHPCR/Tests/Util/QOM/QueryBuilderTest.php +++ b/tests/PHPCR/Tests/Util/QOM/QueryBuilderTest.php @@ -2,15 +2,32 @@ namespace PHPCR\Tests\Util\QOM; +use InvalidArgumentException; +use PHPCR\Query\QOM\ConstraintInterface; +use PHPCR\Query\QOM\DynamicOperandInterface; +use PHPCR\Query\QOM\QueryObjectModelConstantsInterface; +use PHPCR\Query\QOM\QueryObjectModelFactoryInterface; +use PHPCR\Query\QOM\QueryObjectModelInterface; +use PHPCR\Query\QOM\SameNodeJoinConditionInterface; +use PHPCR\Query\QOM\SourceInterface; use PHPCR\Util\QOM\QueryBuilder; +use PHPUnit_Framework_MockObject_MockObject; +use PHPUnit_Framework_TestCase; +use RuntimeException; -class QueryBuilderTest extends \PHPUnit_Framework_TestCase +class QueryBuilderTest extends PHPUnit_Framework_TestCase { + /** + * @var PHPUnit_Framework_MockObject_MockObject|QueryObjectModelFactoryInterface + */ protected $qf; public function setUp() { - $this->qf = $this->getMock('PHPCR\Query\QOM\QueryObjectModelFactoryInterface', array(), array()); + $this->qf = $this->getMockBuilder(QueryObjectModelFactoryInterface::class) + ->setMethods([]) + ->setConstructorArgs([]) + ->getMock(); } public function testSetFirstResult() @@ -27,9 +44,25 @@ public function testSetMaxResults() $this->assertEquals(15, $qb->getMaxResults()); } + /** + * @return DynamicOperandInterface + */ + private function createDynamicOperandMock() + { + /** @var DynamicOperandInterface $dynamicOperand */ + $dynamicOperand = $this->getMockBuilder(DynamicOperandInterface::class) + ->setMethods([]) + ->setConstructorArgs([]) + ->getMock() + ; + + return $dynamicOperand; + } + public function testAddOrderBy() { - $dynamicOperand = $this->getMock('PHPCR\Query\QOM\DynamicOperandInterface', array(), array()); + $dynamicOperand = $this->createDynamicOperandMock(); + $qb = new QueryBuilder($this->qf); $qb->addOrderBy($dynamicOperand, 'ASC'); $qb->addOrderBy($dynamicOperand, 'DESC'); @@ -39,7 +72,8 @@ public function testAddOrderBy() public function testAddOrderByLowercase() { - $dynamicOperand = $this->getMock('PHPCR\Query\QOM\DynamicOperandInterface', array(), array()); + $dynamicOperand = $this->createDynamicOperandMock(); + $qb = new QueryBuilder($this->qf); $qb->addOrderBy($dynamicOperand, 'asc'); $qb->addOrderBy($dynamicOperand, 'desc'); @@ -47,19 +81,20 @@ public function testAddOrderByLowercase() $orderings = $qb->getOrderings(); } - /** - * @expectedException \InvalidArgumentException - */ public function testAddOrderByInvalid() { - $dynamicOperand = $this->getMock('PHPCR\Query\QOM\DynamicOperandInterface', array(), array()); + $this->expectException(InvalidArgumentException::class); + + $dynamicOperand = $this->createDynamicOperandMock(); + $qb = new QueryBuilder($this->qf); $qb->addOrderBy($dynamicOperand, 'FOO'); } public function testOrderBy() { - $dynamicOperand = $this->getMock('PHPCR\Query\QOM\DynamicOperandInterface', array(), array()); + $dynamicOperand = $this->createDynamicOperandMock(); + $qb = new QueryBuilder($this->qf); $qb->orderBy($dynamicOperand, 'ASC'); $qb->orderBy($dynamicOperand, 'ASC'); @@ -68,37 +103,59 @@ public function testOrderBy() public function testOrderAscending() { - $dynamicOperand = $this->getMock('PHPCR\Query\QOM\DynamicOperandInterface', array(), array()); + $dynamicOperand = $this->createDynamicOperandMock(); + $this->qf->expects($this->once()) ->method('ascending') ->with($this->equalTo($dynamicOperand)); + $qb = new QueryBuilder($this->qf); $qb->addOrderBy($dynamicOperand, 'ASC'); } public function testOrderDescending() { - $dynamicOperand = $this->getMock('PHPCR\Query\QOM\DynamicOperandInterface', array(), array()); + $dynamicOperand = $this->createDynamicOperandMock(); + $this->qf->expects($this->once()) ->method('descending') ->with($this->equalTo($dynamicOperand)); + $qb = new QueryBuilder($this->qf); $qb->addOrderBy($dynamicOperand, 'DESC'); } public function testOrderAscendingIsDefault() { - $dynamicOperand = $this->getMock('PHPCR\Query\QOM\DynamicOperandInterface', array(), array()); + $dynamicOperand = $this->createDynamicOperandMock(); + $this->qf->expects($this->once()) ->method('ascending') ->with($this->equalTo($dynamicOperand)); + $qb = new QueryBuilder($this->qf); $qb->addOrderBy($dynamicOperand); } + /** + * @return ConstraintInterface + */ + private function createConstraintMock() + { + /** @var ConstraintInterface $constraint */ + $constraint = $this->getMockBuilder(ConstraintInterface::class) + ->setMethods([]) + ->setConstructorArgs([]) + ->getMock() + ; + + return $constraint; + } + public function testWhere() { - $constraint = $this->getMock('PHPCR\Query\QOM\ConstraintInterface', array(), array()); + $constraint = $this->createConstraintMock(); + $qb = new QueryBuilder($this->qf); $qb->where($constraint); $this->assertEquals($constraint, $qb->getConstraint()); @@ -106,13 +163,12 @@ public function testWhere() public function testAndWhere() { - $dynamicOperand = $this->getMock('PHPCR\Query\QOM\ConstraintInterface', array(), array()); - $this->qf = $this->getMock('PHPCR\Query\QOM\QueryObjectModelFactoryInterface', array(), array()); $this->qf->expects($this->once()) ->method('andConstraint'); - $constraint1 = $this->getMock('PHPCR\Query\QOM\ConstraintInterface', array(), array()); - $constraint2 = $this->getMock('PHPCR\Query\QOM\ConstraintInterface', array(), array()); + $constraint1 = $this->createConstraintMock(); + $constraint2 = $this->createConstraintMock(); + $qb = new QueryBuilder($this->qf); $qb->where($constraint1); $qb->andWhere($constraint2); @@ -120,13 +176,12 @@ public function testAndWhere() public function testOrWhere() { - $dynamicOperand = $this->getMock('PHPCR\Query\QOM\ConstraintInterface', array(), array()); - $this->qf = $this->getMock('PHPCR\Query\QOM\QueryObjectModelFactoryInterface', array(), array()); $this->qf->expects($this->once()) ->method('orConstraint'); - $constraint1 = $this->getMock('PHPCR\Query\QOM\ConstraintInterface', array(), array()); - $constraint2 = $this->getMock('PHPCR\Query\QOM\ConstraintInterface', array(), array()); + $constraint1 = $this->createConstraintMock(); + $constraint2 = $this->createConstraintMock(); + $qb = new QueryBuilder($this->qf); $qb->where($constraint1); $qb->orWhere($constraint2); @@ -152,31 +207,70 @@ public function testAddSelect() $this->assertCount(2, $qb->getColumns()); } + /** + * @return SourceInterface + */ + private function createSourceMock() + { + /** @var SourceInterface $source */ + $source = $this->getMockBuilder(SourceInterface::class) + ->setMethods([]) + ->setConstructorArgs([]) + ->getMock(); + + return $source; + } + public function testFrom() { - $source = $this->getMock('PHPCR\Query\QOM\SourceInterface', array(), array()); + $source = $this->createSourceMock(); + $qb = new QueryBuilder($this->qf); $qb->from($source); $this->assertEquals($source, $qb->getSource()); } + /** + * @return SameNodeJoinConditionInterface + */ + private function createSameNodeJoinConditionMock() + { + /** @var SameNodeJoinConditionInterface $joinCondition */ + $joinCondition = $this->getMockBuilder(SameNodeJoinConditionInterface::class) + ->setMethods([]) + ->setConstructorArgs([]) + ->getMock(); + + return $joinCondition; + } + public function testInvalidJoin() { - $this->setExpectedException('\RuntimeException'); - $source = $this->getMock('PHPCR\Query\QOM\SourceInterface', array(), array()); - $joinCondition = $this->getMock('PHPCR\Query\QOM\SameNodeJoinConditionInterface', array(), array()); + $this->expectException(RuntimeException::class); + + $source = $this->createSourceMock(); + $joinCondition = $this->createSameNodeJoinConditionMock(); + $qb = new QueryBuilder($this->qf); $qb->join($source, $joinCondition); } public function testJoin() { - $source1 = $this->getMock('PHPCR\Query\QOM\SourceInterface', array(), array()); - $source2= $this->getMock('PHPCR\Query\QOM\SourceInterface', array(), array()); - $joinCondition = $this->getMock('PHPCR\Query\QOM\SameNodeJoinConditionInterface', array(), array()); + $source1 = $this->createSourceMock(); + $source2 = $this->createSourceMock(); + $joinCondition = $this->createSameNodeJoinConditionMock(); + $this->qf->expects($this->once()) ->method('join') - ->with($source1, $source2, $this->equalTo(\PHPCR\Query\QOM\QueryObjectModelConstantsInterface::JCR_JOIN_TYPE_INNER), $joinCondition); + ->with( + $source1, + $source2, + $this->equalTo(QueryObjectModelConstantsInterface::JCR_JOIN_TYPE_INNER), + $joinCondition + ) + ; + $qb = new QueryBuilder($this->qf); $qb->from($source1); $qb->join($source2, $joinCondition); @@ -184,12 +278,20 @@ public function testJoin() public function testRightJoin() { - $source1 = $this->getMock('PHPCR\Query\QOM\SourceInterface', array(), array()); - $source2= $this->getMock('PHPCR\Query\QOM\SourceInterface', array(), array()); - $joinCondition = $this->getMock('PHPCR\Query\QOM\SameNodeJoinConditionInterface', array(), array()); + $source1 = $this->createSourceMock(); + $source2 = $this->createSourceMock(); + $joinCondition = $this->createSameNodeJoinConditionMock(); + $this->qf->expects($this->once()) ->method('join') - ->with($source1, $source2, $this->equalTo(\PHPCR\Query\QOM\QueryObjectModelConstantsInterface::JCR_JOIN_TYPE_RIGHT_OUTER), $joinCondition); + ->with( + $source1, + $source2, + $this->equalTo(QueryObjectModelConstantsInterface::JCR_JOIN_TYPE_RIGHT_OUTER), + $joinCondition + ) + ; + $qb = new QueryBuilder($this->qf); $qb->from($source1); $qb->rightJoin($source2, $joinCondition); @@ -197,12 +299,20 @@ public function testRightJoin() public function testLeftJoin() { - $source1 = $this->getMock('PHPCR\Query\QOM\SourceInterface', array(), array()); - $source2= $this->getMock('PHPCR\Query\QOM\SourceInterface', array(), array()); - $joinCondition = $this->getMock('PHPCR\Query\QOM\SameNodeJoinConditionInterface', array(), array()); + $source1 = $this->createSourceMock(); + $source2 = $this->createSourceMock(); + $joinCondition = $this->createSameNodeJoinConditionMock(); + $this->qf->expects($this->once()) - ->method('join') - ->with($source1, $source2, $this->equalTo(\PHPCR\Query\QOM\QueryObjectModelConstantsInterface::JCR_JOIN_TYPE_LEFT_OUTER), $joinCondition); + ->method('join') + ->with( + $source1, + $source2, + $this->equalTo(QueryObjectModelConstantsInterface::JCR_JOIN_TYPE_LEFT_OUTER), + $joinCondition + ) + ; + $qb = new QueryBuilder($this->qf); $qb->from($source1); $qb->leftJoin($source2, $joinCondition); @@ -210,69 +320,99 @@ public function testLeftJoin() public function testGetQuery() { - $source = $this->getMock('PHPCR\Query\QOM\SourceInterface', array(), array()); - $constraint = $this->getMock('PHPCR\Query\QOM\ConstraintInterface', array(), array()); + $source = $this->createSourceMock(); + $constraint = $this->createConstraintMock(); + $qb = new QueryBuilder($this->qf); $qb->from($source); $qb->where($constraint); + $this->qf->expects($this->once()) ->method('createQuery') - ->will($this->returnValue("true")); + ->will($this->returnValue('true')); + $qb->getQuery(); } + + /** + * @return QueryObjectModelInterface|PHPUnit_Framework_MockObject_MockObject + */ + private function createQueryMock() + { + /** @var QueryObjectModelInterface $query */ + $query = $this->getMockBuilder(QueryObjectModelInterface::class) + ->setMethods([]) + ->setConstructorArgs([]) + ->getMock() + ; + + return $query; + } + public function testGetQueryWithOffsetAndLimit() { - $source = $this->getMock('PHPCR\Query\QOM\SourceInterface', array(), array()); - $constraint = $this->getMock('PHPCR\Query\QOM\ConstraintInterface', array(), array()); - $query = $this->getMock('PHPCR\Query\QOM\QueryObjectModelInterface', array(), array()); + $source = $this->createSourceMock(); + $constraint = $this->createConstraintMock(); + + $query = $this->createQueryMock(); + $qb = new QueryBuilder($this->qf); $qb->from($source); $qb->where($constraint); $qb->setFirstResult(13); $qb->setMaxResults(42); + $query->expects($this->once()) ->method('setOffset'); $query->expects($this->once()) ->method('setLimit'); + $this->qf->expects($this->once()) ->method('createQuery') ->will($this->returnValue($query)); + $qb->getQuery(); } public function testSetParameter() { + $key = 'key'; + $value = 'value'; + $qb = new QueryBuilder($this->qf); - $key = "key"; - $value = "value"; $qb->setParameter($key, $value); + $this->assertEquals($value, $qb->getParameter($key)); } public function testSetParameters() { + $key1 = 'key1'; + $value1 = 'value1'; + $key2 = 'key2'; + $value2 = 'value2'; + $qb = new QueryBuilder($this->qf); - $key1 = "key1"; - $value1 = "value1"; - $key2 = "key2"; - $value2 = "value2"; - $qb->setParameters(array($key1, $value1), array($key2, $value2)); + $qb->setParameters([$key1, $value1], [$key2, $value2]); $this->assertCount(2, $qb->getParameters()); } public function testExecute() { - $source = $this->getMock('PHPCR\Query\QOM\SourceInterface', array(), array()); - $constraint = $this->getMock('PHPCR\Query\QOM\ConstraintInterface', array(), array()); - $query = $this->getMock('PHPCR\Query\QueryInterface', array(), array()); + $source = $this->createSourceMock(); + $constraint = $this->createConstraintMock(); + $query = $this->createQueryMock(); + $query->expects($this->once()) ->method('execute'); $query->expects($this->once()) ->method('bindValue'); + $this->qf->expects($this->once()) ->method('createQuery') ->with($source, $constraint, array(), array()) ->will($this->returnValue($query)); + $qb = new QueryBuilder($this->qf); $qb->from($source) ->where($constraint) diff --git a/tests/PHPCR/Tests/Util/QOM/Sql1GeneratorTest.php b/tests/PHPCR/Tests/Util/QOM/Sql1GeneratorTest.php index 423c75d..4955379 100644 --- a/tests/PHPCR/Tests/Util/QOM/Sql1GeneratorTest.php +++ b/tests/PHPCR/Tests/Util/QOM/Sql1GeneratorTest.php @@ -2,11 +2,16 @@ namespace PHPCR\Tests\Util\QOM; +use DateTime; use PHPCR\Util\QOM\Sql1Generator; use PHPCR\Util\ValueConverter; +use PHPUnit_Framework_TestCase; -class Sql1GeneratorTest extends \PHPUnit_Framework_TestCase +class Sql1GeneratorTest extends PHPUnit_Framework_TestCase { + /** + * @var Sql1Generator + */ protected $generator; public function setUp() @@ -22,7 +27,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); } @@ -35,44 +40,44 @@ public function testBoolLiteral() public function testLongLiteral() { $literal = $this->generator->evalLiteral(11); - $this->assertSame("11", $literal); + $this->assertSame('11', $literal); } public function testDoubleLiteral() { $literal = $this->generator->evalLiteral(11.0); - $this->assertSame("11.0", $literal); + $this->assertSame('11.0', $literal); } public function testChildNode() { - $literal = $this->generator->evalChildNode("/"); + $literal = $this->generator->evalChildNode('/'); $this->assertSame("jcr:path LIKE '/%' AND NOT jcr:path LIKE '/%/%'", $literal); - $literal = $this->generator->evalChildNode("/foo/bar/baz"); + $literal = $this->generator->evalChildNode('/foo/bar/baz'); $this->assertSame("jcr:path LIKE '/foo[%]/bar[%]/baz[%]/%' AND NOT jcr:path LIKE '/foo[%]/bar[%]/baz[%]/%/%'", $literal); } public function testDescendantNode() { - $literal = $this->generator->evalDescendantNode("/"); + $literal = $this->generator->evalDescendantNode('/'); $this->assertSame("jcr:path LIKE '/%'", $literal); - $literal = $this->generator->evalDescendantNode("/foo/bar/baz"); + $literal = $this->generator->evalDescendantNode('/foo/bar/baz'); $this->assertSame("jcr:path LIKE '/foo[%]/bar[%]/baz[%]/%'", $literal); } public function testPopertyExistence() { - $literal = $this->generator->evalPropertyExistence(null, "foo"); - $this->assertSame("foo IS NOT NULL", $literal); + $literal = $this->generator->evalPropertyExistence(null, 'foo'); + $this->assertSame('foo IS NOT NULL', $literal); } public function testFullTextSearch() { $literal = $this->generator->evalFullTextSearch(null, "'foo'"); $this->assertSame("CONTAINS(*, 'foo')", $literal); - $literal = $this->generator->evalFullTextSearch(null, "'foo'", "bar"); + $literal = $this->generator->evalFullTextSearch(null, "'foo'", 'bar'); $this->assertSame("CONTAINS(bar, 'foo')", $literal); } @@ -80,13 +85,13 @@ public function testColumns() { $literal = $this->generator->evalColumns(null); $this->assertSame("s", $literal); - $literal = $this->generator->evalColumns(array("bar", "foo")); + $literal = $this->generator->evalColumns(['bar', 'foo']); $this->assertSame("bar, foo", $literal); } public function testPropertyValue() { - $literal = $this->generator->evalPropertyValue("foo"); - $this->assertSame("foo", $literal); + $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 14b48bb..7ea45fd 100644 --- a/tests/PHPCR/Tests/Util/QOM/Sql2GeneratorTest.php +++ b/tests/PHPCR/Tests/Util/QOM/Sql2GeneratorTest.php @@ -2,11 +2,15 @@ namespace PHPCR\Tests\Util\QOM; +use DateTime; use PHPCR\Util\QOM\Sql2Generator; use PHPCR\Util\ValueConverter; class Sql2GeneratorTest extends BaseSqlGeneratorTest { + /** + * @var Sql2Generator + */ protected $generator; public function setUp() @@ -22,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("CAST('2011-12-23T00:00:00.000+00:00' AS DATE)", $literal); } diff --git a/tests/PHPCR/Tests/Util/QOM/Sql2ToQomQueryConverterTest.php b/tests/PHPCR/Tests/Util/QOM/Sql2ToQomQueryConverterTest.php index 15def8d..6649f1e 100644 --- a/tests/PHPCR/Tests/Util/QOM/Sql2ToQomQueryConverterTest.php +++ b/tests/PHPCR/Tests/Util/QOM/Sql2ToQomQueryConverterTest.php @@ -2,26 +2,43 @@ namespace PHPCR\Tests\Util\QOM; +use PHPCR\Query\InvalidQueryException; +use PHPCR\Query\QOM\QueryObjectModelFactoryInterface; use PHPCR\Util\QOM\Sql2ToQomQueryConverter; +use PHPCR\Util\ValueConverter; +use PHPUnit_Framework_TestCase; -class Sql2ToQomQueryConverterTest extends \PHPUnit_Framework_TestCase +class Sql2ToQomQueryConverterTest extends PHPUnit_Framework_TestCase { + /** + * @var QueryObjectModelFactoryInterface + */ protected $qomFactory; + + /** + * @var ValueConverter + */ protected $valueConverter; + /** + * @var Sql2ToQomQueryConverter + */ + protected $converter; + public function setUp() { - $this->qomFactory = $this->getMock('PHPCR\Query\QOM\QueryObjectModelFactoryInterface'); - $this->valueConverter = $this->getMock('PHPCR\Util\ValueConverter'); + $this->qomFactory = $this->createMock(QueryObjectModelFactoryInterface::class); + $this->valueConverter = $this->createMock(ValueConverter::class); $this->converter = new Sql2ToQomQueryConverter($this->qomFactory, $this->valueConverter); } /** - * @expectedException \PHPCR\Query\InvalidQueryException * @expectedExceptionMessage Error parsing query */ public function testInvalid() { + $this->expectException(InvalidQueryException::class); + $this->converter->parse('SELECTING WITH AN INVALID QUERY'); } } diff --git a/tests/PHPCR/Tests/Util/TraversingItemVisitorTest.php b/tests/PHPCR/Tests/Util/TraversingItemVisitorTest.php index 3867723..88c85f9 100644 --- a/tests/PHPCR/Tests/Util/TraversingItemVisitorTest.php +++ b/tests/PHPCR/Tests/Util/TraversingItemVisitorTest.php @@ -2,7 +2,9 @@ namespace PHPCR\Tests\Util; -class TraversingItemVisitorTest extends \PHPUnit_Framework_TestCase +use PHPUnit_Framework_TestCase; + +class TraversingItemVisitorTest extends PHPUnit_Framework_TestCase { public function testVisitor() { diff --git a/tests/PHPCR/Tests/Util/UUIDHelperTest.php b/tests/PHPCR/Tests/Util/UUIDHelperTest.php index ab7de3f..3945a34 100644 --- a/tests/PHPCR/Tests/Util/UUIDHelperTest.php +++ b/tests/PHPCR/Tests/Util/UUIDHelperTest.php @@ -3,8 +3,9 @@ namespace PHPCR\Tests\Util; use PHPCR\Util\UUIDHelper; +use PHPUnit_Framework_TestCase; -class UUIDHelperTest extends \PHPUnit_Framework_TestCase +class UUIDHelperTest extends PHPUnit_Framework_TestCase { public function testGenerateUUID() { diff --git a/tests/PHPCR/Tests/Util/ValueConverterTest.php b/tests/PHPCR/Tests/Util/ValueConverterTest.php index 48fe04a..d4177aa 100644 --- a/tests/PHPCR/Tests/Util/ValueConverterTest.php +++ b/tests/PHPCR/Tests/Util/ValueConverterTest.php @@ -1,17 +1,24 @@ setTimestamp(123); - $nodemock = $this->getMock('PHPCR\Tests\Stubs\MockNode'); - $nodemock + $nodeMock = $this->createMock(MockNode::class); + $nodeMock ->expects($this->any()) ->method('getIdentifier') ->will($this->returnValue('38b7cf18-c417-477a-af0b-c1e92a290c9a')) ; - $nodemock + + $nodeMock ->expects($this->any()) ->method('isNodeType') ->with('mix:referenceable') ->will($this->returnValue(true)) ; - return array( - // string to... - array('test string', PropertyType::STRING, 'test string', PropertyType::STRING), - array('test string', PropertyType::STRING, 0, PropertyType::LONG), - array('378.37', PropertyType::STRING, 378, PropertyType::LONG), - array('test string', PropertyType::STRING, 0.0, PropertyType::DOUBLE), - array('249.39', PropertyType::STRING, 249.39, PropertyType::DOUBLE), - array('test string', PropertyType::STRING, null, PropertyType::DATE), - array('17.12.2010 GMT', PropertyType::STRING, new \DateTime('17.12.2010 GMT'), PropertyType::DATE), - array('test string', PropertyType::STRING, true, PropertyType::BOOLEAN), - array('false', PropertyType::STRING, true, PropertyType::BOOLEAN), - array('', PropertyType::STRING, false, PropertyType::BOOLEAN), - // TODO: check NAME may not have spaces array('test string', PropertyType::STRING, null, PropertyType::NAME), - array('test', PropertyType::STRING, 'test', PropertyType::NAME), - // TODO: check PATH may not have spaces array('test string', PropertyType::STRING, null, PropertyType::PATH), - array('../the/node', PropertyType::STRING, '../the/node', PropertyType::PATH), - array('38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::STRING, '38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::REFERENCE), - // TODO: should we move UUIDHelper to phpcr so we can check in PropertyType? array('test string', PropertyType::STRING, null, PropertyType::REFERENCE), - array('', PropertyType::STRING, null, PropertyType::REFERENCE), - array('http://phpcr.github.com/', PropertyType::STRING, 'http://phpcr.github.com/', PropertyType::URI), - array('test string', PropertyType::STRING, 'test string', PropertyType::DECIMAL), // up to the decimal functions to validate - - // stream to... - array($stream, PropertyType::BINARY, 'test string', PropertyType::STRING), - array($stream, PropertyType::BINARY, 0, PropertyType::LONG), - array($numberstream, PropertyType::BINARY, 123, PropertyType::LONG), - array($stream, PropertyType::BINARY, 0.0, PropertyType::DOUBLE), - array($numberstream, PropertyType::BINARY, 123.456, PropertyType::DOUBLE), - array($stream, PropertyType::BINARY, null, PropertyType::DATE), - array($datestream, PropertyType::BINARY, new \DateTime('17.12.2010 GMT'), PropertyType::DATE), - array($stream, PropertyType::BINARY, true, PropertyType::BOOLEAN), - // TODO: check NAME may not have spaces array($stream, PropertyType::BINARY, null, PropertyType::NAME), - array($namestream, PropertyType::BINARY, 'test', PropertyType::NAME), - // TODO: check PATH may not have spaces array($stream, PropertyType::BINARY, null, PropertyType::PATH), - // TODO: should we move UUIDHelper to phpcr so we can check in PropertyType? array($stream, PropertyType::STRING, null, PropertyType::REFERENCE), - array($uuidstream, PropertyType::BINARY, '38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::REFERENCE), - array($stream, PropertyType::BINARY, 'test string', PropertyType::DECIMAL), // up to the decimal functions to validate - - // invalid stream resource - array($stream, PropertyType::DECIMAL, null, PropertyType::STRING), - - // long to... - array(123, PropertyType::LONG, '123', PropertyType::STRING), - array(123, PropertyType::LONG, 123, PropertyType::LONG), - array(123, PropertyType::LONG, 123.0, PropertyType::DOUBLE), - array(123, PropertyType::LONG, $datetimeLong, PropertyType::DATE), - array(123, PropertyType::LONG, true, PropertyType::BOOLEAN), - array(0, PropertyType::LONG, false, PropertyType::BOOLEAN), - array(123, PropertyType::LONG, null, PropertyType::NAME), - array(123, PropertyType::LONG, null, PropertyType::PATH), - array(123, PropertyType::LONG, null, PropertyType::REFERENCE), - array(123, PropertyType::LONG, null, PropertyType::URI), - array(123, PropertyType::LONG, '123', PropertyType::DECIMAL), - - // double to... - array(123.1, PropertyType::DOUBLE, '123.1', PropertyType::STRING), - array(123.1, PropertyType::DOUBLE, 123, PropertyType::LONG), - array(123.1, PropertyType::DOUBLE, 123.1, PropertyType::DOUBLE), - array(123.1, PropertyType::DOUBLE, $datetimeLong, PropertyType::DATE), - array(123.1, PropertyType::DOUBLE, true, PropertyType::BOOLEAN), - array(0.0, PropertyType::DOUBLE, false, PropertyType::BOOLEAN), - array(123.1, PropertyType::DOUBLE, null, PropertyType::NAME), - array(123.1, PropertyType::DOUBLE, null, PropertyType::PATH), - array(123.1, PropertyType::DOUBLE, null, PropertyType::REFERENCE), - array(123.1, PropertyType::DOUBLE, null, PropertyType::URI), - array(123.1, PropertyType::DOUBLE, '123.1', PropertyType::DECIMAL), - - // date to... - array($datetimeLong, PropertyType::DATE, $datetimeLong->format('Y-m-d\TH:i:s.') . substr($datetimeLong->format('u'), 0, 3) . $datetimeLong->format('P'), PropertyType::STRING), - array($datetimeLong, PropertyType::DATE, 123, PropertyType::LONG), - array($datetimeLong, PropertyType::DATE, 123.0, PropertyType::DOUBLE), - array($datetimeLong, PropertyType::DATE, $datetimeLong, PropertyType::DATE), - array($datetimeLong, PropertyType::DATE, true, PropertyType::BOOLEAN), - array($datetimeLong, PropertyType::DATE, null, PropertyType::NAME), - array($datetimeLong, PropertyType::DATE, null, PropertyType::PATH), - array($datetimeLong, PropertyType::DATE, null, PropertyType::REFERENCE), - array($datetimeLong, PropertyType::DATE, null, PropertyType::URI), - array($datetimeLong, PropertyType::DATE, '123', PropertyType::DECIMAL), - - // boolean to... - array(true, PropertyType::BOOLEAN, '1', PropertyType::STRING), - array(false, PropertyType::BOOLEAN, '', PropertyType::STRING), - array(true, PropertyType::BOOLEAN, null, PropertyType::DATE), - array(true, PropertyType::BOOLEAN, 1, PropertyType::LONG), - array(true, PropertyType::BOOLEAN, 1.0, PropertyType::DOUBLE), - array(true, PropertyType::BOOLEAN, true, PropertyType::BOOLEAN), - array(true, PropertyType::BOOLEAN, null, PropertyType::NAME), - array(true, PropertyType::BOOLEAN, null, PropertyType::PATH), - array(true, PropertyType::BOOLEAN, null, PropertyType::REFERENCE), - array(true, PropertyType::BOOLEAN, null, PropertyType::URI), - array(true, PropertyType::BOOLEAN, '1', PropertyType::DECIMAL), - array(false, PropertyType::BOOLEAN, '', PropertyType::DECIMAL), - - // name to... - array('name', PropertyType::NAME, 'name', PropertyType::STRING), - array('name', PropertyType::NAME, null, PropertyType::DATE), - array('name', PropertyType::NAME, null, PropertyType::LONG), - array('name', PropertyType::NAME, null, PropertyType::DOUBLE), - array('name', PropertyType::NAME, null, PropertyType::BOOLEAN), - array('name', PropertyType::NAME, 'name', PropertyType::NAME), - array('name', PropertyType::NAME, 'name', PropertyType::PATH), - array('name', PropertyType::NAME, null, PropertyType::REFERENCE), - array('name', PropertyType::NAME, '../name', PropertyType::URI), - array('näme', PropertyType::NAME, '../n%C3%A4me', PropertyType::URI), - array('name', PropertyType::NAME, null, PropertyType::DECIMAL), - - // path to... - array('../test/path', PropertyType::PATH, '../test/path', PropertyType::STRING), - array('../test/path', PropertyType::PATH, null, PropertyType::DATE), - array('../test/path', PropertyType::PATH, null, PropertyType::LONG), - array('../test/path', PropertyType::PATH, null, PropertyType::DOUBLE), - array('../test/path', PropertyType::PATH, null, PropertyType::BOOLEAN), - // TODO: fix array('../test/path', PropertyType::PATH, null, PropertyType::NAME), - // TODO: fix array('./path', PropertyType::PATH, 'path', PropertyType::NAME), - array('../test/path', PropertyType::PATH, '../test/path', PropertyType::PATH), - array('../test/path', PropertyType::PATH, null, PropertyType::REFERENCE), - array('../test/path', PropertyType::PATH, '../test/path', PropertyType::URI), - array('../test/päth', PropertyType::PATH, '../test/p%C3%A4th', PropertyType::URI), - array('test', PropertyType::PATH, './test', PropertyType::URI), - array('../test/path', PropertyType::PATH, null, PropertyType::DECIMAL), - - // reference to... - array('38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::REFERENCE, '38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::STRING), - array($nodemock, PropertyType::REFERENCE, '38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::STRING), - array('38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::REFERENCE, '38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::REFERENCE), - array($nodemock, PropertyType::REFERENCE, '38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::REFERENCE), - array('38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::REFERENCE, null, PropertyType::DATE), - array($nodemock, PropertyType::REFERENCE, null, PropertyType::DATE), - array('38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::REFERENCE, null, PropertyType::LONG), - array($nodemock, PropertyType::REFERENCE, null, PropertyType::LONG), - array('38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::REFERENCE, null, PropertyType::DOUBLE), - array($nodemock, PropertyType::REFERENCE, null, PropertyType::DOUBLE), - array('38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::REFERENCE, null, PropertyType::BOOLEAN), - array($nodemock, PropertyType::REFERENCE, null, PropertyType::BOOLEAN), - array('38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::REFERENCE, null, PropertyType::NAME), - array($nodemock, PropertyType::REFERENCE, null, PropertyType::NAME), - array('38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::REFERENCE, null, PropertyType::PATH), - array($nodemock, PropertyType::REFERENCE, null, PropertyType::PATH), - array('38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::REFERENCE, null, PropertyType::URI), - array($nodemock, PropertyType::REFERENCE, null, PropertyType::URI), - array('38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::REFERENCE, '38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::REFERENCE), - array('38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::REFERENCE, null, PropertyType::DECIMAL), - array($nodemock, PropertyType::REFERENCE, null, PropertyType::DECIMAL), - - array($this, PropertyType::REFERENCE, null, PropertyType::STRING), - array($this, PropertyType::REFERENCE, null, PropertyType::BINARY), - array($this, PropertyType::REFERENCE, null, PropertyType::DATE), - array($this, PropertyType::REFERENCE, null, PropertyType::LONG), - array($this, PropertyType::REFERENCE, null, PropertyType::DOUBLE), - array($this, PropertyType::REFERENCE, null, PropertyType::BOOLEAN), - array($this, PropertyType::REFERENCE, null, PropertyType::NAME), - array($this, PropertyType::REFERENCE, null, PropertyType::PATH), - array($this, PropertyType::REFERENCE, null, PropertyType::URI), - array($this, PropertyType::REFERENCE, null, PropertyType::DECIMAL), - - // weak to... - array('38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::WEAKREFERENCE, '38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::STRING), - array($nodemock, PropertyType::WEAKREFERENCE, '38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::STRING), - array('38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::WEAKREFERENCE, '38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::REFERENCE), - array($nodemock, PropertyType::WEAKREFERENCE, '38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::REFERENCE), - array('38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::WEAKREFERENCE, null, PropertyType::DATE), - array($nodemock, PropertyType::WEAKREFERENCE, null, PropertyType::DATE), - array('38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::WEAKREFERENCE, null, PropertyType::LONG), - array($nodemock, PropertyType::WEAKREFERENCE, null, PropertyType::LONG), - array('38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::WEAKREFERENCE, null, PropertyType::DOUBLE), - array($nodemock, PropertyType::WEAKREFERENCE, null, PropertyType::DOUBLE), - array('38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::WEAKREFERENCE, null, PropertyType::BOOLEAN), - array($nodemock, PropertyType::WEAKREFERENCE, null, PropertyType::BOOLEAN), - array('38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::WEAKREFERENCE, null, PropertyType::NAME), - array($nodemock, PropertyType::WEAKREFERENCE, null, PropertyType::NAME), - array('38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::WEAKREFERENCE, null, PropertyType::PATH), - array($nodemock, PropertyType::WEAKREFERENCE, null, PropertyType::PATH), - array('38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::WEAKREFERENCE, null, PropertyType::URI), - array($nodemock, PropertyType::WEAKREFERENCE, null, PropertyType::URI), - array('38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::WEAKREFERENCE, '38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::REFERENCE), - array('38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::WEAKREFERENCE, null, PropertyType::DECIMAL), - array($nodemock, PropertyType::WEAKREFERENCE, null, PropertyType::DECIMAL), + return [ + // String to... + ['test string', PropertyType::STRING, 'test string', PropertyType::STRING], + ['test string', PropertyType::STRING, 0, PropertyType::LONG], + ['378.37', PropertyType::STRING, 378, PropertyType::LONG], + ['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], + ['test string', PropertyType::STRING, true, PropertyType::BOOLEAN], + ['false', PropertyType::STRING, true, PropertyType::BOOLEAN], + ['', PropertyType::STRING, false, PropertyType::BOOLEAN], + // TODO: check NAME may not have spaces ['test string', PropertyType::STRING, null, PropertyType::NAME], + ['test', PropertyType::STRING, 'test', PropertyType::NAME], + // TODO: check PATH may not have spaces ['test string', PropertyType::STRING, null, PropertyType::PATH], + ['../the/node', PropertyType::STRING, '../the/node', PropertyType::PATH], + ['38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::STRING, '38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::REFERENCE], + // TODO: should we move UUIDHelper to phpcr so we can check in PropertyType? ['test string', PropertyType::STRING, null, PropertyType::REFERENCE], + ['', PropertyType::STRING, null, PropertyType::REFERENCE], + ['http://phpcr.github.com/', PropertyType::STRING, 'http://phpcr.github.com/', PropertyType::URI], + ['test string', PropertyType::STRING, 'test string', PropertyType::DECIMAL], // up to the decimal functions to validate + + // Stream to... + [$stream, PropertyType::BINARY, 'test string', PropertyType::STRING], + [$stream, PropertyType::BINARY, 0, PropertyType::LONG], + [$numberStream, PropertyType::BINARY, 123, PropertyType::LONG], + [$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], + [$stream, PropertyType::BINARY, true, PropertyType::BOOLEAN], + // TODO: check NAME may not have spaces [$stream, PropertyType::BINARY, null, PropertyType::NAME], + [$nameStream, PropertyType::BINARY, 'test', PropertyType::NAME], + // TODO: check PATH may not have spaces [$stream, PropertyType::BINARY, null, PropertyType::PATH], + // TODO: should we move UUIDHelper to phpcr so we can check in PropertyType? [$stream, PropertyType::STRING, null, PropertyType::REFERENCE], + [$uuidStream, PropertyType::BINARY, '38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::REFERENCE], + [$stream, PropertyType::BINARY, 'test string', PropertyType::DECIMAL], // up to the decimal functions to validate + + // Invalid stream resource + [$stream, PropertyType::DECIMAL, null, PropertyType::STRING], + + // Long to... + [123, PropertyType::LONG, '123', PropertyType::STRING], + [123, PropertyType::LONG, 123, PropertyType::LONG], + [123, PropertyType::LONG, 123.0, PropertyType::DOUBLE], + [123, PropertyType::LONG, $datetimeLong, PropertyType::DATE], + [123, PropertyType::LONG, true, PropertyType::BOOLEAN], + [0, PropertyType::LONG, false, PropertyType::BOOLEAN], + [123, PropertyType::LONG, null, PropertyType::NAME], + [123, PropertyType::LONG, null, PropertyType::PATH], + [123, PropertyType::LONG, null, PropertyType::REFERENCE], + [123, PropertyType::LONG, null, PropertyType::URI], + [123, PropertyType::LONG, '123', PropertyType::DECIMAL], + + // Double to... + [123.1, PropertyType::DOUBLE, '123.1', PropertyType::STRING], + [123.1, PropertyType::DOUBLE, 123, PropertyType::LONG], + [123.1, PropertyType::DOUBLE, 123.1, PropertyType::DOUBLE], + [123.1, PropertyType::DOUBLE, $datetimeLong, PropertyType::DATE], + [123.1, PropertyType::DOUBLE, true, PropertyType::BOOLEAN], + [0.0, PropertyType::DOUBLE, false, PropertyType::BOOLEAN], + [123.1, PropertyType::DOUBLE, null, PropertyType::NAME], + [123.1, PropertyType::DOUBLE, null, PropertyType::PATH], + [123.1, PropertyType::DOUBLE, null, PropertyType::REFERENCE], + [123.1, PropertyType::DOUBLE, null, PropertyType::URI], + [123.1, PropertyType::DOUBLE, '123.1', PropertyType::DECIMAL], + + // Date to... + [$datetimeLong, PropertyType::DATE, $datetimeLong->format('Y-m-d\TH:i:s.') . substr($datetimeLong->format('u'), 0, 3) . $datetimeLong->format('P'), PropertyType::STRING], + [$datetimeLong, PropertyType::DATE, 123, PropertyType::LONG], + [$datetimeLong, PropertyType::DATE, 123.0, PropertyType::DOUBLE], + [$datetimeLong, PropertyType::DATE, $datetimeLong, PropertyType::DATE], + [$datetimeLong, PropertyType::DATE, true, PropertyType::BOOLEAN], + [$datetimeLong, PropertyType::DATE, null, PropertyType::NAME], + [$datetimeLong, PropertyType::DATE, null, PropertyType::PATH], + [$datetimeLong, PropertyType::DATE, null, PropertyType::REFERENCE], + [$datetimeLong, PropertyType::DATE, null, PropertyType::URI], + [$datetimeLong, PropertyType::DATE, '123', PropertyType::DECIMAL], + + // Boolean to... + [true, PropertyType::BOOLEAN, '1', PropertyType::STRING], + [false, PropertyType::BOOLEAN, '', PropertyType::STRING], + [true, PropertyType::BOOLEAN, null, PropertyType::DATE], + [true, PropertyType::BOOLEAN, 1, PropertyType::LONG], + [true, PropertyType::BOOLEAN, 1.0, PropertyType::DOUBLE], + [true, PropertyType::BOOLEAN, true, PropertyType::BOOLEAN], + [true, PropertyType::BOOLEAN, null, PropertyType::NAME], + [true, PropertyType::BOOLEAN, null, PropertyType::PATH], + [true, PropertyType::BOOLEAN, null, PropertyType::REFERENCE], + [true, PropertyType::BOOLEAN, null, PropertyType::URI], + [true, PropertyType::BOOLEAN, '1', PropertyType::DECIMAL], + [false, PropertyType::BOOLEAN, '', PropertyType::DECIMAL], + + // Name to... + ['name', PropertyType::NAME, 'name', PropertyType::STRING], + ['name', PropertyType::NAME, null, PropertyType::DATE], + ['name', PropertyType::NAME, null, PropertyType::LONG], + ['name', PropertyType::NAME, null, PropertyType::DOUBLE], + ['name', PropertyType::NAME, null, PropertyType::BOOLEAN], + ['name', PropertyType::NAME, 'name', PropertyType::NAME], + ['name', PropertyType::NAME, 'name', PropertyType::PATH], + ['name', PropertyType::NAME, null, PropertyType::REFERENCE], + ['name', PropertyType::NAME, '../name', PropertyType::URI], + ['näme', PropertyType::NAME, '../n%C3%A4me', PropertyType::URI], + ['name', PropertyType::NAME, null, PropertyType::DECIMAL], + + // Path to... + ['../test/path', PropertyType::PATH, '../test/path', PropertyType::STRING], + ['../test/path', PropertyType::PATH, null, PropertyType::DATE], + ['../test/path', PropertyType::PATH, null, PropertyType::LONG], + ['../test/path', PropertyType::PATH, null, PropertyType::DOUBLE], + ['../test/path', PropertyType::PATH, null, PropertyType::BOOLEAN], + // TODO: fix ['../test/path', PropertyType::PATH, null, PropertyType::NAME], + // TODO: fix ['./path', PropertyType::PATH, 'path', PropertyType::NAME], + ['../test/path', PropertyType::PATH, '../test/path', PropertyType::PATH], + ['../test/path', PropertyType::PATH, null, PropertyType::REFERENCE], + ['../test/path', PropertyType::PATH, '../test/path', PropertyType::URI], + ['../test/päth', PropertyType::PATH, '../test/p%C3%A4th', PropertyType::URI], + ['test', PropertyType::PATH, './test', PropertyType::URI], + ['../test/path', PropertyType::PATH, null, PropertyType::DECIMAL], + + // Reference to... + ['38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::REFERENCE, '38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::STRING], + [$nodeMock, PropertyType::REFERENCE, '38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::STRING], + ['38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::REFERENCE, '38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::REFERENCE], + [$nodeMock, PropertyType::REFERENCE, '38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::REFERENCE], + ['38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::REFERENCE, null, PropertyType::DATE], + [$nodeMock, PropertyType::REFERENCE, null, PropertyType::DATE], + ['38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::REFERENCE, null, PropertyType::LONG], + [$nodeMock, PropertyType::REFERENCE, null, PropertyType::LONG], + ['38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::REFERENCE, null, PropertyType::DOUBLE], + [$nodeMock, PropertyType::REFERENCE, null, PropertyType::DOUBLE], + ['38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::REFERENCE, null, PropertyType::BOOLEAN], + [$nodeMock, PropertyType::REFERENCE, null, PropertyType::BOOLEAN], + ['38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::REFERENCE, null, PropertyType::NAME], + [$nodeMock, PropertyType::REFERENCE, null, PropertyType::NAME], + ['38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::REFERENCE, null, PropertyType::PATH], + [$nodeMock, PropertyType::REFERENCE, null, PropertyType::PATH], + ['38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::REFERENCE, null, PropertyType::URI], + [$nodeMock, PropertyType::REFERENCE, null, PropertyType::URI], + ['38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::REFERENCE, '38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::REFERENCE], + ['38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::REFERENCE, null, PropertyType::DECIMAL], + [$nodeMock, PropertyType::REFERENCE, null, PropertyType::DECIMAL], + + [$this, PropertyType::REFERENCE, null, PropertyType::STRING], + [$this, PropertyType::REFERENCE, null, PropertyType::BINARY], + [$this, PropertyType::REFERENCE, null, PropertyType::DATE], + [$this, PropertyType::REFERENCE, null, PropertyType::LONG], + [$this, PropertyType::REFERENCE, null, PropertyType::DOUBLE], + [$this, PropertyType::REFERENCE, null, PropertyType::BOOLEAN], + [$this, PropertyType::REFERENCE, null, PropertyType::NAME], + [$this, PropertyType::REFERENCE, null, PropertyType::PATH], + [$this, PropertyType::REFERENCE, null, PropertyType::URI], + [$this, PropertyType::REFERENCE, null, PropertyType::DECIMAL], + + // Weak to... + ['38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::WEAKREFERENCE, '38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::STRING], + [$nodeMock, PropertyType::WEAKREFERENCE, '38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::STRING], + ['38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::WEAKREFERENCE, '38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::REFERENCE], + [$nodeMock, PropertyType::WEAKREFERENCE, '38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::REFERENCE], + ['38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::WEAKREFERENCE, null, PropertyType::DATE], + [$nodeMock, PropertyType::WEAKREFERENCE, null, PropertyType::DATE], + ['38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::WEAKREFERENCE, null, PropertyType::LONG], + [$nodeMock, PropertyType::WEAKREFERENCE, null, PropertyType::LONG], + ['38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::WEAKREFERENCE, null, PropertyType::DOUBLE], + [$nodeMock, PropertyType::WEAKREFERENCE, null, PropertyType::DOUBLE], + ['38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::WEAKREFERENCE, null, PropertyType::BOOLEAN], + [$nodeMock, PropertyType::WEAKREFERENCE, null, PropertyType::BOOLEAN], + ['38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::WEAKREFERENCE, null, PropertyType::NAME], + [$nodeMock, PropertyType::WEAKREFERENCE, null, PropertyType::NAME], + ['38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::WEAKREFERENCE, null, PropertyType::PATH], + [$nodeMock, PropertyType::WEAKREFERENCE, null, PropertyType::PATH], + ['38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::WEAKREFERENCE, null, PropertyType::URI], + [$nodeMock, PropertyType::WEAKREFERENCE, null, PropertyType::URI], + ['38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::WEAKREFERENCE, '38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::REFERENCE], + ['38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::WEAKREFERENCE, null, PropertyType::DECIMAL], + [$nodeMock, PropertyType::WEAKREFERENCE, null, PropertyType::DECIMAL], // uri to... - array('http://phpcr.githbub.com/doc/html', PropertyType::URI, 'http://phpcr.githbub.com/doc/html', PropertyType::STRING), - array('http://phpcr.githbub.com/doc/html', PropertyType::URI, null, PropertyType::DATE), - array('http://phpcr.githbub.com/doc/html', PropertyType::URI, null, PropertyType::LONG), - array('http://phpcr.githbub.com/doc/html', PropertyType::URI, null, PropertyType::DOUBLE), - array('http://phpcr.githbub.com/doc/html', PropertyType::URI, null, PropertyType::BOOLEAN), - // TODO: fix array('http://phpcr.githbub.com/doc/html', PropertyType::URI, null, PropertyType::NAME), - // TODO: fix array('http://phpcr.githbub.com/doc/html', PropertyType::URI, null, PropertyType::PATH), - array('http://phpcr.githbub.com/doc/html', PropertyType::URI, null, PropertyType::REFERENCE), - array('http://phpcr.githbub.com/doc/html', PropertyType::URI, 'http://phpcr.githbub.com/doc/html', PropertyType::URI), - array('http://phpcr.githbub.com/doc/html', PropertyType::URI, null, PropertyType::DECIMAL), + ['http://phpcr.githbub.com/doc/html', PropertyType::URI, 'http://phpcr.githbub.com/doc/html', PropertyType::STRING], + ['http://phpcr.githbub.com/doc/html', PropertyType::URI, null, PropertyType::DATE], + ['http://phpcr.githbub.com/doc/html', PropertyType::URI, null, PropertyType::LONG], + ['http://phpcr.githbub.com/doc/html', PropertyType::URI, null, PropertyType::DOUBLE], + ['http://phpcr.githbub.com/doc/html', PropertyType::URI, null, PropertyType::BOOLEAN], + // TODO: fix ['http://phpcr.githbub.com/doc/html', PropertyType::URI, null, PropertyType::NAME], + // TODO: fix ['http://phpcr.githbub.com/doc/html', PropertyType::URI, null, PropertyType::PATH], + ['http://phpcr.githbub.com/doc/html', PropertyType::URI, null, PropertyType::REFERENCE], + ['http://phpcr.githbub.com/doc/html', PropertyType::URI, 'http://phpcr.githbub.com/doc/html', PropertyType::URI], + ['http://phpcr.githbub.com/doc/html', PropertyType::URI, null, PropertyType::DECIMAL], // decimal to... - array('123.4', PropertyType::DECIMAL, '123.4', PropertyType::STRING), - array('123.4', PropertyType::DECIMAL, $datetimeLong, PropertyType::DATE), - array('123.4', PropertyType::DECIMAL, 123, PropertyType::LONG), - array('123.4', PropertyType::DECIMAL, 123.4, PropertyType::DOUBLE), - array('123.4', PropertyType::DECIMAL, true, PropertyType::BOOLEAN), - array('0', PropertyType::DECIMAL, false, PropertyType::BOOLEAN), - array('123.4', PropertyType::DECIMAL, null, PropertyType::NAME), - array('123.4', PropertyType::DECIMAL, null, PropertyType::PATH), - array('123.4', PropertyType::DECIMAL, null, PropertyType::URI), - array('123.4', PropertyType::DECIMAL, null, PropertyType::REFERENCE), - array('123.4', PropertyType::DECIMAL, '123.4', PropertyType::DECIMAL), - ); + ['123.4', PropertyType::DECIMAL, '123.4', PropertyType::STRING], + ['123.4', PropertyType::DECIMAL, $datetimeLong, PropertyType::DATE], + ['123.4', PropertyType::DECIMAL, 123, PropertyType::LONG], + ['123.4', PropertyType::DECIMAL, 123.4, PropertyType::DOUBLE], + ['123.4', PropertyType::DECIMAL, true, PropertyType::BOOLEAN], + ['0', PropertyType::DECIMAL, false, PropertyType::BOOLEAN], + ['123.4', PropertyType::DECIMAL, null, PropertyType::NAME], + ['123.4', PropertyType::DECIMAL, null, PropertyType::PATH], + ['123.4', PropertyType::DECIMAL, null, PropertyType::URI], + ['123.4', PropertyType::DECIMAL, null, PropertyType::REFERENCE], + ['123.4', PropertyType::DECIMAL, '123.4', PropertyType::DECIMAL], + ]; } /** * Skip binary target as its a special case * - * @param int $srctype PropertyType constant to convert from - * @param $validtargets array map of target type => value | null for exception + * @param mixed $value + * @param int $srcType PropertyType constant to convert from + * @param $expected + * @param $targetType * * @dataProvider dataConversionMatrix */ - public function testConvertType($value, $srctype, $expected, $targettype) + public function testConvertType($value, $srcType, $expected, $targetType) { if (null === $expected) { try { - $this->valueConverter->convertType($value, $targettype, $srctype); - $this->fail('Excpected that this conversion would throw an exception'); - } catch (\PHPCR\ValueFormatException $e) { + $this->valueConverter->convertType($value, $targetType, $srcType); + $this->fail('Expected that this conversion would throw an exception'); + } catch (ValueFormatException $e) { // expected $this->assertTrue(true); // make it assert something } } else { - if ($expected instanceof \DateTime) { - $result = $this->valueConverter->convertType($value, $targettype, $srctype); - $this->assertInstanceOf('DateTime', $result); + if ($expected instanceof DateTime) { + $result = $this->valueConverter->convertType($value, $targetType, $srcType); + $this->assertInstanceOf(DateTime::class, $result); $this->assertEquals($expected->getTimestamp(), $result->getTimestamp()); } else { - $this->assertSame($expected, $this->valueConverter->convertType($value, $targettype, $srctype)); + $this->assertSame($expected, $this->valueConverter->convertType($value, $targetType, $srcType)); } } } @@ -303,11 +313,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->assertInternalType('resource', $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'); @@ -322,121 +332,119 @@ public function testConvertTypeToBinary() public function testConvertTypeArray() { - $result = $this->valueConverter->convertType(array('2012-01-10', '2012-02-12'), + $result = $this->valueConverter->convertType(['2012-01-10', '2012-02-12'], PropertyType::DATE, PropertyType::STRING); $this->assertInternalType('array', $result); $this->assertCount(2, $result); - $this->assertInstanceOf('DateTime', $result[0]); - $this->assertInstanceOf('DateTime', $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')); - $result = $this->valueConverter->convertType(array(), PropertyType::STRING, PropertyType::NAME); - $this->assertEquals(array(), $result); + $result = $this->valueConverter->convertType([], PropertyType::STRING, PropertyType::NAME); + $this->assertEquals([], $result); } 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', $result); + $this->assertInstanceOf(DateTime::class, $result); $this->assertEquals(1331668855, $result->getTimestamp()); } - /** - * @expectedException \PHPCR\ValueFormatException - */ public function testConvertTypeArrayInvalid() { - $this->valueConverter->convertType(array('a', 'b', 'c'), PropertyType::NAME, PropertyType::REFERENCE); + $this->expectException(ValueFormatException::class); + + $this->valueConverter->convertType(['a', 'b', 'c'], PropertyType::NAME, PropertyType::REFERENCE); } - /** - * @expectedException \PHPCR\ValueFormatException - */ public function testConvertInvalidString() { + $this->expectException(ValueFormatException::class); + $this->valueConverter->convertType($this, PropertyType::STRING); } - /** - * @expectedException \PHPCR\ValueFormatException - */ + public function testConvertInvalidBinary() { + $this->expectException(ValueFormatException::class); + $this->valueConverter->convertType($this, PropertyType::BINARY); } - /** - * @expectedException \PHPCR\ValueFormatException - */ + public function testConvertInvalidDate() { + $this->expectException(ValueFormatException::class); + $this->valueConverter->convertType($this, PropertyType::DATE); } - /** - * @expectedException \PHPCR\ValueFormatException - */ public function testConvertNewNode() { - $nodemock = $this->getMock('PHPCR\Tests\Stubs\MockNode'); - $nodemock + $this->expectException(ValueFormatException::class); + + $nodeMock = $this->createMock(MockNode::class); + $nodeMock ->expects($this->never()) ->method('isNew') ->will($this->returnValue(true)) ; - $this->valueConverter->convertType($nodemock, PropertyType::STRING); + $this->valueConverter->convertType($nodeMock, PropertyType::STRING); } - /** - * @expectedException \PHPCR\ValueFormatException - */ - public function testConvertNonrefNode() + + public function testConvertNonRefNode() { - $nodemock = $this->getMock('PHPCR\Tests\Stubs\MockNode'); - $nodemock + $this->expectException(ValueFormatException::class); + + $nodeMock = $this->createMock(MockNode::class); + $nodeMock ->expects($this->never()) ->method('isNew') ->will($this->returnValue(false)) ; - $nodemock + $nodeMock ->expects($this->once()) ->method('isNodeType') ->with('mix:referenceable') ->will($this->returnValue(false)) ; - $this->valueConverter->convertType($nodemock, PropertyType::STRING); + $this->valueConverter->convertType($nodeMock, PropertyType::STRING); } public function dataDateTargetType() { - return array( - array(PropertyType::STRING), - array(PropertyType::LONG), - array(PropertyType::DOUBLE), - ); + return [ + [PropertyType::STRING], + [PropertyType::LONG], + [PropertyType::DOUBLE], + ]; } /** * Check if the util will survive a broken implementation - * @expectedException \PHPCR\RepositoryException + * * @dataProvider dataDateTargetType */ public function testConvertInvalidDateValue($targettype) { + $this->expectException(RepositoryException::class); + $this->valueConverter->convertType('', $targettype, PropertyType::DATE); } - /** - * @expectedException \PHPCR\ValueFormatException - */ public function testConvertTypeInvalidTarget() { + $this->expectException(ValueFormatException::class); + $this->valueConverter->convertType('test', PropertyType::UNDEFINED); } } From 9bf4f50fbbcc00108ac73b8999983c293a4be6f1 Mon Sep 17 00:00:00 2001 From: Pavel Vondrasek Date: Sat, 21 Jan 2017 01:13:31 +0100 Subject: [PATCH 08/88] I think that I must remove bonus because it breaks our tests :( :-D (evil PHP 7) --- composer.json | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/composer.json b/composer.json index 4a32c02..71e3cd6 100644 --- a/composer.json +++ b/composer.json @@ -33,8 +33,7 @@ }, "require-dev": { "ramsey/uuid": "^3.5", - "phpunit/phpunit": "^5.7", - "phpstan/phpstan": "^0.6.0" + "phpunit/phpunit": "^5.7" }, "suggest": { "ramsey/uuid": "A PHP 5.4+ library for generating RFC 4122 version 1, 3, 4, and 5 universally unique identifiers (UUID)." From 38aadebe5079c67e08f4872b8c23c5bda13976d3 Mon Sep 17 00:00:00 2001 From: Pavel Vondrasek Date: Sat, 21 Jan 2017 14:30:43 +0100 Subject: [PATCH 09/88] added phpunit in vendor to .travis --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 5a3f048..d5cce21 100644 --- a/.travis.yml +++ b/.travis.yml @@ -21,7 +21,7 @@ before_script: - if [[ "$PACKAGE_VERSION" == "high" ]]; then composer update --prefer-source; fi - if [[ "$PACKAGE_VERSION" == "low" ]]; then composer update --prefer-lowest --prefer-source; fi -script: phpunit -c tests/phpunit.xml.dist +script: php vendor/bin/phpunit -c tests/phpunit.xml.dist notifications: irc: "irc.freenode.org#jackalope" From b222c2ad9f4772257106c77da8048f9ced5af111 Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Thu, 2 Mar 2017 08:29:32 +0100 Subject: [PATCH 10/88] no point in passing an empty argument. and this started failing now --- .../PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php index 381cdf5..db97551 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php @@ -94,7 +94,6 @@ public function testNodeUpdate($options) $this->setupQueryManager($options); $args = [ - '--query-language' => null, '--query' => $options['query'], '--no-interaction' => true, '--set-prop' => [], From a0add7fcfe08ee5f6d98bea6a2e3169775358bc3 Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Thu, 13 Jul 2017 08:44:20 +0200 Subject: [PATCH 11/88] Update .travis.yml --- .travis.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index d5cce21..b813824 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,7 +4,6 @@ php: - 5.6 - 7.0 - 7.1 - - hhvm env: - PACKAGE_VERSION=high @@ -15,6 +14,8 @@ matrix: include: - php: 5.6 env: PACKAGE_VERSION=low + - php: hhvm + dist: trusty before_script: - composer selfupdate From 7e52120c8ac638c3c690d582d1c63c6cc3d87449 Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Wed, 27 Sep 2017 08:19:51 +0000 Subject: [PATCH 12/88] Apply fixes from StyleCI --- src/PHPCR/Util/CND/Parser/CndParser.php | 54 +++++++++---------- .../Scanner/Context/DefaultScannerContext.php | 4 +- .../CND/Scanner/Context/ScannerContext.php | 12 ++--- src/PHPCR/Util/CND/Scanner/TokenQueue.php | 2 +- src/PHPCR/Util/CND/Writer/CndWriter.php | 2 +- .../Util/Console/Command/NodeDumpCommand.php | 4 +- .../Util/Console/Command/NodeTouchCommand.php | 4 +- .../Console/Command/NodesUpdateCommand.php | 4 +- .../Helper/PhpcrConsoleDumperHelper.php | 4 +- src/PHPCR/Util/Console/Helper/PhpcrHelper.php | 14 ++--- .../ConsoleDumperPropertyVisitor.php | 16 +++--- src/PHPCR/Util/NodeHelper.php | 8 +-- src/PHPCR/Util/PathHelper.php | 4 +- .../Util/QOM/BaseQomToSqlQueryConverter.php | 2 +- src/PHPCR/Util/QOM/QueryBuilder.php | 2 +- .../Util/QOM/Sql2ToQomQueryConverter.php | 24 ++++----- src/PHPCR/Util/ValueConverter.php | 2 +- .../Tests/Util/CND/Scanner/TokenQueueTest.php | 2 +- .../Console/Command/NodeDumpCommandTest.php | 2 +- .../Console/Command/NodeRemoveCommandTest.php | 8 +-- .../Command/NodesUpdateCommandTest.php | 8 +-- .../Command/WorkspaceDeleteCommandTest.php | 4 +- .../Command/WorkspaceListCommandTest.php | 4 +- tests/PHPCR/Tests/Util/PathHelperTest.php | 10 ++-- .../PHPCR/Tests/Util/QOM/QueryBuilderTest.php | 2 +- .../Tests/Util/QOM/Sql2GeneratorTest.php | 2 +- 26 files changed, 102 insertions(+), 102 deletions(-) diff --git a/src/PHPCR/Util/CND/Parser/CndParser.php b/src/PHPCR/Util/CND/Parser/CndParser.php index a912ff5..7dc5b48 100644 --- a/src/PHPCR/Util/CND/Parser/CndParser.php +++ b/src/PHPCR/Util/CND/Parser/CndParser.php @@ -36,30 +36,30 @@ class CndParser extends AbstractParser { // node type attributes - private $ORDERABLE = array('o', 'ord', 'orderable');//, 'variant' => true); - private $MIXIN = array('m', 'mix', 'mixin');//, 'variant' => true); - private $ABSTRACT = array('a', 'abs', 'abstract');//, 'variant' => true); - private $NOQUERY = array('noquery', 'nq');//, 'variant' => false); - private $QUERY = array('query', 'q');//, 'variant' => false); - private $PRIMARYITEM = array('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 = array('!', 'pri', 'primary'); //, 'variant' => true), - private $AUTOCREATED = array('a', 'aut', 'autocreated'); //, 'variant' => true), - private $MANDATORY = array('m', 'man', 'mandatory'); //, 'variant' => true), - private $PROTECTED = array('p', 'pro', 'protected'); //, 'variant' => true), - private $OPV = array('COPY', 'VERSION', 'INITIALIZE', 'COMPUTE', 'IGNORE', 'ABORT'); + 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 = array('*', 'mul', 'multiple'); //, 'variant' => true), - private $QUERYOPS = array('qop', 'queryops'); //, 'variant' => true), // Needs special handling ! - private $NOFULLTEXT = array('nof', 'nofulltext'); //, 'variant' => true), - private $NOQUERYORDER = array('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 = array('*', 'sns', 'multiple'); //, 'variant' => true), + private $SNS = ['*', 'sns', 'multiple']; //, 'variant' => true), /** * @var NodeTypeManagerInterface @@ -69,12 +69,12 @@ class CndParser extends AbstractParser /** * @var array */ - protected $namespaces = array(); + protected $namespaces = []; /** * @var array */ - protected $nodeTypes = array(); + protected $nodeTypes = []; /** * @param NodeTypeManagerInterface $ntm @@ -129,10 +129,10 @@ private function parse(ReaderInterface $reader) } } - return array( + return [ 'namespaces' => $this->namespaces, 'nodeTypes' => $this->nodeTypes, - ); + ]; } /** @@ -208,7 +208,7 @@ protected function parseSupertypes(NodeTypeTemplateInterface $nodeType) $this->expectToken(Token::TK_SYMBOL, '>'); if ($this->checkAndExpectToken(Token::TK_SYMBOL, '?')) { - $nodeType->setDeclaredSuperTypeNames(array('?')); + $nodeType->setDeclaredSuperTypeNames(['?']); } else { $nodeType->setDeclaredSuperTypeNames($this->parseCndStringList()); } @@ -369,8 +369,8 @@ protected function parsePropDef(NodeTypeTemplateInterface $nodeType) */ protected function parsePropertyType(PropertyDefinitionTemplateInterface $property) { - $types = array("STRING", "BINARY", "LONG", "DOUBLE", "BOOLEAN", "DATE", "NAME", "PATH", - "REFERENCE", "WEAKREFERENCE", "DECIMAL", "URI", "UNDEFINED", "*", "?"); + $types = ["STRING", "BINARY", "LONG", "DOUBLE", "BOOLEAN", "DATE", "NAME", "PATH", + "REFERENCE", "WEAKREFERENCE", "DECIMAL", "URI", "UNDEFINED", "*", "?"]; if (! $this->checkTokenIn(Token::TK_IDENTIFIER, $types, true)) { throw new ParserException($this->tokenQueue, sprintf("Invalid property type: %s", $this->tokenQueue->get()->getData())); @@ -394,7 +394,7 @@ protected function parsePropertyType(PropertyDefinitionTemplateInterface $proper protected function parseDefaultValue(PropertyDefinitionTemplateInterface $property) { if ($this->checkAndExpectToken(Token::TK_SYMBOL, '?')) { - $list = array('?'); + $list = ['?']; } else { $list = $this->parseCndStringList(); } @@ -414,7 +414,7 @@ protected function parseValueConstraints(PropertyDefinitionTemplateInterface $pr $this->expectToken(Token::TK_SYMBOL, '<'); if ($this->checkAndExpectToken(Token::TK_SYMBOL, '?')) { - $list = array('?'); + $list = ['?']; } else { $list = $this->parseCndStringList(); } @@ -632,7 +632,7 @@ protected function parseChildNodeAttributes( */ protected function parseCndStringList() { - $strings = array(); + $strings = []; $strings[] = $this->parseCndString(); while ($this->checkAndExpectToken(Token::TK_SYMBOL, ',')) { @@ -728,7 +728,7 @@ protected function parseQueryOpsAttribute() throw new ParserException($this->tokenQueue, 'TODO: understand what "variant" means'); } - $ops = array(); + $ops = []; do { $op = $this->parseQueryOperator(); $ops[] = $op; diff --git a/src/PHPCR/Util/CND/Scanner/Context/DefaultScannerContext.php b/src/PHPCR/Util/CND/Scanner/Context/DefaultScannerContext.php index 1242664..c80705c 100644 --- a/src/PHPCR/Util/CND/Scanner/Context/DefaultScannerContext.php +++ b/src/PHPCR/Util/CND/Scanner/Context/DefaultScannerContext.php @@ -22,10 +22,10 @@ public function __construct() $this->addBlockCommentDelimiter('/*', '*/'); - $symbols = array( + $symbols = [ '<', '>', '+', '*', '%', '&', '/', '(', ')', '=', '?', '#', '|', '!', '~', '[', ']', '{', '}', '$', ',', ';', ':', '.', '-', '_', '\\', - ); + ]; foreach ($symbols as $symbol) { $this->addSymbol($symbol); } diff --git a/src/PHPCR/Util/CND/Scanner/Context/ScannerContext.php b/src/PHPCR/Util/CND/Scanner/Context/ScannerContext.php index 42be844..7a72915 100644 --- a/src/PHPCR/Util/CND/Scanner/Context/ScannerContext.php +++ b/src/PHPCR/Util/CND/Scanner/Context/ScannerContext.php @@ -16,7 +16,7 @@ class ScannerContext * Characters to be considered as white spaces * @var array */ - protected $whitespaces = array(); + protected $whitespaces = []; /** * Characters to be considered as paired string delimiters. @@ -26,21 +26,21 @@ class ScannerContext * * @var array */ - protected $stringDelimiters = array(); + protected $stringDelimiters = []; /** * Line comments start * * @var array */ - protected $lineCommentDelimiters = array(); + protected $lineCommentDelimiters = []; /** * Block comments delimiters * * @var array */ - protected $blockCommentDelimiters = array(); + protected $blockCommentDelimiters = []; /** * Characters to be considered as symbols. @@ -49,12 +49,12 @@ class ScannerContext * * @var array */ - protected $symbols = array(); + protected $symbols = []; /** * @var TokenFilterInterface[] */ - protected $tokenFilters = array(); + protected $tokenFilters = []; /** * @param string $startDelim diff --git a/src/PHPCR/Util/CND/Scanner/TokenQueue.php b/src/PHPCR/Util/CND/Scanner/TokenQueue.php index eff51b4..ae141e1 100644 --- a/src/PHPCR/Util/CND/Scanner/TokenQueue.php +++ b/src/PHPCR/Util/CND/Scanner/TokenQueue.php @@ -15,7 +15,7 @@ class TokenQueue implements \IteratorAggregate */ protected $tokens; - public function __construct($tokens = array()) + public function __construct($tokens = []) { $this->tokens = $tokens; } diff --git a/src/PHPCR/Util/CND/Writer/CndWriter.php b/src/PHPCR/Util/CND/Writer/CndWriter.php index ef8ce79..046d01f 100644 --- a/src/PHPCR/Util/CND/Writer/CndWriter.php +++ b/src/PHPCR/Util/CND/Writer/CndWriter.php @@ -33,7 +33,7 @@ class CndWriter private $ns; /** @var array hashmap of prefix => namespace uri */ - private $namespaces = array(); + private $namespaces = []; /** * @param NodeTypeManagerInterface $ntm diff --git a/src/PHPCR/Util/Console/Command/NodeDumpCommand.php b/src/PHPCR/Util/Console/Command/NodeDumpCommand.php index dbc3bcf..ee22d95 100644 --- a/src/PHPCR/Util/Console/Command/NodeDumpCommand.php +++ b/src/PHPCR/Util/Console/Command/NodeDumpCommand.php @@ -72,14 +72,14 @@ protected function execute(InputInterface $input, OutputInterface $output) $identifier = $input->getArgument('identifier'); // whether to dump node uuid - $options = array(); + $options = []; $options['dump_uuids'] = $input->hasParameterOption('--identifiers'); $options['ref_format'] = $input->getOption('ref-format'); $options['show_props'] = $input->hasParameterOption('--props'); $options['show_sys_nodes'] = $input->hasParameterOption('--sys-nodes'); $options['max_line_length'] = $input->getOption('max_line_length'); - if (null !== $options['ref_format'] && !in_array($options['ref_format'], array('uuid', 'path'))) { + 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"'); } diff --git a/src/PHPCR/Util/Console/Command/NodeTouchCommand.php b/src/PHPCR/Util/Console/Command/NodeTouchCommand.php index b856db8..9e8d72e 100644 --- a/src/PHPCR/Util/Console/Command/NodeTouchCommand.php +++ b/src/PHPCR/Util/Console/Command/NodeTouchCommand.php @@ -132,13 +132,13 @@ protected function execute(InputInterface $input, OutputInterface $output) $node = $parentNode->addNode($nodeName, $type); } - $helper->processNode($output, $node, array( + $helper->processNode($output, $node, [ 'setProp' => $setProp, 'removeProp' => $removeProp, 'addMixins' => $addMixins, 'removeMixins' => $removeMixins, 'dump' => $dump, - )); + ]); $session->save(); diff --git a/src/PHPCR/Util/Console/Command/NodesUpdateCommand.php b/src/PHPCR/Util/Console/Command/NodesUpdateCommand.php index 881406e..ff793ff 100644 --- a/src/PHPCR/Util/Console/Command/NodesUpdateCommand.php +++ b/src/PHPCR/Util/Console/Command/NodesUpdateCommand.php @@ -132,13 +132,13 @@ protected function execute(InputInterface $input, OutputInterface $output) $node = $row->getNode(); - $helper->processNode($output, $node, array( + $helper->processNode($output, $node, [ 'setProp' => $setProp, 'removeProp' => $removeProp, 'addMixins' => $addMixins, 'removeMixins' => $removeMixins, 'applyClosures' => $applyClosures, - )); + ]); $persistIn--; if (0 === $persistIn) { diff --git a/src/PHPCR/Util/Console/Helper/PhpcrConsoleDumperHelper.php b/src/PHPCR/Util/Console/Helper/PhpcrConsoleDumperHelper.php index 35b96ce..9e3a779 100644 --- a/src/PHPCR/Util/Console/Helper/PhpcrConsoleDumperHelper.php +++ b/src/PHPCR/Util/Console/Helper/PhpcrConsoleDumperHelper.php @@ -20,12 +20,12 @@ class PhpcrConsoleDumperHelper extends Helper { public function getTreeWalker(OutputInterface $output, $options) { - $options = array_merge(array( + $options = array_merge([ 'dump_uuids' => false, 'ref_format' => 'uuid', 'show_props' => false, 'show_sys_nodes' => false, - ), $options); + ], $options); $propVisitor = null; $nodeVisitor = new ConsoleDumperNodeVisitor($output, $options['dump_uuids']); diff --git a/src/PHPCR/Util/Console/Helper/PhpcrHelper.php b/src/PHPCR/Util/Console/Helper/PhpcrHelper.php index 889b7f2..d0aea35 100644 --- a/src/PHPCR/Util/Console/Helper/PhpcrHelper.php +++ b/src/PHPCR/Util/Console/Helper/PhpcrHelper.php @@ -64,14 +64,14 @@ public function getName() */ public function processNode(OutputInterface $output, NodeInterface $node, array $operations) { - $operations = array_merge(array( - 'setProp' => array(), - 'removeProp' => array(), - 'addMixins' => array(), - 'removeMixins' => array(), - 'applyClosures' => array(), + $operations = array_merge([ + 'setProp' => [], + 'removeProp' => [], + 'addMixins' => [], + 'removeMixins' => [], + 'applyClosures' => [], 'dump' => false, - ), $operations); + ], $operations); foreach ($operations['setProp'] as $set) { $parts = explode('=', $set); diff --git a/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperPropertyVisitor.php b/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperPropertyVisitor.php index 350b8b3..b2e896f 100644 --- a/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperPropertyVisitor.php +++ b/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperPropertyVisitor.php @@ -33,12 +33,12 @@ class ConsoleDumperPropertyVisitor extends ConsoleDumperItemVisitor * @param OutputInterface $output * @param array $options */ - public function __construct(OutputInterface $output, $options = array()) + public function __construct(OutputInterface $output, $options = []) { - $options = array_merge(array( + $options = array_merge([ 'max_line_length' => 120, 'ref_format' => 'uuid', - ), $options); + ], $options); parent::__construct($output); @@ -69,13 +69,13 @@ public function visit(ItemInterface $item) $value = substr($value, 0, $this->maxLineLength) . '...'; } - $referrers = array(); + $referrers = []; - if (in_array($item->getType(), array( + if (in_array($item->getType(), [ PropertyType::WEAKREFERENCE, PropertyType::REFERENCE - ))) { - $referenceStrings = array(); + ])) { + $referenceStrings = []; if ('path' == $this->refFormat) { $references = (array) $item->getValue(); @@ -90,7 +90,7 @@ public function visit(ItemInterface $item) $value = ''; } - $value = str_replace(array("\n", "\t"), '', $value); + $value = str_replace(["\n", "\t"], '', $value); $this->output->writeln(str_repeat(' ', $this->level + 1) . '- ' . $item->getName() . ' = ' . $value); diff --git a/src/PHPCR/Util/NodeHelper.php b/src/PHPCR/Util/NodeHelper.php index dcc28c1..087068c 100644 --- a/src/PHPCR/Util/NodeHelper.php +++ b/src/PHPCR/Util/NodeHelper.php @@ -176,10 +176,10 @@ public static function generateAutoNodeName($usedNames, $namespaces, $defaultNam return self::generateWithPrefix($usedNames, ''); } - /* - * "somePrefix:" where somePrefix is a syntactically - * valid namespace prefix - */ + /* + * "somePrefix:" where somePrefix is a syntactically + * valid namespace prefix + */ if (':' === $nameHint[strlen($nameHint)-1] && substr_count($nameHint, ':') === 1 && preg_match('#^[a-zA-Z][a-zA-Z0-9]*:$#', $nameHint) diff --git a/src/PHPCR/Util/PathHelper.php b/src/PHPCR/Util/PathHelper.php index c82d9b1..d922b4a 100644 --- a/src/PHPCR/Util/PathHelper.php +++ b/src/PHPCR/Util/PathHelper.php @@ -58,7 +58,7 @@ public static function assertValidAbsolutePath($path, $destination = false, $thr return self::error("Destination path may not end with index: '$path'", $throw); } if ($namespacePrefixes) { - $matches = array(); + $matches = []; preg_match_all('#/(?P[^/:]+):#', $path, $matches); $unknown = array_diff(array_unique($matches['prefixes']), $namespacePrefixes); if (count($unknown)) { @@ -144,7 +144,7 @@ public static function normalizePath($path, $destination = false, $throw = true) return self::error("Not an absolute path '$path'", $throw); } - $finalParts= array(); + $finalParts= []; $parts = explode('/', $path); foreach ($parts as $pathPart) { diff --git a/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php b/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php index 67e7bca..09fef6d 100644 --- a/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php +++ b/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php @@ -237,7 +237,7 @@ protected function convertPropertyValue(QOM\PropertyValueInterface $value) */ protected function convertOrderings(array $orderings) { - $list = array(); + $list = []; /** @var $ordering QOM\OrderingInterface */ foreach ($orderings as $ordering) { $order = $this->generator->evalOrder($ordering->getOrder()); diff --git a/src/PHPCR/Util/QOM/QueryBuilder.php b/src/PHPCR/Util/QOM/QueryBuilder.php index 5626ca4..7597190 100644 --- a/src/PHPCR/Util/QOM/QueryBuilder.php +++ b/src/PHPCR/Util/QOM/QueryBuilder.php @@ -243,7 +243,7 @@ public function addOrderBy(DynamicOperandInterface $sort, $order = 'ASC') */ public function orderBy(DynamicOperandInterface $sort, $order = 'ASC') { - $this->orderings = array(); + $this->orderings = []; $this->addOrderBy($sort, $order); return $this; diff --git a/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php b/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php index f08ecf9..80eccd0 100644 --- a/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php +++ b/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php @@ -99,9 +99,9 @@ public function parse($sql2) $this->sql2 = $sql2; $this->scanner = new Sql2Scanner($sql2); $source = null; - $columnData = array(); + $columnData = []; $constraint = null; - $orderings = array(); + $orderings = []; while ($this->scanner->lookupNextToken() !== '') { switch (strtoupper($this->scanner->lookupNextToken())) { @@ -119,7 +119,7 @@ public function parse($sql2) break; case 'ORDER': // Ordering, check there is a BY - $this->scanner->expectTokens(array('ORDER', 'BY')); + $this->scanner->expectTokens(['ORDER', 'BY']); $orderings = $this->parseOrderings(); break; default: @@ -229,11 +229,11 @@ protected function parseJoinType() $this->scanner->fetchNextToken(); break; case 'LEFT': - $this->scanner->expectTokens(array('OUTER', 'JOIN')); + $this->scanner->expectTokens(['OUTER', 'JOIN']); $joinType = Constants::JCR_JOIN_TYPE_LEFT_OUTER; break; case 'RIGHT': - $this->scanner->expectTokens(array('OUTER', 'JOIN')); + $this->scanner->expectTokens(['OUTER', 'JOIN']); $joinType = Constants::JCR_JOIN_TYPE_RIGHT_OUTER; break; default: @@ -292,7 +292,7 @@ protected function parseEquiJoin() */ protected function parseSameNodeJoinCondition() { - $this->scanner->expectTokens(array('ISSAMENODE', '(')); + $this->scanner->expectTokens(['ISSAMENODE', '(']); $selectorName1 = $this->fetchTokenWithoutBrackets(); $this->scanner->expectToken(','); $selectorName2 = $this->fetchTokenWithoutBrackets(); @@ -335,7 +335,7 @@ protected function parseChildNodeJoinCondition() */ protected function parseDescendantNodeJoinCondition() { - $this->scanner->expectTokens(array('ISDESCENDANTNODE', '(')); + $this->scanner->expectTokens(['ISDESCENDANTNODE', '(']); $descendant = $this->fetchTokenWithoutBrackets(); $this->scanner->expectToken(','); $parent = $this->fetchTokenWithoutBrackets(); @@ -361,10 +361,10 @@ protected function parseConstraint($lhs = null, $minprec = 0) $lhs = $this->parsePrimaryConstraint(); } - $opprec = array( + $opprec = [ 'OR' => 1, 'AND' => 2, - ); + ]; $op = strtoupper($this->scanner->lookupNextToken()); while (isset($opprec[$op]) && $opprec[$op] >= $minprec) { @@ -994,7 +994,7 @@ private function parseIdentifier($checkSelector = true) $selectorName = $this->ensureSelectorName($selectorName); } - return array($selectorName, $propertyName); + return [$selectorName, $propertyName]; } /** @@ -1010,7 +1010,7 @@ protected function updateImplicitSelectorName($selectorName) $this->implicitSelectorName = $selectorName; } else { if (!is_array($this->implicitSelectorName)) { - $this->implicitSelectorName = array($this->implicitSelectorName => $this->implicitSelectorName); + $this->implicitSelectorName = [$this->implicitSelectorName => $this->implicitSelectorName]; } if (isset($this->implicitSelectorName[$selectorName])) { throw new InvalidQueryException("Selector $selectorName is already in use"); @@ -1065,7 +1065,7 @@ protected function scanColumn() $columnName = $propertyName; } - return array($selectorName, $propertyName, $columnName); + return [$selectorName, $propertyName, $columnName]; } /** diff --git a/src/PHPCR/Util/ValueConverter.php b/src/PHPCR/Util/ValueConverter.php index 155d068..c39d16d 100644 --- a/src/PHPCR/Util/ValueConverter.php +++ b/src/PHPCR/Util/ValueConverter.php @@ -119,7 +119,7 @@ public function determineType($value, $weak = false) public function convertType($value, $type, $srcType = PropertyType::UNDEFINED) { if (is_array($value)) { - $ret = array(); + $ret = []; foreach ($value as $v) { $ret[] = self::convertType($v, $type, $srcType); } diff --git a/tests/PHPCR/Tests/Util/CND/Scanner/TokenQueueTest.php b/tests/PHPCR/Tests/Util/CND/Scanner/TokenQueueTest.php index 30501f7..db91a14 100644 --- a/tests/PHPCR/Tests/Util/CND/Scanner/TokenQueueTest.php +++ b/tests/PHPCR/Tests/Util/CND/Scanner/TokenQueueTest.php @@ -108,7 +108,7 @@ public function testGet() public function testGetIterator() { $this->assertEquals( - array($this->token0, $this->token1, $this->token2, $this->token3), + [$this->token0, $this->token1, $this->token2, $this->token3], iterator_to_array($this->queue->getIterator()) ); } diff --git a/tests/PHPCR/Tests/Util/Console/Command/NodeDumpCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodeDumpCommandTest.php index 84727e3..46cfc57 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodeDumpCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodeDumpCommandTest.php @@ -46,7 +46,7 @@ public function testCommand() ->with($this->node1) ; - $this->executeCommand('phpcr:node:dump', array()); + $this->executeCommand('phpcr:node:dump', []); } public function testCommandIdentifier() diff --git a/tests/PHPCR/Tests/Util/Console/Command/NodeRemoveCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodeRemoveCommandTest.php index ac5e100..822fe4a 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodeRemoveCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodeRemoveCommandTest.php @@ -20,19 +20,19 @@ public function testRemove() ->method('removeItem') ->with('/cms'); - $this->executeCommand('phpcr:node:remove', array( + $this->executeCommand('phpcr:node:remove', [ '--force' => true, 'path' => '/cms', - )); + ]); } public function testRemoveRoot() { $this->expectException(LogicException::class); - $this->executeCommand('phpcr:node:remove', array( + $this->executeCommand('phpcr:node:remove', [ '--force' => true, 'path' => '/', - )); + ]); } } diff --git a/tests/PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php index db97551..b07b67e 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php @@ -140,16 +140,16 @@ public function testNodeUpdate($options) public function testApplyClosure() { - $args = array( + $args = [ '--query' => "SELECT foo FROM bar", '--no-interaction' => true, - '--apply-closure' => array( + '--apply-closure' => [ '$session->getNodeByIdentifier("/foo"); $node->setProperty("foo", "bar");', function ($session, $node) { $node->setProperty('foo', 'bar'); } - ), - ); + ], + ]; $this->setupQueryManager(['query' => 'SELECT foo FROM bar']); diff --git a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceDeleteCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceDeleteCommandTest.php index 5b1f16e..d17c40e 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceDeleteCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceDeleteCommandTest.php @@ -42,10 +42,10 @@ public function testDelete() ->with('test_workspace') ; - $ct = $this->executeCommand('phpcr:workspace:delete', array( + $ct = $this->executeCommand('phpcr:workspace:delete', [ 'name' => 'test_workspace', '--force' => 'true', - )); + ]); $this->assertContains("Deleted workspace 'test_workspace'.", $ct->getDisplay()); } diff --git a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceListCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceListCommandTest.php index ecbc36d..36c6c00 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceListCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceListCommandTest.php @@ -25,8 +25,8 @@ public function testNodeTypeList() 'foo', 'bar' ])); - $ct = $this->executeCommand('phpcr:workspace:list', array( - )); + $ct = $this->executeCommand('phpcr:workspace:list', [ + ]); $expected = <<qf->expects($this->once()) ->method('createQuery') - ->with($source, $constraint, array(), array()) + ->with($source, $constraint, [], []) ->will($this->returnValue($query)); $qb = new QueryBuilder($this->qf); diff --git a/tests/PHPCR/Tests/Util/QOM/Sql2GeneratorTest.php b/tests/PHPCR/Tests/Util/QOM/Sql2GeneratorTest.php index 7ea45fd..bf3d0f0 100644 --- a/tests/PHPCR/Tests/Util/QOM/Sql2GeneratorTest.php +++ b/tests/PHPCR/Tests/Util/QOM/Sql2GeneratorTest.php @@ -78,7 +78,7 @@ public function testColumns() { $literal = $this->generator->evalColumns(null); $this->assertSame('*', $literal); - $literal = $this->generator->evalColumns(array('bar', 'foo')); + $literal = $this->generator->evalColumns(['bar', 'foo']); $this->assertSame('bar, foo', $literal); } From 411e31c48cc98f50aeca621ed2fc95bfae663890 Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Wed, 27 Sep 2017 09:33:19 +0200 Subject: [PATCH 13/88] build with php 7.2 --- .travis.yml | 1 + composer.json | 2 +- src/PHPCR/Util/Console/Helper/PhpcrHelper.php | 4 +++- src/PHPCR/Util/QOM/Sql1Generator.php | 4 +++- src/PHPCR/Util/QOM/Sql2Generator.php | 4 +++- 5 files changed, 11 insertions(+), 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index b813824..c465361 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,6 +4,7 @@ php: - 5.6 - 7.0 - 7.1 + - 7.2 env: - PACKAGE_VERSION=high diff --git a/composer.json b/composer.json index 71e3cd6..541e5d4 100644 --- a/composer.json +++ b/composer.json @@ -27,7 +27,7 @@ } ], "require": { - "php": "^5.6|7.0.x|7.1.x", + "php": "^5.6|^7.0", "phpcr/phpcr": "~2.1.0", "symfony/console": "~2.3|~3.0" }, diff --git a/src/PHPCR/Util/Console/Helper/PhpcrHelper.php b/src/PHPCR/Util/Console/Helper/PhpcrHelper.php index d0aea35..719d0e9 100644 --- a/src/PHPCR/Util/Console/Helper/PhpcrHelper.php +++ b/src/PHPCR/Util/Console/Helper/PhpcrHelper.php @@ -115,7 +115,9 @@ public function processNode(OutputInterface $output, NodeInterface $node, array ); } else { $closureString = $closure; - $closure = create_function('$session, $node', $closure); + $closure = function (SessionInterface $session, NodeInterface $node) use ($closureString) { + eval($closureString); + }; $output->writeln(sprintf( ' > Applying closure: %s', strlen($closureString) > 75 ? substr($closureString, 0, 72).'...' : $closureString diff --git a/src/PHPCR/Util/QOM/Sql1Generator.php b/src/PHPCR/Util/QOM/Sql1Generator.php index 2f9d6c4..1f1bfc3 100644 --- a/src/PHPCR/Util/QOM/Sql1Generator.php +++ b/src/PHPCR/Util/QOM/Sql1Generator.php @@ -120,7 +120,9 @@ public function evalFullTextSearch($selectorName, $searchExpression, $propertyNa */ public function evalColumns($columns) { - if (count($columns) === 0) { + if ((!is_array($columns) && !$columns instanceof \Countable) + || count($columns) === 0 + ) { return 's'; } diff --git a/src/PHPCR/Util/QOM/Sql2Generator.php b/src/PHPCR/Util/QOM/Sql2Generator.php index 21f29eb..95e2146 100644 --- a/src/PHPCR/Util/QOM/Sql2Generator.php +++ b/src/PHPCR/Util/QOM/Sql2Generator.php @@ -325,7 +325,9 @@ public function evalPropertyValue($propertyName, $selectorName = null) */ public function evalColumns($columns) { - if (count($columns) === 0) { + if ((!is_array($columns) && !$columns instanceof \Countable) + || count($columns) === 0 + ) { return '*'; } From 0db19c7adeb3a2890f147f71d3e6bf56a309c9c9 Mon Sep 17 00:00:00 2001 From: Gabriel Caruso Date: Tue, 7 Nov 2017 00:04:48 -0200 Subject: [PATCH 14/88] Use PSR-1 for PHPUnit TestCase --- tests/PHPCR/Tests/Util/CND/Reader/BufferReaderTest.php | 4 ++-- tests/PHPCR/Tests/Util/CND/Reader/FileReaderTest.php | 4 ++-- tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php | 4 ++-- tests/PHPCR/Tests/Util/CND/Scanner/TokenQueueTest.php | 4 ++-- tests/PHPCR/Tests/Util/CND/Scanner/TokenTest.php | 4 ++-- tests/PHPCR/Tests/Util/Console/Command/BaseCommandTest.php | 4 ++-- .../Util/Console/Helper/PhpcrConsoleDumperHelperTest.php | 3 ++- tests/PHPCR/Tests/Util/NodeHelperTest.php | 4 ++-- tests/PHPCR/Tests/Util/PathHelperTest.php | 3 ++- tests/PHPCR/Tests/Util/QOM/BaseSqlGeneratorTest.php | 4 ++-- tests/PHPCR/Tests/Util/QOM/QueryBuilderTest.php | 4 ++-- tests/PHPCR/Tests/Util/QOM/Sql1GeneratorTest.php | 4 ++-- tests/PHPCR/Tests/Util/QOM/Sql2ToQomQueryConverterTest.php | 4 ++-- tests/PHPCR/Tests/Util/TraversingItemVisitorTest.php | 4 ++-- tests/PHPCR/Tests/Util/UUIDHelperTest.php | 4 ++-- tests/PHPCR/Tests/Util/ValueConverterTest.php | 4 ++-- 16 files changed, 32 insertions(+), 30 deletions(-) diff --git a/tests/PHPCR/Tests/Util/CND/Reader/BufferReaderTest.php b/tests/PHPCR/Tests/Util/CND/Reader/BufferReaderTest.php index 442019b..af07214 100644 --- a/tests/PHPCR/Tests/Util/CND/Reader/BufferReaderTest.php +++ b/tests/PHPCR/Tests/Util/CND/Reader/BufferReaderTest.php @@ -3,9 +3,9 @@ namespace PHPCR\Tests\Util\CND\Reader; use PHPCR\Util\CND\Reader\BufferReader; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; -class BufferReaderTest extends PHPUnit_Framework_TestCase +class BufferReaderTest extends TestCase { public function test__construct() { diff --git a/tests/PHPCR/Tests/Util/CND/Reader/FileReaderTest.php b/tests/PHPCR/Tests/Util/CND/Reader/FileReaderTest.php index c6926d7..c65e6a9 100644 --- a/tests/PHPCR/Tests/Util/CND/Reader/FileReaderTest.php +++ b/tests/PHPCR/Tests/Util/CND/Reader/FileReaderTest.php @@ -4,9 +4,9 @@ use InvalidArgumentException; use PHPCR\Util\CND\Reader\FileReader; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; -class FileReaderTest extends PHPUnit_Framework_TestCase +class FileReaderTest extends TestCase { /** * @var string diff --git a/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php b/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php index 9c21956..1479cf5 100644 --- a/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php +++ b/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php @@ -9,11 +9,11 @@ use PHPCR\Util\CND\Scanner\TokenQueue; use PHPCR\Util\CND\Scanner\TokenFilter; use PHPCR\Util\CND\Scanner\Context\DefaultScannerContext; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; use Test; use TestClass; -class GenericScannerTest extends PHPUnit_Framework_TestCase +class GenericScannerTest extends TestCase { protected $expectedTokens = [ diff --git a/tests/PHPCR/Tests/Util/CND/Scanner/TokenQueueTest.php b/tests/PHPCR/Tests/Util/CND/Scanner/TokenQueueTest.php index db91a14..d2831e1 100644 --- a/tests/PHPCR/Tests/Util/CND/Scanner/TokenQueueTest.php +++ b/tests/PHPCR/Tests/Util/CND/Scanner/TokenQueueTest.php @@ -4,9 +4,9 @@ use PHPCR\Util\CND\Scanner\Token; use PHPCR\Util\CND\Scanner\TokenQueue; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; -class TokenQueueTest extends PHPUnit_Framework_TestCase +class TokenQueueTest extends TestCase { /** * @var Token diff --git a/tests/PHPCR/Tests/Util/CND/Scanner/TokenTest.php b/tests/PHPCR/Tests/Util/CND/Scanner/TokenTest.php index 442b3df..718b5ce 100644 --- a/tests/PHPCR/Tests/Util/CND/Scanner/TokenTest.php +++ b/tests/PHPCR/Tests/Util/CND/Scanner/TokenTest.php @@ -3,9 +3,9 @@ namespace PHPCR\Tests\Util\CND\Scanner; use PHPCR\Util\CND\Scanner\Token; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; -class TokenTest extends PHPUnit_Framework_TestCase +class TokenTest extends TestCase { /** * @var Token diff --git a/tests/PHPCR/Tests/Util/Console/Command/BaseCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/BaseCommandTest.php index ce50cdc..21abea3 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/BaseCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/BaseCommandTest.php @@ -9,7 +9,7 @@ use PHPCR\Tests\Stubs\MockNode; use PHPCR\Tests\Stubs\MockRow; use PHPUnit_Framework_MockObject_MockObject; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; use Symfony\Component\Console\Application; use Symfony\Component\Console\Tester\CommandTester; use Symfony\Component\Console\Helper\HelperSet; @@ -22,7 +22,7 @@ require_once __DIR__.'/../../../Stubs/MockNodeTypeManager.php'; require_once __DIR__.'/../../../Stubs/MockRow.php'; -abstract class BaseCommandTest extends PHPUnit_Framework_TestCase +abstract class BaseCommandTest extends TestCase { /** * @var SessionInterface|PHPUnit_Framework_MockObject_MockObject diff --git a/tests/PHPCR/Tests/Util/Console/Helper/PhpcrConsoleDumperHelperTest.php b/tests/PHPCR/Tests/Util/Console/Helper/PhpcrConsoleDumperHelperTest.php index 8ec131b..ed62d20 100644 --- a/tests/PHPCR/Tests/Util/Console/Helper/PhpcrConsoleDumperHelperTest.php +++ b/tests/PHPCR/Tests/Util/Console/Helper/PhpcrConsoleDumperHelperTest.php @@ -4,8 +4,9 @@ use PHPCR\Util\Console\Helper\TreeDumper\ConsoleDumperPropertyVisitor; use PHPCR\Util\TreeWalker; use Symfony\Component\Console\Output\OutputInterface; +use PHPUnit\Framework\TestCase; -class PhpcrConsoleDumperHelperTest extends PHPUnit_Framework_TestCase +class PhpcrConsoleDumperHelperTest extends TestCase { private $outputMock; /** diff --git a/tests/PHPCR/Tests/Util/NodeHelperTest.php b/tests/PHPCR/Tests/Util/NodeHelperTest.php index 7c0612d..64223d5 100644 --- a/tests/PHPCR/Tests/Util/NodeHelperTest.php +++ b/tests/PHPCR/Tests/Util/NodeHelperTest.php @@ -5,11 +5,11 @@ use PHPCR\Tests\Stubs\MockNode; use PHPCR\Util\NodeHelper; use PHPUnit_Framework_MockObject_MockObject; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; require_once __DIR__.'/../Stubs/MockNode.php'; -class NodeHelperTest extends PHPUnit_Framework_TestCase +class NodeHelperTest extends TestCase { /** * @var array diff --git a/tests/PHPCR/Tests/Util/PathHelperTest.php b/tests/PHPCR/Tests/Util/PathHelperTest.php index 8f086e4..78f6239 100644 --- a/tests/PHPCR/Tests/Util/PathHelperTest.php +++ b/tests/PHPCR/Tests/Util/PathHelperTest.php @@ -6,8 +6,9 @@ use PHPCR\RepositoryException; use PHPCR\Util\PathHelper; use stdClass; +use PHPUnit\Framework\TestCase; -class PathHelperTest extends \PHPUnit_Framework_TestCase +class PathHelperTest extends TestCase { // assertValidPath tests diff --git a/tests/PHPCR/Tests/Util/QOM/BaseSqlGeneratorTest.php b/tests/PHPCR/Tests/Util/QOM/BaseSqlGeneratorTest.php index 6c20bd3..e5ed115 100644 --- a/tests/PHPCR/Tests/Util/QOM/BaseSqlGeneratorTest.php +++ b/tests/PHPCR/Tests/Util/QOM/BaseSqlGeneratorTest.php @@ -2,9 +2,9 @@ namespace PHPCR\Tests\Util\QOM; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; -abstract class BaseSqlGeneratorTest extends PHPUnit_Framework_TestCase +abstract class BaseSqlGeneratorTest extends TestCase { public function testNot() { diff --git a/tests/PHPCR/Tests/Util/QOM/QueryBuilderTest.php b/tests/PHPCR/Tests/Util/QOM/QueryBuilderTest.php index 9001d26..a99fa92 100644 --- a/tests/PHPCR/Tests/Util/QOM/QueryBuilderTest.php +++ b/tests/PHPCR/Tests/Util/QOM/QueryBuilderTest.php @@ -12,10 +12,10 @@ use PHPCR\Query\QOM\SourceInterface; use PHPCR\Util\QOM\QueryBuilder; use PHPUnit_Framework_MockObject_MockObject; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; use RuntimeException; -class QueryBuilderTest extends PHPUnit_Framework_TestCase +class QueryBuilderTest extends TestCase { /** * @var PHPUnit_Framework_MockObject_MockObject|QueryObjectModelFactoryInterface diff --git a/tests/PHPCR/Tests/Util/QOM/Sql1GeneratorTest.php b/tests/PHPCR/Tests/Util/QOM/Sql1GeneratorTest.php index 4955379..4909138 100644 --- a/tests/PHPCR/Tests/Util/QOM/Sql1GeneratorTest.php +++ b/tests/PHPCR/Tests/Util/QOM/Sql1GeneratorTest.php @@ -5,9 +5,9 @@ use DateTime; use PHPCR\Util\QOM\Sql1Generator; use PHPCR\Util\ValueConverter; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; -class Sql1GeneratorTest extends PHPUnit_Framework_TestCase +class Sql1GeneratorTest extends TestCase { /** * @var Sql1Generator diff --git a/tests/PHPCR/Tests/Util/QOM/Sql2ToQomQueryConverterTest.php b/tests/PHPCR/Tests/Util/QOM/Sql2ToQomQueryConverterTest.php index 6649f1e..79a8863 100644 --- a/tests/PHPCR/Tests/Util/QOM/Sql2ToQomQueryConverterTest.php +++ b/tests/PHPCR/Tests/Util/QOM/Sql2ToQomQueryConverterTest.php @@ -6,9 +6,9 @@ use PHPCR\Query\QOM\QueryObjectModelFactoryInterface; use PHPCR\Util\QOM\Sql2ToQomQueryConverter; use PHPCR\Util\ValueConverter; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; -class Sql2ToQomQueryConverterTest extends PHPUnit_Framework_TestCase +class Sql2ToQomQueryConverterTest extends TestCase { /** * @var QueryObjectModelFactoryInterface diff --git a/tests/PHPCR/Tests/Util/TraversingItemVisitorTest.php b/tests/PHPCR/Tests/Util/TraversingItemVisitorTest.php index 88c85f9..e233026 100644 --- a/tests/PHPCR/Tests/Util/TraversingItemVisitorTest.php +++ b/tests/PHPCR/Tests/Util/TraversingItemVisitorTest.php @@ -2,9 +2,9 @@ namespace PHPCR\Tests\Util; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; -class TraversingItemVisitorTest extends PHPUnit_Framework_TestCase +class TraversingItemVisitorTest extends TestCase { public function testVisitor() { diff --git a/tests/PHPCR/Tests/Util/UUIDHelperTest.php b/tests/PHPCR/Tests/Util/UUIDHelperTest.php index 3945a34..3e20505 100644 --- a/tests/PHPCR/Tests/Util/UUIDHelperTest.php +++ b/tests/PHPCR/Tests/Util/UUIDHelperTest.php @@ -3,9 +3,9 @@ namespace PHPCR\Tests\Util; use PHPCR\Util\UUIDHelper; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; -class UUIDHelperTest extends PHPUnit_Framework_TestCase +class UUIDHelperTest extends TestCase { public function testGenerateUUID() { diff --git a/tests/PHPCR/Tests/Util/ValueConverterTest.php b/tests/PHPCR/Tests/Util/ValueConverterTest.php index d4177aa..02474b1 100644 --- a/tests/PHPCR/Tests/Util/ValueConverterTest.php +++ b/tests/PHPCR/Tests/Util/ValueConverterTest.php @@ -7,14 +7,14 @@ use PHPCR\Tests\Stubs\MockNode; use PHPCR\Util\ValueConverter; use PHPCR\ValueFormatException; -use PHPUnit_Framework_TestCase; +use PHPUnit\Framework\TestCase; require_once __DIR__.'/../Stubs/MockNode.php'; /** * A test for the PHPCR\PropertyType class */ -class ValueConverterTest extends PHPUnit_Framework_TestCase +class ValueConverterTest extends TestCase { /** * @var ValueConverter From a62ea4eb8be4a585068b56b539879416b81b99f0 Mon Sep 17 00:00:00 2001 From: ElectricMaxxx Date: Sat, 18 Nov 2017 15:23:36 +0100 Subject: [PATCH 15/88] =?UTF-8?q?allow=20symfony=204.0,=20drop=20older=20p?= =?UTF-8?q?hp=20versions=C3=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .travis.yml | 4 +--- composer.json | 4 ++-- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/.travis.yml b/.travis.yml index c465361..cae9d57 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,8 +1,6 @@ language: php php: - - 5.6 - - 7.0 - 7.1 - 7.2 @@ -13,7 +11,7 @@ sudo: false matrix: include: - - php: 5.6 + - php: 7.1 env: PACKAGE_VERSION=low - php: hhvm dist: trusty diff --git a/composer.json b/composer.json index 541e5d4..6299473 100644 --- a/composer.json +++ b/composer.json @@ -27,9 +27,9 @@ } ], "require": { - "php": "^5.6|^7.0", + "php": "^7.1", "phpcr/phpcr": "~2.1.0", - "symfony/console": "~2.3|~3.0" + "symfony/console": "~2.3|~3.0|^4.0" }, "require-dev": { "ramsey/uuid": "^3.5", From 947d89313c4d427b3cc5160022afe74a08772b40 Mon Sep 17 00:00:00 2001 From: ElectricMaxxx Date: Sat, 18 Nov 2017 15:30:55 +0100 Subject: [PATCH 16/88] revert php version changes, remove hhvm only --- .travis.yml | 6 +++--- CHANGELOG.md | 2 ++ composer.json | 2 +- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index cae9d57..129c8f7 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,8 @@ language: php php: + - 5.6 + - 7.0 - 7.1 - 7.2 @@ -11,10 +13,8 @@ sudo: false matrix: include: - - php: 7.1 + - php: 5.6 env: PACKAGE_VERSION=low - - php: hhvm - dist: trusty before_script: - composer selfupdate diff --git a/CHANGELOG.md b/CHANGELOG.md index aca20b8..17c9b17 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,8 @@ Changelog ========= +* **2017-11-18**: Removed hhvm test + 1.2.7 ----- diff --git a/composer.json b/composer.json index 6299473..60fdb35 100644 --- a/composer.json +++ b/composer.json @@ -27,7 +27,7 @@ } ], "require": { - "php": "^7.1", + "php": "^5.6|^7.0", "phpcr/phpcr": "~2.1.0", "symfony/console": "~2.3|~3.0|^4.0" }, From 60f0fe9659bd1a1b590adb99061938472c27cade Mon Sep 17 00:00:00 2001 From: Gabriel Caruso Date: Mon, 11 Dec 2017 03:14:39 -0200 Subject: [PATCH 17/88] Use assertNotContains --- tests/PHPCR/Tests/Util/NodeHelperTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/PHPCR/Tests/Util/NodeHelperTest.php b/tests/PHPCR/Tests/Util/NodeHelperTest.php index 64223d5..634d153 100644 --- a/tests/PHPCR/Tests/Util/NodeHelperTest.php +++ b/tests/PHPCR/Tests/Util/NodeHelperTest.php @@ -67,7 +67,7 @@ public function testGenerateAutoNodeName($hint, $expect) { $result = NodeHelper::generateAutoNodeName($this->usedNames, $this->namespaces, 'a', $hint); if (true === $expect) { - $this->assertFalse(strpos($result, ':')); + $this->assertNotContains(':', $result); } else { $this->assertEquals($expect, substr($result, 0, strlen($expect))); } From e425ee10e99eb512b22628c4e84f7d934abe752f Mon Sep 17 00:00:00 2001 From: Gabriel Caruso Date: Thu, 14 Dec 2017 06:19:02 -0200 Subject: [PATCH 18/88] Clean else --- src/PHPCR/Util/CND/Scanner/GenericScanner.php | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/PHPCR/Util/CND/Scanner/GenericScanner.php b/src/PHPCR/Util/CND/Scanner/GenericScanner.php index 4541d47..77d8317 100644 --- a/src/PHPCR/Util/CND/Scanner/GenericScanner.php +++ b/src/PHPCR/Util/CND/Scanner/GenericScanner.php @@ -235,13 +235,12 @@ protected function consumeLineComments(ReaderInterface $reader) $this->addToken($reader, $token); return true; - } else { + } - // Rewind the looked up characters - $reader->rewind(); + // Rewind the looked up characters + $reader->rewind(); - return false; - } + return false; } } From 547ef501c1cae4a0bdb3d2f15faf4f9a38d037e3 Mon Sep 17 00:00:00 2001 From: Gabriel Caruso Date: Thu, 14 Dec 2017 19:53:00 -0200 Subject: [PATCH 19/88] Enable "no_useless_else" in StyleCI --- .styleci.yml | 3 ++- src/PHPCR/Util/CND/Scanner/GenericScanner.php | 9 ++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.styleci.yml b/.styleci.yml index 0f86e26..b612217 100644 --- a/.styleci.yml +++ b/.styleci.yml @@ -2,4 +2,5 @@ preset: psr2 enabled: - short_array_syntax - - duplicate_semicolon \ No newline at end of file + - duplicate_semicolon + - no_useless_else diff --git a/src/PHPCR/Util/CND/Scanner/GenericScanner.php b/src/PHPCR/Util/CND/Scanner/GenericScanner.php index 77d8317..9dd8367 100644 --- a/src/PHPCR/Util/CND/Scanner/GenericScanner.php +++ b/src/PHPCR/Util/CND/Scanner/GenericScanner.php @@ -195,13 +195,12 @@ protected function consumeBlockComments(ReaderInterface $reader) // End of file reached and no end delimiter found, error throw new ScannerException($reader, "Unterminated block comment"); - } else { + } - // Start delimiter not found, rewind the looked up characters - $reader->rewind(); + // Start delimiter not found, rewind the looked up characters + $reader->rewind(); - return false; - } + return false; } } From 481851e95a4a7e61ca3cee435ec0e418f016cce7 Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Mon, 18 Dec 2017 09:45:25 +0100 Subject: [PATCH 20/88] use recommended setting for styleci --- .styleci.yml | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/.styleci.yml b/.styleci.yml index b612217..989801f 100644 --- a/.styleci.yml +++ b/.styleci.yml @@ -1,6 +1,4 @@ -preset: psr2 +preset: recommended enabled: - - short_array_syntax - - duplicate_semicolon - no_useless_else From 70d74703f03c9fd85c21556b0b0152e8960efe74 Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Mon, 18 Dec 2017 09:15:55 +0000 Subject: [PATCH 21/88] Apply fixes from StyleCI --- .../Util/CND/Exception/ParserException.php | 6 +- .../Util/CND/Exception/ScannerException.php | 1 - src/PHPCR/Util/CND/Parser/AbstractParser.php | 17 ++- src/PHPCR/Util/CND/Parser/CndParser.php | 41 +++--- src/PHPCR/Util/CND/Reader/BufferReader.php | 10 +- src/PHPCR/Util/CND/Reader/FileReader.php | 1 - src/PHPCR/Util/CND/Reader/ReaderInterface.php | 12 +- .../Util/CND/Scanner/AbstractScanner.php | 1 - .../Scanner/Context/DefaultScannerContext.php | 3 +- ...ScannerContextWithoutSpacesAndComments.php | 1 - .../CND/Scanner/Context/ScannerContext.php | 8 +- src/PHPCR/Util/CND/Scanner/GenericScanner.php | 49 ++++--- src/PHPCR/Util/CND/Scanner/GenericToken.php | 1 - src/PHPCR/Util/CND/Scanner/Token.php | 11 +- .../Scanner/TokenFilter/NoCommentsFilter.php | 1 - .../Scanner/TokenFilter/NoNewlinesFilter.php | 1 - .../TokenFilter/NoWhitespacesFilter.php | 1 - .../Scanner/TokenFilter/TokenFilterChain.php | 6 +- .../TokenFilter/TokenFilterInterface.php | 5 +- .../Scanner/TokenFilter/TokenTypeFilter.php | 9 +- src/PHPCR/Util/CND/Scanner/TokenQueue.php | 1 - src/PHPCR/Util/CND/Writer/CndWriter.php | 45 +++--- .../Util/Console/Command/BaseCommand.php | 8 +- .../Util/Console/Command/NodeDumpCommand.php | 20 ++- .../Util/Console/Command/NodeMoveCommand.php | 12 +- .../Console/Command/NodeRemoveCommand.php | 12 +- .../Util/Console/Command/NodeTouchCommand.php | 21 ++- .../Console/Command/NodeTypeListCommand.php | 13 +- .../Command/NodeTypeRegisterCommand.php | 22 +-- .../Console/Command/NodesUpdateCommand.php | 17 ++- .../Command/WorkspaceCreateCommand.php | 14 +- .../Command/WorkspaceDeleteCommand.php | 14 +- .../Command/WorkspaceExportCommand.php | 16 +-- .../Command/WorkspaceImportCommand.php | 14 +- .../Console/Command/WorkspaceListCommand.php | 14 +- .../Console/Command/WorkspacePurgeCommand.php | 14 +- .../Console/Command/WorkspaceQueryCommand.php | 11 +- .../Helper/PhpcrConsoleDumperHelper.php | 15 +- src/PHPCR/Util/Console/Helper/PhpcrHelper.php | 23 ++- .../TreeDumper/ConsoleDumperItemVisitor.php | 12 +- .../TreeDumper/ConsoleDumperNodeVisitor.php | 16 +-- .../ConsoleDumperPropertyVisitor.php | 24 ++-- .../Helper/TreeDumper/SystemNodeFilter.php | 10 +- src/PHPCR/Util/NodeHelper.php | 74 +++++----- src/PHPCR/Util/PathHelper.php | 95 ++++++------ .../Util/QOM/BaseQomToSqlQueryConverter.php | 63 ++++---- src/PHPCR/Util/QOM/BaseSqlGenerator.php | 35 +++-- .../QOM/NotSupportedConstraintException.php | 2 +- .../Util/QOM/NotSupportedOperandException.php | 2 +- .../Util/QOM/QomToSql1QueryConverter.php | 24 ++-- .../Util/QOM/QomToSql2QueryConverter.php | 57 ++++---- src/PHPCR/Util/QOM/QueryBuilder.php | 76 +++++----- src/PHPCR/Util/QOM/Sql1Generator.php | 59 ++++---- src/PHPCR/Util/QOM/Sql2Generator.php | 136 +++++++++--------- src/PHPCR/Util/QOM/Sql2Scanner.php | 39 ++--- .../Util/QOM/Sql2ToQomQueryConverter.php | 107 +++++++------- src/PHPCR/Util/TraversingItemVisitor.php | 58 ++++---- src/PHPCR/Util/TreeWalker.php | 31 ++-- src/PHPCR/Util/TreeWalkerFilterInterface.php | 3 +- src/PHPCR/Util/ValueConverter.php | 110 +++++++------- .../Util/CND/Fixtures/files/TestFile.php | 4 +- .../Util/CND/Reader/BufferReaderTest.php | 2 +- .../Tests/Util/CND/Reader/FileReaderTest.php | 4 +- .../Util/CND/Scanner/GenericScannerTest.php | 12 +- .../Util/Console/Command/BaseCommandTest.php | 29 ++-- .../Console/Command/NodeDumpCommandTest.php | 28 ++-- .../Console/Command/NodeMoveCommandTest.php | 6 +- .../Console/Command/NodeRemoveCommandTest.php | 4 +- .../Console/Command/NodeTouchCommandTest.php | 48 +++---- .../Command/NodeTypeListCommandTest.php | 12 +- .../Command/NodeTypeRegisterCommandTest.php | 9 +- .../Command/NodesUpdateCommandTest.php | 55 ++++--- .../Command/WorkspaceCreateCommandTest.php | 35 ++--- .../Command/WorkspaceDeleteCommandTest.php | 27 ++-- .../Command/WorkspaceExportCommandTest.php | 4 +- .../Command/WorkspaceImportCommandTest.php | 4 +- .../Command/WorkspaceListCommandTest.php | 4 +- .../Helper/PhpcrConsoleDumperHelperTest.php | 10 +- tests/PHPCR/Tests/Util/NodeHelperTest.php | 26 ++-- tests/PHPCR/Tests/Util/PathHelperTest.php | 4 +- .../PHPCR/Tests/Util/QOM/QueryBuilderTest.php | 20 +-- .../Tests/Util/QOM/Sql1GeneratorTest.php | 4 +- tests/PHPCR/Tests/Util/ValueConverterTest.php | 26 ++-- tests/bootstrap.php | 3 +- 84 files changed, 908 insertions(+), 996 deletions(-) diff --git a/src/PHPCR/Util/CND/Exception/ParserException.php b/src/PHPCR/Util/CND/Exception/ParserException.php index 85707d6..a08d67e 100644 --- a/src/PHPCR/Util/CND/Exception/ParserException.php +++ b/src/PHPCR/Util/CND/Exception/ParserException.php @@ -2,15 +2,13 @@ namespace PHPCR\Util\CND\Exception; -use PHPCR\Util\CND\Scanner\TokenQueue; use PHPCR\Util\CND\Scanner\GenericToken; +use PHPCR\Util\CND\Scanner\TokenQueue; /** * @author Daniel Barsotti - * * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * */ class ParserException extends \Exception { @@ -26,7 +24,7 @@ public function __construct(TokenQueue $queue, $msg) break; } $token = $queue->get(); - $lookup .= $token->getData() . ' '; + $lookup .= $token->getData().' '; } $msg .= "\nBuffer lookup: \"$lookup\""; diff --git a/src/PHPCR/Util/CND/Exception/ScannerException.php b/src/PHPCR/Util/CND/Exception/ScannerException.php index cd4872e..8f20151 100644 --- a/src/PHPCR/Util/CND/Exception/ScannerException.php +++ b/src/PHPCR/Util/CND/Exception/ScannerException.php @@ -7,7 +7,6 @@ /** * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * * @author Daniel Barsotti */ class ScannerException extends \Exception diff --git a/src/PHPCR/Util/CND/Parser/AbstractParser.php b/src/PHPCR/Util/CND/Parser/AbstractParser.php index ff09486..e01aae6 100644 --- a/src/PHPCR/Util/CND/Parser/AbstractParser.php +++ b/src/PHPCR/Util/CND/Parser/AbstractParser.php @@ -2,12 +2,12 @@ namespace PHPCR\Util\CND\Parser; +use PHPCR\Util\CND\Exception\ParserException; use PHPCR\Util\CND\Scanner\GenericToken as Token; use PHPCR\Util\CND\Scanner\TokenQueue; -use PHPCR\Util\CND\Exception\ParserException; /** - * Abstract base class for parsers + * Abstract base class for parsers. * * It implements helper functions for parsers: * @@ -17,13 +17,12 @@ * * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * * @author Daniel Barsotti */ abstract class AbstractParser { /** - * The token queue + * The token queue. * * @var TokenQueue */ @@ -38,7 +37,7 @@ abstract class AbstractParser * @param null|string $data The expected data or null * @param bool $ignoreCase whether to do string comparisons case insensitive or sensitive * - * @return boolean + * @return bool */ protected function checkToken($type, $data = null, $ignoreCase = false) { @@ -69,7 +68,7 @@ protected function checkToken($type, $data = null, $ignoreCase = false) * @param int $type * @param array $data * - * @return boolean + * @return bool */ protected function checkTokenIn($type, array $data, $ignoreCase = false) { @@ -89,9 +88,9 @@ protected function checkTokenIn($type, array $data, $ignoreCase = false) * @param int $type The expected token type * @param null|string $data The expected token data or null * - * @return Token - * * @throws ParserException + * + * @return Token */ protected function expectToken($type, $data = null) { @@ -113,7 +112,7 @@ protected function expectToken($type, $data = null) * @param int $type The expected token type * @param null|string $data The expected token data or null * - * @return boolean|Token + * @return bool|Token */ protected function checkAndExpectToken($type, $data = null) { diff --git a/src/PHPCR/Util/CND/Parser/CndParser.php b/src/PHPCR/Util/CND/Parser/CndParser.php index 7dc5b48..4ae8a9a 100644 --- a/src/PHPCR/Util/CND/Parser/CndParser.php +++ b/src/PHPCR/Util/CND/Parser/CndParser.php @@ -7,13 +7,13 @@ use PHPCR\NodeType\NodeTypeTemplateInterface; use PHPCR\NodeType\PropertyDefinitionTemplateInterface; use PHPCR\PropertyType; +use PHPCR\Util\CND\Exception\ParserException; use PHPCR\Util\CND\Reader\BufferReader; use PHPCR\Util\CND\Reader\FileReader; use PHPCR\Util\CND\Reader\ReaderInterface; use PHPCR\Util\CND\Scanner\Context\DefaultScannerContextWithoutSpacesAndComments; use PHPCR\Util\CND\Scanner\GenericScanner; use PHPCR\Util\CND\Scanner\GenericToken as Token; -use PHPCR\Util\CND\Exception\ParserException; use PHPCR\Version\OnParentVersionAction; /** @@ -29,19 +29,18 @@ * * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * * @author Daniel Barsotti * @author David Buchmann */ 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), @@ -90,7 +89,7 @@ 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 + * hashmap of typename = > NodeTypeDefinitionInterface */ public function parseFile($filename) { @@ -105,7 +104,7 @@ 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 + * hashmap of typename = > NodeTypeDefinitionInterface */ public function parseString($cnd) { @@ -131,7 +130,7 @@ private function parse(ReaderInterface $reader) return [ 'namespaces' => $this->namespaces, - 'nodeTypes' => $this->nodeTypes, + 'nodeTypes' => $this->nodeTypes, ]; } @@ -283,7 +282,7 @@ protected function parseNodeTypeAttributes(NodeTypeTemplateInterface $nodeType) } /** - * Parse both the children propery and nodes definitions + * Parse both the children propery and nodes definitions. * * {PropertyDef | ChildNodeDef} */ @@ -369,11 +368,11 @@ protected function parsePropDef(NodeTypeTemplateInterface $nodeType) */ protected function parsePropertyType(PropertyDefinitionTemplateInterface $property) { - $types = ["STRING", "BINARY", "LONG", "DOUBLE", "BOOLEAN", "DATE", "NAME", "PATH", - "REFERENCE", "WEAKREFERENCE", "DECIMAL", "URI", "UNDEFINED", "*", "?"]; + $types = ['STRING', 'BINARY', 'LONG', 'DOUBLE', 'BOOLEAN', 'DATE', 'NAME', 'PATH', + 'REFERENCE', 'WEAKREFERENCE', 'DECIMAL', 'URI', 'UNDEFINED', '*', '?', ]; - if (! $this->checkTokenIn(Token::TK_IDENTIFIER, $types, true)) { - throw new ParserException($this->tokenQueue, sprintf("Invalid property type: %s", $this->tokenQueue->get()->getData())); + if (!$this->checkTokenIn(Token::TK_IDENTIFIER, $types, true)) { + throw new ParserException($this->tokenQueue, sprintf('Invalid property type: %s', $this->tokenQueue->get()->getData())); } $data = $this->tokenQueue->get()->getData(); @@ -387,7 +386,7 @@ protected function parsePropertyType(PropertyDefinitionTemplateInterface $proper * The default values, if any, are listed after a '='. The attribute is a * list in order to accommodate multi-value properties. The absence of this * element indicates that there is no static default value reportable. A '?' - * indicates that this attribute is a variant + * indicates that this attribute is a variant. * * DefaultValues ::= '=' (StringList | '?') */ @@ -405,7 +404,7 @@ protected function parseDefaultValue(PropertyDefinitionTemplateInterface $proper /** * The value constraints, if any, are listed after a '<'. The absence of * this element indicates that no value constraints reportable within the - * value constraint syntax. A '?' indicates that this attribute is a variant + * value constraint syntax. A '?' indicates that this attribute is a variant. * * ValueConstraints ::= '<' (StringList | '?') */ @@ -500,7 +499,7 @@ protected function parsePropertyAttributes(NodeTypeTemplateInterface $parentType $property->setQueryOrderable(false); } elseif ($this->checkTokenIn(Token::TK_IDENTIFIER, $this->OPV)) { if ($opvSeen) { - throw new ParserException($this->tokenQueue, 'More than one on parent version action specified on property ' . $property->getName()); + throw new ParserException($this->tokenQueue, 'More than one on parent version action specified on property '.$property->getName()); } $token = $this->tokenQueue->get(); $property->setOnParentVersion(OnParentVersionAction::valueFromName($token->getData())); @@ -624,7 +623,7 @@ protected function parseChildNodeAttributes( } /** - * Parse a string list + * Parse a string list. * * StringList ::= String {',' String} * @@ -643,7 +642,7 @@ protected function parseCndStringList() } /** - * Parse a string + * Parse a string. * * String ::= QuotedString | UnquotedString * QuotedString ::= SingleQuotedString | DoubleQuotedString diff --git a/src/PHPCR/Util/CND/Reader/BufferReader.php b/src/PHPCR/Util/CND/Reader/BufferReader.php index 4585d8c..e9b8d0b 100644 --- a/src/PHPCR/Util/CND/Reader/BufferReader.php +++ b/src/PHPCR/Util/CND/Reader/BufferReader.php @@ -5,7 +5,6 @@ /** * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * * @author Daniel Barsotti * @author Nikola Petkanski */ @@ -57,7 +56,7 @@ class BufferReader implements ReaderInterface public function __construct($buffer) { $this->eofMarker = chr(1); - $this->buffer = str_replace("\r\n", "\n", $buffer) . $this->eofMarker; + $this->buffer = str_replace("\r\n", "\n", $buffer).$this->eofMarker; $this->reset(); } @@ -96,7 +95,8 @@ public function getCurrentColumn() } /** - * Return the literal delimited by start and end position + * Return the literal delimited by start and end position. + * * @return string */ public function current() @@ -110,7 +110,7 @@ public function currentChar() } /** - * @return boolean + * @return bool */ public function isEof() { @@ -121,7 +121,7 @@ public function isEof() } /** - * Advance the forward position and return the literal delimited by start and end position + * Advance the forward position and return the literal delimited by start and end position. * * @return string */ diff --git a/src/PHPCR/Util/CND/Reader/FileReader.php b/src/PHPCR/Util/CND/Reader/FileReader.php index 8bddb0a..2115b5f 100644 --- a/src/PHPCR/Util/CND/Reader/FileReader.php +++ b/src/PHPCR/Util/CND/Reader/FileReader.php @@ -5,7 +5,6 @@ /** * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * * @author Daniel Barsotti * @author Nikola Petkanski */ diff --git a/src/PHPCR/Util/CND/Reader/ReaderInterface.php b/src/PHPCR/Util/CND/Reader/ReaderInterface.php index c633b6b..0f8b73e 100644 --- a/src/PHPCR/Util/CND/Reader/ReaderInterface.php +++ b/src/PHPCR/Util/CND/Reader/ReaderInterface.php @@ -5,7 +5,6 @@ /** * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * * @author Daniel Barsotti */ interface ReaderInterface @@ -21,7 +20,7 @@ public function getEofMarker(); public function currentChar(); /** - * @return boolean + * @return bool */ public function isEof(); @@ -36,14 +35,15 @@ public function getCurrentLine(); public function getCurrentColumn(); /** - * Return the literal delimited by start and end position + * Return the literal delimited by start and end position. * * @return string */ public function current(); /** - * Advance the forward position and return the literal delimited by start and end position + * Advance the forward position and return the literal delimited by start and end position. + * * @return string */ public function forward(); @@ -51,13 +51,13 @@ public function forward(); public function forwardChar(); /** - * Rewind the forward position to the start position + * Rewind the forward position to the start position. */ public function rewind(); /** * Return the literal delimited by start and end position, then set the - * start position to the end position + * start position to the end position. * * @return string */ diff --git a/src/PHPCR/Util/CND/Scanner/AbstractScanner.php b/src/PHPCR/Util/CND/Scanner/AbstractScanner.php index 4aa178d..f61f0dd 100644 --- a/src/PHPCR/Util/CND/Scanner/AbstractScanner.php +++ b/src/PHPCR/Util/CND/Scanner/AbstractScanner.php @@ -7,7 +7,6 @@ /** * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * * @author Daniel Barsotti */ abstract class AbstractScanner diff --git a/src/PHPCR/Util/CND/Scanner/Context/DefaultScannerContext.php b/src/PHPCR/Util/CND/Scanner/Context/DefaultScannerContext.php index c80705c..e983802 100644 --- a/src/PHPCR/Util/CND/Scanner/Context/DefaultScannerContext.php +++ b/src/PHPCR/Util/CND/Scanner/Context/DefaultScannerContext.php @@ -5,14 +5,13 @@ /** * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * * @author Daniel Barsotti */ class DefaultScannerContext extends ScannerContext { public function __construct() { - $this->addWhitespace(" "); + $this->addWhitespace(' '); $this->addWhitespace("\t"); $this->addStringDelimiter('\''); diff --git a/src/PHPCR/Util/CND/Scanner/Context/DefaultScannerContextWithoutSpacesAndComments.php b/src/PHPCR/Util/CND/Scanner/Context/DefaultScannerContextWithoutSpacesAndComments.php index 7cc39a8..0bd85b4 100644 --- a/src/PHPCR/Util/CND/Scanner/Context/DefaultScannerContextWithoutSpacesAndComments.php +++ b/src/PHPCR/Util/CND/Scanner/Context/DefaultScannerContextWithoutSpacesAndComments.php @@ -7,7 +7,6 @@ /** * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * * @author Daniel Barsotti */ class DefaultScannerContextWithoutSpacesAndComments extends DefaultScannerContext diff --git a/src/PHPCR/Util/CND/Scanner/Context/ScannerContext.php b/src/PHPCR/Util/CND/Scanner/Context/ScannerContext.php index 7a72915..a9ea48a 100644 --- a/src/PHPCR/Util/CND/Scanner/Context/ScannerContext.php +++ b/src/PHPCR/Util/CND/Scanner/Context/ScannerContext.php @@ -7,13 +7,13 @@ /** * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * * @author Daniel Barsotti */ class ScannerContext { /** - * Characters to be considered as white spaces + * Characters to be considered as white spaces. + * * @var array */ protected $whitespaces = []; @@ -29,14 +29,14 @@ class ScannerContext protected $stringDelimiters = []; /** - * Line comments start + * Line comments start. * * @var array */ protected $lineCommentDelimiters = []; /** - * Block comments delimiters + * Block comments delimiters. * * @var array */ diff --git a/src/PHPCR/Util/CND/Scanner/GenericScanner.php b/src/PHPCR/Util/CND/Scanner/GenericScanner.php index 9dd8367..edc1d00 100644 --- a/src/PHPCR/Util/CND/Scanner/GenericScanner.php +++ b/src/PHPCR/Util/CND/Scanner/GenericScanner.php @@ -2,8 +2,8 @@ namespace PHPCR\Util\CND\Scanner; -use PHPCR\Util\CND\Reader\ReaderInterface; use PHPCR\Util\CND\Exception\ScannerException; +use PHPCR\Util\CND\Reader\ReaderInterface; /** * Generic scanner detecting GenericTokens. @@ -13,7 +13,6 @@ * * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * * @author Daniel Barsotti * @author Nikola Petkanski */ @@ -54,11 +53,11 @@ public function scan(ReaderInterface $reader) } /** - * Detect and consume whitespaces + * Detect and consume whitespaces. * * @param ReaderInterface $reader * - * @return boolean + * @return bool */ protected function consumeSpaces(ReaderInterface $reader) { @@ -80,11 +79,11 @@ protected function consumeSpaces(ReaderInterface $reader) } /** - * Detect and consume newlines + * Detect and consume newlines. * * @param ReaderInterface $reader * - * @return boolean + * @return bool */ protected function consumeNewLine(ReaderInterface $reader) { @@ -105,13 +104,13 @@ protected function consumeNewLine(ReaderInterface $reader) } /** - * Detect and consume strings + * Detect and consume strings. * - * @param ReaderInterface $reader - * - * @return boolean + * @param ReaderInterface $reader * * @throws ScannerException + * + * @return bool */ protected function consumeString(ReaderInterface $reader) { @@ -120,7 +119,7 @@ protected function consumeString(ReaderInterface $reader) $char = $reader->forwardChar(); while ($char !== $curDelimiter) { if ($char === "\n") { - throw new ScannerException($reader, "Newline detected in string"); + throw new ScannerException($reader, 'Newline detected in string'); } $char = $reader->forwardChar(); @@ -137,11 +136,11 @@ protected function consumeString(ReaderInterface $reader) } /** - * Detect and consume comments + * Detect and consume comments. * * @param ReaderInterface $reader * - * @return boolean + * @return bool */ protected function consumeComments(ReaderInterface $reader) { @@ -153,13 +152,13 @@ protected function consumeComments(ReaderInterface $reader) } /** - * Detect and consume block comments - * - * @param ReaderInterface $reader + * Detect and consume block comments. * - * @return boolean + * @param ReaderInterface $reader * * @throws ScannerException + * + * @return bool */ protected function consumeBlockComments(ReaderInterface $reader) { @@ -176,7 +175,7 @@ protected function consumeBlockComments(ReaderInterface $reader) // Start delimiter found, let's try to find the end delimiter $nextChar = $reader->forwardChar(); - while (! $reader->isEof()) { + while (!$reader->isEof()) { if ($nextChar === $endDelim[0]) { for ($i = 1; $i <= strlen($endDelim); $i++) { $reader->forward(); @@ -194,7 +193,7 @@ protected function consumeBlockComments(ReaderInterface $reader) } // End of file reached and no end delimiter found, error - throw new ScannerException($reader, "Unterminated block comment"); + throw new ScannerException($reader, 'Unterminated block comment'); } // Start delimiter not found, rewind the looked up characters @@ -208,11 +207,11 @@ protected function consumeBlockComments(ReaderInterface $reader) } /** - * Detect and consume line comments + * Detect and consume line comments. * * @param ReaderInterface $reader * - * @return boolean + * @return bool */ protected function consumeLineComments(ReaderInterface $reader) { @@ -247,11 +246,11 @@ protected function consumeLineComments(ReaderInterface $reader) } /** - * Detect and consume identifiers + * Detect and consume identifiers. * * @param ReaderInterface $reader * - * @return boolean + * @return bool */ protected function consumeIdentifiers(ReaderInterface $reader) { @@ -272,11 +271,11 @@ protected function consumeIdentifiers(ReaderInterface $reader) } /** - * Detect and consume symbols + * Detect and consume symbols. * * @param ReaderInterface $reader * - * @return boolean + * @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 0b148d2..735de8c 100644 --- a/src/PHPCR/Util/CND/Scanner/GenericToken.php +++ b/src/PHPCR/Util/CND/Scanner/GenericToken.php @@ -5,7 +5,6 @@ /** * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * * @author Daniel Barsotti */ class GenericToken extends Token diff --git a/src/PHPCR/Util/CND/Scanner/Token.php b/src/PHPCR/Util/CND/Scanner/Token.php index 6f12bba..80aebe6 100644 --- a/src/PHPCR/Util/CND/Scanner/Token.php +++ b/src/PHPCR/Util/CND/Scanner/Token.php @@ -9,41 +9,40 @@ * * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * * @author Daniel Barsotti */ class Token { /** - * The type of token + * The type of token. * * @var int */ public $type; /** - * The token raw data + * The token raw data. * * @var string */ public $data; /** - * The line where the token appears + * The line where the token appears. * * @var int */ protected $line; /** - * The column where the token appears + * The column where the token appears. * * @var int */ protected $row; /** - * Constructor + * Constructor. * * @param int $type * @param string $data diff --git a/src/PHPCR/Util/CND/Scanner/TokenFilter/NoCommentsFilter.php b/src/PHPCR/Util/CND/Scanner/TokenFilter/NoCommentsFilter.php index dd3684b..d2a898e 100644 --- a/src/PHPCR/Util/CND/Scanner/TokenFilter/NoCommentsFilter.php +++ b/src/PHPCR/Util/CND/Scanner/TokenFilter/NoCommentsFilter.php @@ -7,7 +7,6 @@ /** * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * * @author Daniel Barsotti */ class NoCommentsFilter extends TokenTypeFilter diff --git a/src/PHPCR/Util/CND/Scanner/TokenFilter/NoNewlinesFilter.php b/src/PHPCR/Util/CND/Scanner/TokenFilter/NoNewlinesFilter.php index f45aae1..54b519a 100644 --- a/src/PHPCR/Util/CND/Scanner/TokenFilter/NoNewlinesFilter.php +++ b/src/PHPCR/Util/CND/Scanner/TokenFilter/NoNewlinesFilter.php @@ -7,7 +7,6 @@ /** * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * * @author Daniel Barsotti */ class NoNewlinesFilter extends TokenTypeFilter diff --git a/src/PHPCR/Util/CND/Scanner/TokenFilter/NoWhitespacesFilter.php b/src/PHPCR/Util/CND/Scanner/TokenFilter/NoWhitespacesFilter.php index 80fe846..7d3bc02 100644 --- a/src/PHPCR/Util/CND/Scanner/TokenFilter/NoWhitespacesFilter.php +++ b/src/PHPCR/Util/CND/Scanner/TokenFilter/NoWhitespacesFilter.php @@ -7,7 +7,6 @@ /** * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * * @author Daniel Barsotti */ class NoWhitespacesFilter extends TokenTypeFilter diff --git a/src/PHPCR/Util/CND/Scanner/TokenFilter/TokenFilterChain.php b/src/PHPCR/Util/CND/Scanner/TokenFilter/TokenFilterChain.php index 5f51b30..f24fdb6 100644 --- a/src/PHPCR/Util/CND/Scanner/TokenFilter/TokenFilterChain.php +++ b/src/PHPCR/Util/CND/Scanner/TokenFilter/TokenFilterChain.php @@ -7,7 +7,6 @@ /** * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * * @author Daniel Barsotti */ class TokenFilterChain implements TokenFilterInterface @@ -23,7 +22,8 @@ public function addFilter(TokenFilterInterface $filter) } /** - * @param Token $token + * @param Token $token + * * @return Token | null */ public function filter(Token $token) @@ -32,7 +32,7 @@ public function filter(Token $token) $token = $filter->filter($token); if (!$token) { - return null; + return; } } diff --git a/src/PHPCR/Util/CND/Scanner/TokenFilter/TokenFilterInterface.php b/src/PHPCR/Util/CND/Scanner/TokenFilter/TokenFilterInterface.php index a468480..6acf162 100644 --- a/src/PHPCR/Util/CND/Scanner/TokenFilter/TokenFilterInterface.php +++ b/src/PHPCR/Util/CND/Scanner/TokenFilter/TokenFilterInterface.php @@ -7,14 +7,15 @@ /** * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * * @author Daniel Barsotti */ interface TokenFilterInterface { /** * @abstract - * @param Token $token + * + * @param Token $token + * * @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 2eb5ed9..9268388 100644 --- a/src/PHPCR/Util/CND/Scanner/TokenFilter/TokenTypeFilter.php +++ b/src/PHPCR/Util/CND/Scanner/TokenFilter/TokenTypeFilter.php @@ -7,13 +7,13 @@ /** * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * * @author Daniel Barsotti */ class TokenTypeFilter implements TokenFilterInterface { /** - * The filtered out token type + * The filtered out token type. + * * @var int */ protected $type; @@ -24,13 +24,14 @@ public function __construct($tokenType) } /** - * @param Token $token + * @param Token $token + * * @return Token | null */ public function filter(Token $token) { if ($token->getType() === $this->type) { - return null; + return; } return $token; diff --git a/src/PHPCR/Util/CND/Scanner/TokenQueue.php b/src/PHPCR/Util/CND/Scanner/TokenQueue.php index ae141e1..188f72e 100644 --- a/src/PHPCR/Util/CND/Scanner/TokenQueue.php +++ b/src/PHPCR/Util/CND/Scanner/TokenQueue.php @@ -5,7 +5,6 @@ /** * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * * @author Daniel Barsotti */ class TokenQueue implements \IteratorAggregate diff --git a/src/PHPCR/Util/CND/Writer/CndWriter.php b/src/PHPCR/Util/CND/Writer/CndWriter.php index 046d01f..4df28c7 100644 --- a/src/PHPCR/Util/CND/Writer/CndWriter.php +++ b/src/PHPCR/Util/CND/Writer/CndWriter.php @@ -3,13 +3,13 @@ namespace PHPCR\Util\CND\Writer; use PHPCR\NamespaceRegistryInterface; -use PHPCR\PropertyType; -use PHPCR\Version\OnParentVersionAction; use PHPCR\NodeType\NodeDefinitionInterface; use PHPCR\NodeType\NodeTypeDefinitionInterface; use PHPCR\NodeType\NodeTypeManagerInterface; use PHPCR\NodeType\NodeTypeTemplateInterface; use PHPCR\NodeType\PropertyDefinitionInterface; +use PHPCR\PropertyType; +use PHPCR\Version\OnParentVersionAction; /** * Generator for JCR-2.0 CND files. @@ -22,7 +22,6 @@ * * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * * @author David Buchmann */ class CndWriter @@ -49,7 +48,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) { @@ -58,7 +57,7 @@ public function writeString(array $nodeTypes) $cnd .= $this->writeNodeType($nodeType); } - return $this->writeNamespaces() . $cnd; + return $this->writeNamespaces().$cnd; } /** @@ -86,7 +85,7 @@ private function checkNamespace($name) list($prefix) = explode(':', $name); // namespace registry will throw exception if namespace prefix not found - $this->namespaces[$prefix] = "'" . $this->ns->getURI($prefix) . "'"; + $this->namespaces[$prefix] = "'".$this->ns->getURI($prefix)."'"; } /** @@ -101,12 +100,12 @@ private function checkNamespace($name) protected function writeNodeType(NodeTypeDefinitionInterface $nodeType) { $this->checkNamespace($nodeType->getName()); - $s = '[' . $nodeType->getName() . ']'; + $s = '['.$nodeType->getName().']'; if ($superTypes = $nodeType->getDeclaredSupertypeNames()) { foreach ($superTypes as $superType) { $this->checkNamespace($superType); } - $s .= ' > ' . implode(', ', $superTypes); + $s .= ' > '.implode(', ', $superTypes); } $s .= "\n"; @@ -123,10 +122,10 @@ protected function writeNodeType(NodeTypeDefinitionInterface $nodeType) } $attributes .= $nodeType->isQueryable() ? 'query ' : 'noquery '; if ($nodeType->getPrimaryItemName()) { - $attributes .= 'primaryitem ' . $nodeType->getPrimaryItemName() . ' '; + $attributes .= 'primaryitem '.$nodeType->getPrimaryItemName().' '; } if ($attributes) { - $s .= trim($attributes) . "\n"; + $s .= trim($attributes)."\n"; } $s .= $this->writeProperties($nodeType->getDeclaredPropertyDefinitions()); @@ -149,14 +148,14 @@ private function writeProperties($properties) /** @var $property PropertyDefinitionInterface */ foreach ($properties as $property) { $this->checkNamespace($property->getName()); - $s .= '- ' . $property->getName(); + $s .= '- '.$property->getName(); if ($property->getRequiredType()) { - $s .= ' (' . PropertyType::nameFromValue($property->getRequiredType()) . ')'; + $s .= ' ('.PropertyType::nameFromValue($property->getRequiredType()).')'; } $s .= "\n"; if ($property->getDefaultValues()) { - $s .= "= '" . implode("', '", $property->getDefaultValues()) . "'\n"; + $s .= "= '".implode("', '", $property->getDefaultValues())."'\n"; } $attributes = ''; if ($property->isMandatory()) { @@ -174,23 +173,23 @@ private function writeProperties($properties) if ($property->getAvailableQueryOperators()) { $attributes .= implode("', '", $property->getAvailableQueryOperators()); } - if (! $property->isFullTextSearchable()) { + if (!$property->isFullTextSearchable()) { $attributes .= 'nofulltext '; } - if (! $property->isQueryOrderable()) { + if (!$property->isQueryOrderable()) { $attributes .= 'noqueryorder '; } if (OnParentVersionAction::COPY !== $property->getOnParentVersion()) { - $attributes .= OnParentVersionAction::nameFromValue($property->getOnParentVersion()) . ' '; + $attributes .= OnParentVersionAction::nameFromValue($property->getOnParentVersion()).' '; } if ($attributes) { - $s .= trim($attributes) . "\n"; + $s .= trim($attributes)."\n"; } if ($property->getValueConstraints()) { - $s .= "< '" . implode("', '", $property->getValueConstraints()) . "'\n"; + $s .= "< '".implode("', '", $property->getValueConstraints())."'\n"; } } @@ -210,17 +209,17 @@ private function writeChildren($children) /** @var $child NodeDefinitionInterface */ foreach ($children as $child) { $this->checkNamespace($child->getName()); - $s .= '+ ' . $child->getName(); + $s .= '+ '.$child->getName(); if ($child->getRequiredPrimaryTypeNames()) { foreach ($child->getRequiredPrimaryTypeNames() as $typeName) { $this->checkNamespace($typeName); } - $s .= ' (' . implode(', ', $child->getRequiredPrimaryTypeNames()) . ')'; + $s .= ' ('.implode(', ', $child->getRequiredPrimaryTypeNames()).')'; } if ($child->getDefaultPrimaryTypeName()) { $this->checkNamespace($child->getDefaultPrimaryTypeName()); - $s .= "\n= " . $child->getDefaultPrimaryTypeName(); + $s .= "\n= ".$child->getDefaultPrimaryTypeName(); } $s .= "\n"; @@ -235,14 +234,14 @@ private function writeChildren($children) $attributes .= 'protected '; } if (OnParentVersionAction::COPY != $child->getOnParentVersion()) { - $attributes .= OnParentVersionAction::nameFromValue($child->getOnParentVersion()) . ' '; + $attributes .= OnParentVersionAction::nameFromValue($child->getOnParentVersion()).' '; } if ($child->allowsSameNameSiblings()) { $attributes .= 'sns '; } if ($attributes) { - $s .= trim($attributes) . "\n"; + $s .= trim($attributes)."\n"; } } diff --git a/src/PHPCR/Util/Console/Command/BaseCommand.php b/src/PHPCR/Util/Console/Command/BaseCommand.php index 11a534c..eb6d82b 100644 --- a/src/PHPCR/Util/Console/Command/BaseCommand.php +++ b/src/PHPCR/Util/Console/Command/BaseCommand.php @@ -2,12 +2,12 @@ namespace PHPCR\Util\Console\Command; +use PHPCR\SessionInterface; +use PHPCR\Util\Console\Helper\PhpcrConsoleDumperHelper; +use PHPCR\Util\Console\Helper\PhpcrHelper; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; -use PHPCR\SessionInterface; -use PHPCR\Util\Console\Helper\PhpcrHelper; -use PHPCR\Util\Console\Helper\PhpcrConsoleDumperHelper; use Symfony\Component\Console\Question\ConfirmationQuestion; use Symfony\Component\Console\Question\Question; @@ -73,7 +73,7 @@ protected function ask(InputInterface $input, OutputInterface $output, $question * @param InputInterface $input * @param OutputInterface $output * @param string $question - * @param boolean $default + * @param bool $default * * @return string */ diff --git a/src/PHPCR/Util/Console/Command/NodeDumpCommand.php b/src/PHPCR/Util/Console/Command/NodeDumpCommand.php index ee22d95..576973e 100644 --- a/src/PHPCR/Util/Console/Command/NodeDumpCommand.php +++ b/src/PHPCR/Util/Console/Command/NodeDumpCommand.php @@ -4,28 +4,27 @@ use Exception; use PHPCR\ItemNotFoundException; -use PHPCR\RepositoryException; use PHPCR\PathNotFoundException; +use PHPCR\RepositoryException; use PHPCR\Util\UUIDHelper; use Symfony\Component\Console\Exception\InvalidArgumentException; use Symfony\Component\Console\Input\InputArgument; -use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; /** - * Command subtrees under a path to the console + * Command subtrees under a path to the console. * * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * * @author Daniel Barsotti * @author Daniel Leech */ class NodeDumpCommand extends BaseCommand { /** - * {@inheritDoc} + * {@inheritdoc} * * @throws InvalidArgumentException */ @@ -36,12 +35,12 @@ protected function configure() ->addOption('sys-nodes', null, InputOption::VALUE_NONE, 'Also dump system nodes (recommended to use with a depth limit)') ->addOption('props', null, InputOption::VALUE_NONE, 'Also dump properties of the nodes') ->addOption('identifiers', null, InputOption::VALUE_NONE, 'Also output node UUID') - ->addOption('depth', null, InputOption::VALUE_OPTIONAL, 'Limit how many level of children to show', "-1") - ->addOption('max_line_length', null, InputOption::VALUE_OPTIONAL, 'Limit the maximum characters per property', "120") + ->addOption('depth', null, InputOption::VALUE_OPTIONAL, 'Limit how many level of children to show', '-1') + ->addOption('max_line_length', null, InputOption::VALUE_OPTIONAL, 'Limit the maximum characters per property', '120') ->addOption('ref-format', 'uuid', InputOption::VALUE_REQUIRED, 'Set the way references should be displayed when dumping reference properties - either "uuid" (default) or "path"') ->addArgument('identifier', InputArgument::OPTIONAL, 'Root path to dump', '/') ->setDescription('Dump subtrees of the content repository') - ->setHelp(<<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. @@ -52,12 +51,11 @@ protected function configure() properties with names starting with 'jcr:'), the --sys-nodes option allows to turn this filter off. HERE - ) - ; + ); } /** - * {@inheritDoc} + * {@inheritdoc} * * @throws InvalidArgumentException * @throws Exception diff --git a/src/PHPCR/Util/Console/Command/NodeMoveCommand.php b/src/PHPCR/Util/Console/Command/NodeMoveCommand.php index 3374ad0..ef3699f 100644 --- a/src/PHPCR/Util/Console/Command/NodeMoveCommand.php +++ b/src/PHPCR/Util/Console/Command/NodeMoveCommand.php @@ -9,17 +9,16 @@ use Symfony\Component\Console\Output\OutputInterface; /** - * Command to move a node from one path to another + * Command to move a node from one path to another. * * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * * @author Daniel Leech */ class NodeMoveCommand extends BaseCommand { /** - * {@inheritDoc} + * {@inheritdoc} * * @throws InvalidArgumentException */ @@ -30,7 +29,7 @@ protected function configure() ->addArgument('source', InputArgument::REQUIRED, 'Path of node to move') ->addArgument('destination', InputArgument::REQUIRED, 'Destination for node') ->setDescription('Moves a node from one path to another') - ->setHelp(<<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. @@ -39,12 +38,11 @@ protected function configure() Note that the parent node of the destination path must already exist. EOF - ) - ; + ); } /** - * {@inheritDoc} + * {@inheritdoc} * * @throws InvalidArgumentException */ diff --git a/src/PHPCR/Util/Console/Command/NodeRemoveCommand.php b/src/PHPCR/Util/Console/Command/NodeRemoveCommand.php index 6f217f6..bf7ec0f 100644 --- a/src/PHPCR/Util/Console/Command/NodeRemoveCommand.php +++ b/src/PHPCR/Util/Console/Command/NodeRemoveCommand.php @@ -6,8 +6,8 @@ use PHPCR\NodeInterface; use Symfony\Component\Console\Exception\InvalidArgumentException as CliInvalidArgumentException; use Symfony\Component\Console\Input\InputArgument; -use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; /** @@ -16,14 +16,13 @@ * * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * * @author Daniel Barsotti * @author Daniel Leech */ class NodeRemoveCommand extends BaseCommand { /** - * {@inheritDoc} + * {@inheritdoc} * * @throws CliInvalidArgumentException */ @@ -37,7 +36,7 @@ protected function configure() ->addArgument('path', InputArgument::REQUIRED, 'Path of the node to purge') ->addOption('force', null, InputOption::VALUE_NONE, 'Use to bypass the confirmation dialog') ->addOption('only-children', null, InputOption::VALUE_NONE, 'Use to only purge children of specified path') - ->setHelp(<<setHelp(<<<'EOF' The phpcr:node:remove command will remove the given node or the children of the given node according to the options given. @@ -49,12 +48,11 @@ protected function configure() $ php bin/phpcr phpcr:node:remove /cms/content/blog --only-children EOF - ) - ; + ); } /** - * {@inheritDoc} + * {@inheritdoc} * * @throws CliInvalidArgumentException * @throws InvalidArgumentException diff --git a/src/PHPCR/Util/Console/Command/NodeTouchCommand.php b/src/PHPCR/Util/Console/Command/NodeTouchCommand.php index 9e8d72e..0ede6d1 100644 --- a/src/PHPCR/Util/Console/Command/NodeTouchCommand.php +++ b/src/PHPCR/Util/Console/Command/NodeTouchCommand.php @@ -2,14 +2,14 @@ namespace PHPCR\Util\Console\Command; +use PHPCR\PathNotFoundException; +use PHPCR\Util\PathHelper; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Exception\InvalidArgumentException; -use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; -use PHPCR\PathNotFoundException; -use PHPCR\Util\PathHelper; /** * Command to create a PHPCR node of a specified type from @@ -17,13 +17,12 @@ * * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * * @author Daniel Leech */ class NodeTouchCommand extends BaseNodeManipulationCommand { /** - * {@inheritDoc} + * {@inheritdoc} * * @throws InvalidArgumentException */ @@ -50,7 +49,7 @@ protected function configure() 'Dump a string reperesentation of the created / modified node.' ) ->setDescription('Create or modify a node') - ->setHelp(<<setHelp(<<<'HERE' This command allows you to create or modify a node at the specified path. For example:: @@ -70,7 +69,7 @@ protected function configure() } /** - * {@inheritDoc} + * {@inheritdoc} * * @throws InvalidArgumentException */ @@ -133,11 +132,11 @@ protected function execute(InputInterface $input, OutputInterface $output) } $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/NodeTypeListCommand.php b/src/PHPCR/Util/Console/Command/NodeTypeListCommand.php index f31baff..060ea9e 100644 --- a/src/PHPCR/Util/Console/Command/NodeTypeListCommand.php +++ b/src/PHPCR/Util/Console/Command/NodeTypeListCommand.php @@ -3,38 +3,35 @@ namespace PHPCR\Util\Console\Command; use Symfony\Component\Console\Command\Command; -use Symfony\Component\Console\Exception\InvalidArgumentException; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** - * A command to list all node types + * A command to list all node types. * * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * * @author Daniel Leech */ class NodeTypeListCommand extends BaseCommand { /** - * {@inheritDoc} + * {@inheritdoc} */ protected function configure() { $this ->setName('phpcr:node-type:list') ->setDescription('List all available node types in the repository') - ->setHelp(<<setHelp(<<<'EOT' This command lists all of the available node types and their subtypes in the PHPCR repository. EOT - ) - ; + ); } /** - * {@inheritDoc} + * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { diff --git a/src/PHPCR/Util/Console/Command/NodeTypeRegisterCommand.php b/src/PHPCR/Util/Console/Command/NodeTypeRegisterCommand.php index 6dbb39b..2020bcc 100644 --- a/src/PHPCR/Util/Console/Command/NodeTypeRegisterCommand.php +++ b/src/PHPCR/Util/Console/Command/NodeTypeRegisterCommand.php @@ -3,31 +3,31 @@ namespace PHPCR\Util\Console\Command; use InvalidArgumentException; +use PHPCR\NodeType\NodeTypeExistsException; use PHPCR\RepositoryException; +use PHPCR\SessionInterface; use Symfony\Component\Console\Input\InputArgument; -use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; -use PHPCR\SessionInterface; -use PHPCR\NodeType\NodeTypeExistsException; /** * Command to load and register a node type defined in a common nodetype * definition (CND) file. * * See the link below for the cnd definition. + * * @link 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 - * * @author Uwe Jäger * @author Daniel Leech */ class NodeTypeRegisterCommand extends BaseCommand { /** - * {@inheritDoc} + * {@inheritdoc} */ protected function configure() { @@ -36,7 +36,7 @@ protected function configure() ->setDescription('Register node types in the PHPCR repository') ->addArgument('cnd-file', InputArgument::IS_ARRAY, 'Register namespaces and node types from a "Compact Node Type Definition" .cnd file(s)') ->addOption('allow-update', null, InputOption::VALUE_NONE, 'Overwrite existig node type') - ->setHelp(<<setHelp(<<<'EOT' Register node types in the PHPCR repository. This command allows to register node types in the repository that are defined @@ -57,12 +57,11 @@ protected function configure() If you use --allow-update existing node type definitions will be overwritten in the repository. EOT - ) - ; + ); } /** - * {@inheritDoc} + * {@inheritdoc} * * @throws InvalidArgumentException */ @@ -114,6 +113,7 @@ protected function updateFromCnd(OutputInterface $output, SessionInterface $sess $output->write(PHP_EOL.'If you want to override the existing definition call this command with the '); $output->write('--allow-update option.'.PHP_EOL); } + throw $e; } } @@ -124,9 +124,9 @@ protected function updateFromCnd(OutputInterface $output, SessionInterface $sess * * @param array $definitions List of files of folders * - * @return array Array of full paths to all the type node definition files. - * * @throws InvalidArgumentException + * + * @return array Array of full paths to all the type node definition files. */ protected function getFilePaths($definitions) { diff --git a/src/PHPCR/Util/Console/Command/NodesUpdateCommand.php b/src/PHPCR/Util/Console/Command/NodesUpdateCommand.php index ff793ff..4f24644 100644 --- a/src/PHPCR/Util/Console/Command/NodesUpdateCommand.php +++ b/src/PHPCR/Util/Console/Command/NodesUpdateCommand.php @@ -6,8 +6,8 @@ use PHPCR\Query\QueryResultInterface; use PHPCR\Query\RowInterface; use Symfony\Component\Console\Exception\InvalidArgumentException as CliInvalidArgumentException; -use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; /** @@ -16,13 +16,12 @@ * * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * * @author Daniel Leech */ class NodesUpdateCommand extends BaseNodeManipulationCommand { /** - * {@inheritDoc} + * {@inheritdoc} * * @throws CliInvalidArgumentException */ @@ -82,7 +81,7 @@ protected function configure() } /** - * {@inheritDoc} + * {@inheritdoc} * * @throws CliInvalidArgumentException * @throws InvalidArgumentException @@ -125,7 +124,7 @@ protected function execute(InputInterface $input, OutputInterface $output) /** @var $row RowInterface */ foreach ($result as $i => $row) { $output->writeln(sprintf( - "Updating node: [%d] %s.", + 'Updating node: [%d] %s.', $i, $row->getPath() )); @@ -133,10 +132,10 @@ protected function execute(InputInterface $input, OutputInterface $output) $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, ]); diff --git a/src/PHPCR/Util/Console/Command/WorkspaceCreateCommand.php b/src/PHPCR/Util/Console/Command/WorkspaceCreateCommand.php index 7effe84..90f0935 100644 --- a/src/PHPCR/Util/Console/Command/WorkspaceCreateCommand.php +++ b/src/PHPCR/Util/Console/Command/WorkspaceCreateCommand.php @@ -3,24 +3,23 @@ namespace PHPCR\Util\Console\Command; use PHPCR\RepositoryInterface; -use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; /** - * A command to create a workspace in the PHPCR repository + * A command to create a workspace in the PHPCR repository. * * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * * @author Lukas Kahwe Smith * @author David Buchmann */ class WorkspaceCreateCommand extends BaseCommand { /** - * {@inheritDoc} + * {@inheritdoc} */ protected function configure() { @@ -34,17 +33,16 @@ protected function configure() 'If set, an existing workspace will return a success code' ) ->setDescription('Create a workspace in the configured repository') - ->setHelp(<<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 - ) - ; + ); } /** - * {@inheritDoc} + * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { diff --git a/src/PHPCR/Util/Console/Command/WorkspaceDeleteCommand.php b/src/PHPCR/Util/Console/Command/WorkspaceDeleteCommand.php index d498d38..ea8aeae 100644 --- a/src/PHPCR/Util/Console/Command/WorkspaceDeleteCommand.php +++ b/src/PHPCR/Util/Console/Command/WorkspaceDeleteCommand.php @@ -9,17 +9,16 @@ use Symfony\Component\Console\Output\OutputInterface; /** - * A command to delete a workspace in the PHPCR repository + * A command to delete a workspace in the PHPCR repository. * * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * * @author David Buchmann */ class WorkspaceDeleteCommand extends BaseCommand { /** - * {@inheritDoc} + * {@inheritdoc} */ protected function configure() { @@ -28,18 +27,17 @@ protected function configure() ->addArgument('name', InputArgument::REQUIRED, 'Name of the workspace to delete') ->addOption('force', null, InputOption::VALUE_NONE, 'Use to bypass the confirmation dialog') ->setDescription('Delete a workspace from the configured repository') - ->setHelp(<<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 - ) - ; + ); } /** - * {@inheritDoc} + * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { @@ -50,7 +48,7 @@ protected function execute(InputInterface $input, OutputInterface $output) $workspace = $session->getWorkspace(); $repo = $session->getRepository(); - if (! in_array($workspaceName, $workspace->getAccessibleWorkspaceNames())) { + if (!in_array($workspaceName, $workspace->getAccessibleWorkspaceNames())) { $output->writeln("Workspace '$workspaceName' does not exist."); return 0; diff --git a/src/PHPCR/Util/Console/Command/WorkspaceExportCommand.php b/src/PHPCR/Util/Console/Command/WorkspaceExportCommand.php index b0a8929..a4bc178 100644 --- a/src/PHPCR/Util/Console/Command/WorkspaceExportCommand.php +++ b/src/PHPCR/Util/Console/Command/WorkspaceExportCommand.php @@ -2,24 +2,23 @@ namespace PHPCR\Util\Console\Command; +use PHPCR\RepositoryInterface; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; -use PHPCR\RepositoryInterface; /** * Command to export a workspace to an XML file. * * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * * @author David Buchmann */ class WorkspaceExportCommand extends BaseCommand { /** - * {@inheritDoc} + * {@inheritdoc} */ protected function configure() { @@ -29,22 +28,21 @@ protected function configure() ->setName('phpcr:workspace:export') ->addArgument('filename', InputArgument::REQUIRED, 'The xml file to export to') ->addOption('path', 'p', InputOption::VALUE_OPTIONAL, 'Path of the node to export', '/') - ->addOption('skip_binary', null, InputOption::VALUE_OPTIONAL, 'Set to "yes" to skip binaries', "no") - ->addOption('recurse', null, InputOption::VALUE_OPTIONAL, 'Set to "no" to prevent recursion', "yes") + ->addOption('skip_binary', null, InputOption::VALUE_OPTIONAL, 'Set to "yes" to skip binaries', 'no') + ->addOption('recurse', null, InputOption::VALUE_OPTIONAL, 'Set to "no" to prevent recursion', 'yes') ->setDescription('Export nodes from the repository, either to the JCR system view format or the document view format') - ->setHelp(<<setHelp(<<<'EOF' 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 - ) - ; + ); } /** - * {@inheritDoc} + * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { diff --git a/src/PHPCR/Util/Console/Command/WorkspaceImportCommand.php b/src/PHPCR/Util/Console/Command/WorkspaceImportCommand.php index b6b8f5c..cf327c1 100644 --- a/src/PHPCR/Util/Console/Command/WorkspaceImportCommand.php +++ b/src/PHPCR/Util/Console/Command/WorkspaceImportCommand.php @@ -2,24 +2,23 @@ namespace PHPCR\Util\Console\Command; +use PHPCR\ImportUUIDBehaviorInterface; +use PHPCR\RepositoryInterface; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; -use PHPCR\RepositoryInterface; -use PHPCR\ImportUUIDBehaviorInterface; /** * Command to import a system or document view XML into the repository. * * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * * @author David Buchmann */ class WorkspaceImportCommand extends BaseCommand { /** - * {@inheritDoc} + * {@inheritdoc} */ protected function configure() { @@ -30,7 +29,7 @@ protected function configure() ->addArgument('filename', null, 'The xml file to import') ->addOption('parentpath', 'p', InputOption::VALUE_OPTIONAL, 'Repository path to the parent where to import the file contents', '/') ->setDescription('Import xml data into the repository, either in JCR system view format or arbitrary xml') - ->setHelp(<<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 @@ -40,12 +39,11 @@ protected function configure() If the parentpath option is set, the document is imported to that path. Otherwise the document is imported at the repository root. EOF - ) - ; + ); } /** - * {@inheritDoc} + * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { diff --git a/src/PHPCR/Util/Console/Command/WorkspaceListCommand.php b/src/PHPCR/Util/Console/Command/WorkspaceListCommand.php index 14312ca..967cbe9 100644 --- a/src/PHPCR/Util/Console/Command/WorkspaceListCommand.php +++ b/src/PHPCR/Util/Console/Command/WorkspaceListCommand.php @@ -6,32 +6,30 @@ use Symfony\Component\Console\Output\OutputInterface; /** - * A command to list all workspaces visible through the current session + * A command to list all workspaces visible through the current session. * * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * * @author Lukas Kahwe Smith */ class WorkspaceListCommand extends BaseCommand { /** - * {@inheritDoc} + * {@inheritdoc} */ protected function configure() { $this ->setName('phpcr:workspace:list') ->setDescription('List all available workspaces in the configured repository') - ->setHelp(<<setHelp(<<<'EOT' The workspace:list command lists all avaialable workspaces. EOT - ) - ; + ); } /** - * {@inheritDoc} + * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { @@ -39,7 +37,7 @@ protected function execute(InputInterface $input, OutputInterface $output) $workspaces = $session->getWorkspace()->getAccessibleWorkspaceNames(); - $output->writeln("The following ".count($workspaces)." workspaces are available:"); + $output->writeln('The following '.count($workspaces).' workspaces are available:'); foreach ($workspaces as $workspace) { $output->writeln($workspace); } diff --git a/src/PHPCR/Util/Console/Command/WorkspacePurgeCommand.php b/src/PHPCR/Util/Console/Command/WorkspacePurgeCommand.php index 14a70a2..487d013 100644 --- a/src/PHPCR/Util/Console/Command/WorkspacePurgeCommand.php +++ b/src/PHPCR/Util/Console/Command/WorkspacePurgeCommand.php @@ -2,10 +2,10 @@ namespace PHPCR\Util\Console\Command; -use Symfony\Component\Console\Input\InputOption; +use PHPCR\Util\NodeHelper; use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; -use PHPCR\Util\NodeHelper; /** * Command to remove all non-system nodes and properties in the workspace of @@ -13,13 +13,12 @@ * * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * * @author Daniel Leech */ class WorkspacePurgeCommand extends BaseCommand { /** - * {@inheritDoc} + * {@inheritdoc} */ protected function configure() { @@ -29,16 +28,15 @@ protected function configure() ->setName('phpcr:workspace:purge') ->setDescription('Remove all nodes from a workspace') ->addOption('force', null, InputOption::VALUE_NONE, 'Use to bypass the confirmation dialog') - ->setHelp(<<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 - ) - ; + ); } /** - * {@inheritDoc} + * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { diff --git a/src/PHPCR/Util/Console/Command/WorkspaceQueryCommand.php b/src/PHPCR/Util/Console/Command/WorkspaceQueryCommand.php index 8c4bbd0..f4d7fc1 100644 --- a/src/PHPCR/Util/Console/Command/WorkspaceQueryCommand.php +++ b/src/PHPCR/Util/Console/Command/WorkspaceQueryCommand.php @@ -2,9 +2,9 @@ namespace PHPCR\Util\Console\Command; -use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; /** @@ -13,14 +13,13 @@ * * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * * @author Daniel Barsotti * @author Daniel Leech */ class WorkspaceQueryCommand extends BaseCommand { /** - * {@inheritDoc} + * {@inheritdoc} */ protected function configure() { @@ -32,11 +31,11 @@ protected function configure() ->addOption('limit', null, InputOption::VALUE_OPTIONAL, 'The query limit', 0) ->addOption('offset', null, InputOption::VALUE_OPTIONAL, 'The query offset', 0) ->setDescription('Execute a JCR SQL2 statement') - ->setHelp("The query command executes a JCR query statement on the content repository"); + ->setHelp('The query command executes a JCR query statement on the content repository'); } /** - * {@inheritDoc} + * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { @@ -64,7 +63,7 @@ protected function execute(InputInterface $input, OutputInterface $output) $output->writeln("Results:\n"); foreach ($result as $i => $row) { - $output->writeln("\n".($i+1).'. Row (Path: '. $row->getPath() .', Score: '. $row->getScore() .'):'); + $output->writeln("\n".($i + 1).'. Row (Path: '.$row->getPath().', Score: '.$row->getScore().'):'); foreach ($row as $column => $value) { $output->writeln("$column: ".var_export($value, true)); } diff --git a/src/PHPCR/Util/Console/Helper/PhpcrConsoleDumperHelper.php b/src/PHPCR/Util/Console/Helper/PhpcrConsoleDumperHelper.php index 9e3a779..d7d3cdb 100644 --- a/src/PHPCR/Util/Console/Helper/PhpcrConsoleDumperHelper.php +++ b/src/PHPCR/Util/Console/Helper/PhpcrConsoleDumperHelper.php @@ -2,28 +2,27 @@ namespace PHPCR\Util\Console\Helper; -use Symfony\Component\Console\Helper\Helper; -use Symfony\Component\Console\Output\OutputInterface; use PHPCR\Util\Console\Helper\TreeDumper\ConsoleDumperNodeVisitor; use PHPCR\Util\Console\Helper\TreeDumper\ConsoleDumperPropertyVisitor; -use PHPCR\Util\TreeWalker; use PHPCR\Util\Console\Helper\TreeDumper\SystemNodeFilter; +use PHPCR\Util\TreeWalker; +use Symfony\Component\Console\Helper\Helper; +use Symfony\Component\Console\Output\OutputInterface; /** * Helper class to make the session instance available to console commands. * * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * */ 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); @@ -45,7 +44,7 @@ public function getTreeWalker(OutputInterface $output, $options) } /** - * {@inheritDoc} + * {@inheritdoc} */ public function getName() { diff --git a/src/PHPCR/Util/Console/Helper/PhpcrHelper.php b/src/PHPCR/Util/Console/Helper/PhpcrHelper.php index 719d0e9..a168f86 100644 --- a/src/PHPCR/Util/Console/Helper/PhpcrHelper.php +++ b/src/PHPCR/Util/Console/Helper/PhpcrHelper.php @@ -3,30 +3,29 @@ namespace PHPCR\Util\Console\Helper; use Exception; -use Symfony\Component\Console\Output\OutputInterface; -use Symfony\Component\Console\Helper\Helper; use PHPCR\NodeInterface; use PHPCR\PropertyInterface; use PHPCR\SessionInterface; +use Symfony\Component\Console\Helper\Helper; +use Symfony\Component\Console\Output\OutputInterface; /** * Helper class to make the session instance available to console commands. * * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * */ class PhpcrHelper extends Helper { /** - * The session bound to this helper + * The session bound to this helper. * * @var SessionInterface */ protected $session; /** - * Constructor + * Constructor. * * @param SessionInterface $session the session to use in commands */ @@ -36,7 +35,7 @@ public function __construct(SessionInterface $session) } /** - * Get the session + * Get the session. * * @return SessionInterface */ @@ -46,7 +45,7 @@ public function getSession() } /** - * {@inheritDoc} + * {@inheritdoc} */ public function getName() { @@ -65,12 +64,12 @@ public function getName() 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) { diff --git a/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperItemVisitor.php b/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperItemVisitor.php index 0984e4b..ddd1623 100644 --- a/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperItemVisitor.php +++ b/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperItemVisitor.php @@ -2,32 +2,32 @@ namespace PHPCR\Util\Console\Helper\TreeDumper; -use Symfony\Component\Console\Output\OutputInterface; use PHPCR\ItemVisitorInterface; +use Symfony\Component\Console\Output\OutputInterface; /** - * TODO: this should base on the TraversingItemVisitor + * TODO: this should base on the TraversingItemVisitor. * * @author Daniel Barsotti */ abstract class ConsoleDumperItemVisitor implements ItemVisitorInterface { /** - * Target for printing information + * Target for printing information. * * @var OutputInterface */ protected $output; /** - * Current depth in the tree + * Current depth in the tree. * * @var int */ protected $level = 0; /** - * Instantiate the console dumper visitor + * Instantiate the console dumper visitor. * * @param OutputInterface $output */ @@ -37,7 +37,7 @@ public function __construct(OutputInterface $output) } /** - * Set the current depth level for indention + * Set the current depth level for indention. * * @param int $level */ diff --git a/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperNodeVisitor.php b/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperNodeVisitor.php index 70bc0d9..f6f710d 100644 --- a/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperNodeVisitor.php +++ b/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperNodeVisitor.php @@ -3,31 +3,31 @@ namespace PHPCR\Util\Console\Helper\TreeDumper; use Exception; -use Symfony\Component\Console\Output\OutputInterface; use PHPCR\ItemInterface; use PHPCR\NodeInterface; +use Symfony\Component\Console\Output\OutputInterface; /** - * TODO: this should base on the TraversingItemVisitor + * TODO: this should base on the TraversingItemVisitor. * * @author Daniel Barsotti */ class ConsoleDumperNodeVisitor extends ConsoleDumperItemVisitor { /** - * Whether to print the UUIDs or not + * Whether to print the UUIDs or not. * * @var bool */ protected $identifiers; /** - * Show the full path for the node + * Show the full path for the node. */ protected $showFullPath; /** - * Instantiate the console dumper visitor + * Instantiate the console dumper visitor. * * @param OutputInterface $output * @param bool $identifiers whether to output the node UUID @@ -39,7 +39,7 @@ public function __construct(OutputInterface $output, $identifiers = false) } /** - * If to show the full path or not + * If to show the full path or not. * * @param bool $showFullPath */ @@ -57,7 +57,7 @@ public function setShowFullPath($showFullPath) */ public function visit(ItemInterface $item) { - if (! $item instanceof NodeInterface) { + if (!$item instanceof NodeInterface) { throw new Exception("Internal error: did not expect to visit a non-node object: $item"); } @@ -70,7 +70,7 @@ public function visit(ItemInterface $item) } $out = str_repeat(' ', $this->level) - . '' . $name . ''; + .''.$name.''; if ($this->identifiers) { $identifier = $item->getIdentifier(); if ($identifier) { diff --git a/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperPropertyVisitor.php b/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperPropertyVisitor.php index b2e896f..3cc4466 100644 --- a/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperPropertyVisitor.php +++ b/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperPropertyVisitor.php @@ -3,32 +3,32 @@ namespace PHPCR\Util\Console\Helper\TreeDumper; use Exception; -use Symfony\Component\Console\Output\OutputInterface; use PHPCR\ItemInterface; use PHPCR\PropertyInterface; use PHPCR\PropertyType; +use Symfony\Component\Console\Output\OutputInterface; /** - * TODO: this should base on the TraversingItemVisitor + * TODO: this should base on the TraversingItemVisitor. * * @author Daniel Barsotti */ class ConsoleDumperPropertyVisitor extends ConsoleDumperItemVisitor { /** - * Limit to cap lines at to avoid garbled output on long property values + * Limit to cap lines at to avoid garbled output on long property values. * * @var int */ protected $maxLineLength; /** - * Show the full path for each reference + * Show the full path for each reference. */ protected $expandReferences; /** - * Instantiate property visitor + * Instantiate property visitor. * * @param OutputInterface $output * @param array $options @@ -37,7 +37,7 @@ public function __construct(OutputInterface $output, $options = []) { $options = array_merge([ 'max_line_length' => 120, - 'ref_format' => 'uuid', + 'ref_format' => 'uuid', ], $options); parent::__construct($output); @@ -47,7 +47,7 @@ public function __construct(OutputInterface $output, $options = []) } /** - * Print information about this property + * Print information about this property. * * @param ItemInterface $item the property to visit * @@ -55,25 +55,25 @@ public function __construct(OutputInterface $output, $options = []) */ public function visit(ItemInterface $item) { - if (! $item instanceof PropertyInterface) { + 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)); } $value = $item->getString(); - if (! is_string($value)) { + if (!is_string($value)) { $value = print_r($value, true); } if (strlen($value) > $this->maxLineLength) { - $value = substr($value, 0, $this->maxLineLength) . '...'; + $value = substr($value, 0, $this->maxLineLength).'...'; } $referrers = []; if (in_array($item->getType(), [ PropertyType::WEAKREFERENCE, - PropertyType::REFERENCE + PropertyType::REFERENCE, ])) { $referenceStrings = []; @@ -92,7 +92,7 @@ public function visit(ItemInterface $item) $value = str_replace(["\n", "\t"], '', $value); - $this->output->writeln(str_repeat(' ', $this->level + 1) . '- ' . $item->getName() . ' = ' . $value); + $this->output->writeln(str_repeat(' ', $this->level + 1).'- '.$item->getName().' = '.$value); if (isset($referenceStrings)) { foreach ($referenceStrings as $referenceString) { diff --git a/src/PHPCR/Util/Console/Helper/TreeDumper/SystemNodeFilter.php b/src/PHPCR/Util/Console/Helper/TreeDumper/SystemNodeFilter.php index 96557eb..51c1cf6 100644 --- a/src/PHPCR/Util/Console/Helper/TreeDumper/SystemNodeFilter.php +++ b/src/PHPCR/Util/Console/Helper/TreeDumper/SystemNodeFilter.php @@ -4,8 +4,8 @@ use PHPCR\ItemInterface; use PHPCR\RepositoryException; -use PHPCR\Util\TreeWalkerFilterInterface; use PHPCR\Util\NodeHelper; +use PHPCR\Util\TreeWalkerFilterInterface; /** * Filter system properties and nodes based on their name. @@ -15,16 +15,16 @@ class SystemNodeFilter implements TreeWalkerFilterInterface { /** - * Checks whether this item is a system item + * Checks whether this item is a system item. * * @param ItemInterface $item * - * @return boolean - * * @throws RepositoryException + * + * @return bool */ public function mustVisit(ItemInterface $item) { - return ! NodeHelper::isSystemItem($item); + return !NodeHelper::isSystemItem($item); } } diff --git a/src/PHPCR/Util/NodeHelper.php b/src/PHPCR/Util/NodeHelper.php index 087068c..95d7459 100644 --- a/src/PHPCR/Util/NodeHelper.php +++ b/src/PHPCR/Util/NodeHelper.php @@ -5,30 +5,29 @@ use InvalidArgumentException; use PHPCR\ItemExistsException; use PHPCR\ItemInterface; +use PHPCR\ItemNotFoundException; use PHPCR\Lock\LockException; +use PHPCR\NamespaceException; use PHPCR\NodeInterface; use PHPCR\NodeType\ConstraintViolationException; use PHPCR\PathNotFoundException; use PHPCR\PropertyInterface; -use PHPCR\SessionInterface; use PHPCR\RepositoryException; -use PHPCR\ItemNotFoundException; -use PHPCR\NamespaceException; +use PHPCR\SessionInterface; use PHPCR\Version\VersionException; /** - * Helper with only static methods to work with PHPCR nodes + * Helper with only static methods to work with PHPCR nodes. * * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * * @author Daniel Barsotti * @author David Buchmann */ class NodeHelper { /** - * Do not create an instance of this class + * Do not create an instance of this class. */ private function __construct() { @@ -40,8 +39,6 @@ private function __construct() * @param SessionInterface $session the PHPCR session to create the path * @param string $path full path, like /content/jobs/data * - * @return NodeInterface the last node of the path, i.e. data - * * @throws InvalidArgumentException * @throws RepositoryException * @throws PathNotFoundException @@ -49,6 +46,8 @@ private function __construct() * @throws LockException * @throws ConstraintViolationException * @throws VersionException + * + * @return NodeInterface the last node of the path, i.e. data */ public static function createPath(SessionInterface $session, $path) { @@ -77,7 +76,7 @@ public static function createPath(SessionInterface $session, $path) * node which you are not allowed to remove. * * @param SessionInterface $session the session to remove all children of - * the root node + * the root node * * @throws RepositoryException * @@ -89,21 +88,21 @@ public static function purgeWorkspace(SessionInterface $session) /** @var $property PropertyInterface */ foreach ($root->getProperties() as $property) { - if (! self::isSystemItem($property)) { + if (!self::isSystemItem($property)) { $property->remove(); } } /** @var $node NodeInterface */ foreach ($root->getNodes() as $node) { - if (! self::isSystemItem($node)) { + if (!self::isSystemItem($node)) { $node->remove(); } } } /** - * Kept as alias of purgeWorkspace for BC compatibility + * Kept as alias of purgeWorkspace for BC compatibility. * * @param SessionInterface $session * @@ -123,9 +122,9 @@ public static function deleteAllNodes(SessionInterface $session) * * @param ItemInterface $item * - * @return boolean 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) { @@ -138,7 +137,7 @@ public static function isSystemItem(ItemInterface $item) } /** - * Helper method to implement NodeInterface::addNodeAutoNamed + * Helper method to implement NodeInterface::addNodeAutoNamed. * * This method only checks for valid namespaces. All other exceptions must * be thrown by the addNodeAutoNamed implementation. @@ -148,13 +147,12 @@ public static function isSystemItem(ItemInterface $item) * @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. - * + * @throws NamespaceException if a namespace prefix is provided in the + * $nameHint which does not exist and this implementation performs + * this validation immediately. * @throws RepositoryException + * + * @return string A valid node name for this node */ public static function generateAutoNodeName($usedNames, $namespaces, $defaultNamespace, $nameHint = null) { @@ -164,7 +162,7 @@ public static function generateAutoNodeName($usedNames, $namespaces, $defaultNam * null: The new node name will be generated entirely by the repository. */ if (null === $nameHint) { - return self::generateWithPrefix($usedNames, $defaultNamespace . ':'); + return self::generateWithPrefix($usedNames, $defaultNamespace.':'); } /* @@ -180,16 +178,16 @@ public static function generateAutoNodeName($usedNames, $namespaces, $defaultNam * "somePrefix:" where somePrefix is a syntactically * valid namespace prefix */ - if (':' === $nameHint[strlen($nameHint)-1] + if (':' === $nameHint[strlen($nameHint) - 1] && substr_count($nameHint, ':') === 1 && preg_match('#^[a-zA-Z][a-zA-Z0-9]*:$#', $nameHint) ) { $prefix = substr($nameHint, 0, -1); - if (! isset($namespaces[$prefix])) { + if (!isset($namespaces[$prefix])) { throw new NamespaceException("Invalid nameHint '$nameHint'"); } - return self::generateWithPrefix($usedNames, $prefix . ':'); + return self::generateWithPrefix($usedNames, $prefix.':'); } /* @@ -198,15 +196,15 @@ public static function generateAutoNodeName($usedNames, $namespaces, $defaultNam */ if (strlen($nameHint) > 2 && '{' === $nameHint[0] - && '}' === $nameHint[strlen($nameHint)-1] + && '}' === $nameHint[strlen($nameHint) - 1] && filter_var(substr($nameHint, 1, -1), FILTER_VALIDATE_URL) ) { $prefix = array_search(substr($nameHint, 1, -1), $namespaces); - if (! $prefix) { + if (!$prefix) { throw new NamespaceException("Invalid nameHint '$nameHint'"); } - return self::generateWithPrefix($usedNames, $prefix . ':'); + return self::generateWithPrefix($usedNames, $prefix.':'); } /* @@ -223,11 +221,11 @@ public static function generateAutoNodeName($usedNames, $namespaces, $defaultNam if (preg_match('#^[a-zA-Z][a-zA-Z0-9]*$#', $prefix) && preg_match('#^[a-zA-Z][a-zA-Z0-9]*$#', $name) ) { - if (! isset($namespaces[$prefix])) { + if (!isset($namespaces[$prefix])) { throw new NamespaceException("Invalid nameHint '$nameHint'"); } - return self::generateWithPrefix($usedNames, $prefix . ':', $name); + return self::generateWithPrefix($usedNames, $prefix.':', $name); } } @@ -246,11 +244,11 @@ public static function generateAutoNodeName($usedNames, $namespaces, $defaultNam $name = $matches[2]; $prefix = array_search($ns, $namespaces); - if (! $prefix) { + if (!$prefix) { throw new NamespaceException("Invalid nameHint '$nameHint'"); } - return self::generateWithPrefix($usedNames, $prefix . ':', $name); + return self::generateWithPrefix($usedNames, $prefix.':', $name); } throw new RepositoryException("Invalid nameHint '$nameHint'"); @@ -269,7 +267,7 @@ public static function generateAutoNodeName($usedNames, $namespaces, $defaultNam private static function generateWithPrefix($usedNames, $prefix, $namepart = '') { do { - $name = $prefix . $namepart . mt_rand(); + $name = $prefix.$namepart.mt_rand(); } while (isset($usedNames[$name])); return $name; @@ -290,7 +288,7 @@ 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) { @@ -345,12 +343,12 @@ public static function calculateOrderBefore(array $old, array $new) * * @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 - * - * @return array The updated $nodes array with new order + * 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 */ public static function orderBeforeArray($name, $destination, $list) { diff --git a/src/PHPCR/Util/PathHelper.php b/src/PHPCR/Util/PathHelper.php index d922b4a..ddd7af6 100644 --- a/src/PHPCR/Util/PathHelper.php +++ b/src/PHPCR/Util/PathHelper.php @@ -6,22 +6,22 @@ use PHPCR\RepositoryException; /** - * Static methods to handle path operations for PHPCR implementations + * Static methods to handle path operations for PHPCR implementations. * * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * * @author David Buchmann */ class PathHelper { /** - * Do not create an instance of this class + * Do not create an instance of this class. */ // @codeCoverageIgnoreStart private function __construct() { } + // @codeCoverageIgnoreEnd /** @@ -32,17 +32,17 @@ private function __construct() * * Non-normalized paths are considered invalid, i.e. /node/. is /node and /my/node/.. is /my * - * @param string $path The path to validate - * @param bool $destination whether this is a destination path (by copy or - * 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 string $path The path to validate + * @param bool $destination whether this is a destination path (by copy or + * 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. - * 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 + * 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 */ public static function assertValidAbsolutePath($path, $destination = false, $throw = true, $namespacePrefixes = false) { @@ -65,6 +65,7 @@ public static function assertValidAbsolutePath($path, $destination = false, $thr if (!$throw) { return false; } + throw new NamespaceException(sprintf('Unknown namespace prefix(es) (%s) in path %s', implode(' and ', $unknown), $path)); } } @@ -83,13 +84,13 @@ public static function assertValidAbsolutePath($path, $destination = false, $thr * encode and decode characters that are not natively allowed by a storage * engine. * - * @param string $name The name to check - * @param boolean $throw whether to throw an exception on validation errors. - * - * @return bool true if valid, false if not valid and $throw was false + * @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 * + * @return bool true if valid, false if not valid and $throw was false + * * @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) @@ -118,19 +119,19 @@ public static function assertValidLocalName($name, $throw = true) * * @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. - * @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 + * 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 is not a valid absolute path and - * $throw is true + * $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); + return self::error('Expected string but got '.gettype($path), $throw); } if (strlen($path) === 0) { return self::error('Path must not be of zero length', $throw); @@ -144,7 +145,7 @@ public static function normalizePath($path, $destination = false, $throw = true) return self::error("Not an absolute path '$path'", $throw); } - $finalParts= []; + $finalParts = []; $parts = explode('/', $path); foreach ($parts as $pathPart) { @@ -162,12 +163,12 @@ public static function normalizePath($path, $destination = false, $throw = true) break; } } - $normalizedPath = count($finalParts) > 1 ? + $normalizedPath = count($finalParts) > 1 ? implode('/', $finalParts) : '/' // first element is always the empty-name root element. this might have been a path like /x/.. - ; +; - if (! self::assertValidAbsolutePath($normalizedPath, $destination, $throw)) { + if (!self::assertValidAbsolutePath($normalizedPath, $destination, $throw)) { return false; } @@ -181,23 +182,23 @@ 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. - * @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 + * 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 + * absolute path and $throw is true + * + * @return string The normalized, absolute path or false if $throw was + * false and the path invalid */ public static function absolutizePath($path, $context, $destination = false, $throw = true) { if (!is_string($path) && !is_numeric($path)) { - return self::error('Expected string path but got ' . gettype($path), $throw); + 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); + return self::error('Expected string context but got '.gettype($context), $throw); } if (strlen($path) === 0) { return self::error('Path must not be of zero length', $throw); @@ -219,7 +220,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 +262,9 @@ public static function getParentPath($path) * * @param string $path a valid absolute path, like /content/jobs/data * - * @return string the name, that is the string after the last "/" - * * @throws RepositoryException + * + * @return string the name, that is the string after the last "/" */ public static function getNodeName($path) { @@ -280,13 +281,13 @@ public static function getNodeName($path) /** * Return the localname of the node at the given path. - * The local name is the node name minus the namespace + * The local name is the node name minus the namespace. * * @param string $path a valid absolute path * - * @return string The localname - * * @throws RepositoryException + * + * @return string The localname */ public static function getLocalNodeName($path) { @@ -301,11 +302,11 @@ public static function getLocalNodeName($path) } /** - * Get the depth of the path, ignore trailing slashes, root starts counting at 0 + * Get the depth of the path, ignore trailing slashes, root starts counting at 0. * * @param string $path a valid absolute path, like /content/jobs/data * - * @return integer with the path depth + * @return int with the path depth */ public static function getPathDepth($path) { @@ -316,12 +317,12 @@ public static function getPathDepth($path) * If $throw is true, throw a RepositoryException with $msg. Otherwise * return false. * - * @param string $msg the exception message to use in case of throw being true - * @param boolean $throw whether to throw the exception or return false - * - * @return boolean false + * @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 */ private static function error($msg, $throw) { diff --git a/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php b/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php index 09fef6d..fb252b1 100644 --- a/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php +++ b/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php @@ -14,14 +14,14 @@ abstract class BaseQomToSqlQueryConverter { /** - * The generator to use + * The generator to use. * * @var BaseSqlGenerator */ protected $generator; /** - * Instantiate the converter + * Instantiate the converter. * * @param BaseSqlGenerator $generator */ @@ -34,7 +34,7 @@ public function __construct(BaseSqlGenerator $generator) * Query ::= 'SELECT' columns * 'FROM' Source * ['WHERE' Constraint] - * ['ORDER BY' orderings] + * ['ORDER BY' orderings]. * * @param QOM\QueryObjectModelInterface $query * @@ -59,7 +59,7 @@ public function convert(QOM\QueryObjectModelInterface $query) } /** - * Convert a source. This is different between SQL1 and SQL2 + * Convert a source. This is different between SQL1 and SQL2. * * @param QOM\SourceInterface $source * @@ -78,6 +78,7 @@ abstract protected function convertConstraint(QOM\ConstraintInterface $constrain /** * Convert dynamic operand. This is different between SQL1 and SQL2. + * * @param QOM\DynamicOperandInterface $operand * * @return mixed @@ -86,9 +87,10 @@ abstract protected function convertDynamicOperand(QOM\DynamicOperandInterface $o /** * Selector ::= nodeTypeName ['AS' selectorName] - * nodeTypeName ::= Name + * nodeTypeName ::= Name. + * + * @param QOM\SelectorInterface $selector * - * @param QOM\SelectorInterface $selector * @return string */ protected function convertSelector(QOM\SelectorInterface $selector) @@ -97,7 +99,7 @@ protected function convertSelector(QOM\SelectorInterface $selector) } /** - * Comparison ::= DynamicOperand Operator StaticOperand + * Comparison ::= DynamicOperand Operator StaticOperand. * * Operator ::= EqualTo | NotEqualTo | LessThan | * LessThanOrEqualTo | GreaterThan | @@ -110,7 +112,8 @@ protected function convertSelector(QOM\SelectorInterface $selector) * GreaterThanOrEqualTo ::= '>=' * Like ::= 'LIKE' * - * @param QOM\ComparisonInterface $comparison + * @param QOM\ComparisonInterface $comparison + * * @return string */ protected function convertComparison(QOM\ComparisonInterface $comparison) @@ -127,12 +130,13 @@ protected function convertComparison(QOM\ComparisonInterface $comparison) * selectorName'.'propertyName 'IS NOT NULL' | * propertyName 'IS NOT NULL' If only one * selector exists in - * this query + * this query. * * Note: The negation, 'NOT x IS NOT NULL' * can be written 'x IS NULL' * - * @param QOM\PropertyExistenceInterface $constraint + * @param QOM\PropertyExistenceInterface $constraint + * * @return string */ protected function convertPropertyExistence(QOM\PropertyExistenceInterface $constraint) @@ -149,9 +153,10 @@ protected function convertPropertyExistence(QOM\PropertyExistenceInterface $cons * FullTextSearchExpression ')' * // If only one selector exists in this query, * explicit specification of the selectorName - * preceding the propertyName is optional + * preceding the propertyName is optional. + * + * @param QOM\FullTextSearchInterface $constraint * - * @param QOM\FullTextSearchInterface $constraint * @return string */ protected function convertFullTextSearch(QOM\FullTextSearchInterface $constraint) @@ -162,9 +167,10 @@ protected function convertFullTextSearch(QOM\FullTextSearchInterface $constraint } /** - * FullTextSearchExpression ::= BindVariable | ''' FullTextSearchLiteral ''' + * FullTextSearchExpression ::= BindVariable | ''' FullTextSearchLiteral '''. + * + * @param string $expr * - * @param string $expr * @return string */ protected function convertFullTextSearchExpression($expr) @@ -179,7 +185,7 @@ protected function convertFullTextSearchExpression($expr) } /** - * StaticOperand ::= Literal | BindVariableValue + * StaticOperand ::= Literal | BindVariableValue. * * Literal ::= CastLiteral | UncastLiteral * CastLiteral ::= 'CAST(' UncastLiteral ' AS ' PropertyType ')' @@ -193,11 +199,11 @@ protected function convertFullTextSearchExpression($expr) * BindVariableValue ::= '$'bindVariableName * bindVariableName ::= Prefix * - * @param QOM\StaticOperandInterface $operand - * - * @return string + * @param QOM\StaticOperandInterface $operand * * @throws InvalidArgumentException + * + * @return string */ protected function convertStaticOperand(QOM\StaticOperandInterface $operand) { @@ -213,9 +219,10 @@ protected function convertStaticOperand(QOM\StaticOperandInterface $operand) } /** - * PropertyValue ::= [selectorName'.'] propertyName // If only one selector exists + * PropertyValue ::= [selectorName'.'] propertyName // If only one selector exists. + * + * @param QOM\PropertyValueInterface $value * - * @param QOM\PropertyValueInterface $value * @return string */ protected function convertPropertyValue(QOM\PropertyValueInterface $value) @@ -230,9 +237,10 @@ protected function convertPropertyValue(QOM\PropertyValueInterface $value) * Ordering ::= DynamicOperand [Order] * Order ::= Ascending | Descending * Ascending ::= 'ASC' - * Descending ::= 'DESC' + * Descending ::= 'DESC'. + * + * @param QOM\OrderingInterface[] $orderings * - * @param QOM\OrderingInterface[] $orderings * @return string */ protected function convertOrderings(array $orderings) @@ -251,7 +259,7 @@ 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 + * simplePath ::= A JCR Name that contains only SQL-legal characters. * * @param string $path * @@ -264,7 +272,7 @@ protected function convertPath($path) /** * BindVariableValue ::= '$'bindVariableName - * bindVariableName ::= Prefix + * bindVariableName ::= Prefix. * * @param string $var * @@ -276,7 +284,7 @@ protected function convertBindVariable($var) } /** - * Literal ::= CastLiteral | UncastLiteral + * Literal ::= CastLiteral | UncastLiteral. * * @param mixed $literal * @@ -294,9 +302,10 @@ protected function convertLiteral($literal) * (selectorName'.*') // If only one selector exists * selectorName ::= Name * propertyName ::= Name - * columnName ::= Name + * columnName ::= Name. + * + * @param QOM\ColumnInterface[] $columns * - * @param QOM\ColumnInterface[] $columns * @return string */ protected function convertColumns(array $columns) diff --git a/src/PHPCR/Util/QOM/BaseSqlGenerator.php b/src/PHPCR/Util/QOM/BaseSqlGenerator.php index 6e34e59..027318e 100644 --- a/src/PHPCR/Util/QOM/BaseSqlGenerator.php +++ b/src/PHPCR/Util/QOM/BaseSqlGenerator.php @@ -3,8 +3,8 @@ namespace PHPCR\Util\QOM; use DateTime; -use PHPCR\Query\QOM\QueryObjectModelConstantsInterface as Constants; use PHPCR\PropertyType; +use PHPCR\Query\QOM\QueryObjectModelConstantsInterface as Constants; use PHPCR\Util\ValueConverter; /** @@ -12,7 +12,6 @@ * * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * */ abstract class BaseSqlGenerator { @@ -30,7 +29,7 @@ public function __construct(ValueConverter $valueConverter) * Query ::= 'SELECT' columns * 'FROM' Source * ['WHERE' Constraint] - * ['ORDER BY' orderings] + * ['ORDER BY' orderings]. * * @param string $source * @param string $columns @@ -55,7 +54,7 @@ public function evalQuery($source, $columns, $constraint = '', $orderings = '') } /** - * And ::= constraint1 'AND' constraint2 + * And ::= constraint1 'AND' constraint2. * * @param string $constraint1 * @param string $constraint2 @@ -68,7 +67,7 @@ public function evalAnd($constraint1, $constraint2) } /** - * Or ::= constraint1 'OR' constraint2 + * Or ::= constraint1 'OR' constraint2. * * @param string $constraint1 * @param string $constraint2 @@ -81,7 +80,7 @@ public function evalOr($constraint1, $constraint2) } /** - * Not ::= 'NOT' Constraint + * Not ::= 'NOT' Constraint. * * @param string $constraint * @@ -93,7 +92,7 @@ public function evalNot($constraint) } /** - * Comparison ::= DynamicOperand Operator StaticOperand + * Comparison ::= DynamicOperand Operator StaticOperand. * * @param string $operand1 * @param string $operator @@ -109,7 +108,7 @@ public function evalComparison($operand1, $operator, $operand2) /** * Operator ::= EqualTo | NotEqualTo | LessThan | * LessThanOrEqualTo | GreaterThan | - * GreaterThanOrEqualTo | Like + * GreaterThanOrEqualTo | Like. * * @param string $operator * @@ -138,7 +137,7 @@ public function evalOperator($operator) } /** - * LowerCase ::= 'LOWER(' DynamicOperand ')' + * LowerCase ::= 'LOWER(' DynamicOperand ')'. * * @param string $operand * @@ -150,7 +149,7 @@ public function evalLower($operand) } /** - * LowerCase ::= 'UPPER(' DynamicOperand ')' + * LowerCase ::= 'UPPER(' DynamicOperand ')'. * * @param string $operand * @@ -162,7 +161,7 @@ public function evalUpper($operand) } /** - * orderings ::= Ordering {',' Ordering} + * orderings ::= Ordering {',' Ordering}. * * @param $orderings * @@ -184,7 +183,7 @@ public function evalOrderings($orderings) } /** - * Ordering ::= DynamicOperand [Order] + * Ordering ::= DynamicOperand [Order]. * * @param $operand * @param $order @@ -199,7 +198,7 @@ public function evalOrdering($operand, $order) /** * Order ::= Ascending | Descending * Ascending ::= 'ASC' - * Descending ::= 'DESC' + * Descending ::= 'DESC'. * * @param $order * @@ -219,7 +218,7 @@ public function evalOrder($order) /** * BindVariableValue ::= '$'bindVariableName - * bindVariableName ::= Prefix + * bindVariableName ::= Prefix. * * @param $var * @@ -227,7 +226,7 @@ public function evalOrder($order) */ public function evalBindVariable($var) { - return '$' . $var; + return '$'.$var; } /** @@ -242,8 +241,8 @@ public function evalBindVariable($var) public function evalFullText($string) { $illegalCharacters = [ - '!' => '\\!', '(' => '\\(', ':' => '\\:', '^' => '\\^', - '[' => '\\[', ']' => '\\]', '{' => '\\{', '}' => '\\}', + '!' => '\\!', '(' => '\\(', ':' => '\\:', '^' => '\\^', + '[' => '\\[', ']' => '\\]', '{' => '\\{', '}' => '\\}', '\"' => '\\\"', '?' => '\\?', "'" => "''", ]; @@ -251,7 +250,7 @@ public function evalFullText($string) } /** - * Literal ::= CastLiteral | UncastLiteral + * Literal ::= CastLiteral | UncastLiteral. * * @param mixed $literal * diff --git a/src/PHPCR/Util/QOM/NotSupportedConstraintException.php b/src/PHPCR/Util/QOM/NotSupportedConstraintException.php index 23a67e8..223e850 100644 --- a/src/PHPCR/Util/QOM/NotSupportedConstraintException.php +++ b/src/PHPCR/Util/QOM/NotSupportedConstraintException.php @@ -13,7 +13,7 @@ class NotSupportedConstraintException extends RuntimeException { /** - * Create the exception with an explaining message + * Create the exception with an explaining message. * * @param string $constraint the constraint expression that is not supported */ diff --git a/src/PHPCR/Util/QOM/NotSupportedOperandException.php b/src/PHPCR/Util/QOM/NotSupportedOperandException.php index b0c369c..bc7f317 100644 --- a/src/PHPCR/Util/QOM/NotSupportedOperandException.php +++ b/src/PHPCR/Util/QOM/NotSupportedOperandException.php @@ -13,7 +13,7 @@ class NotSupportedOperandException extends RuntimeException { /** - * Create the exception with an explaining message + * Create the exception with an explaining message. * * @param string $operand the constraint expression that is not supported */ diff --git a/src/PHPCR/Util/QOM/QomToSql1QueryConverter.php b/src/PHPCR/Util/QOM/QomToSql1QueryConverter.php index 7962fff..f6c327e 100644 --- a/src/PHPCR/Util/QOM/QomToSql1QueryConverter.php +++ b/src/PHPCR/Util/QOM/QomToSql1QueryConverter.php @@ -14,12 +14,13 @@ class QomToSql1QueryConverter extends BaseQomToSqlQueryConverter { /** - * Source ::= Selector + * Source ::= Selector. * - * @param QOM\SourceInterface $source - * @return string + * @param QOM\SourceInterface $source * * @throws InvalidArgumentException + * + * @return string */ protected function convertSource(QOM\SourceInterface $source) { @@ -33,18 +34,18 @@ protected function convertSource(QOM\SourceInterface $source) /** * Constraint ::= And | Or | Not | Comparison | * PropertyExistence | FullTextSearch | - * SameNode | ChildNode | DescendantNode + * SameNode | ChildNode | DescendantNode. * * And ::= constraint1 'AND' constraint2 * Or ::= constraint1 'OR' constraint2 * Not ::= 'NOT' Constraint * - * @param QOM\ConstraintInterface $constraint - * - * @return string + * @param QOM\ConstraintInterface $constraint * * @throws InvalidArgumentException * @throws NotSupportedConstraintException + * + * @return string */ protected function convertConstraint(QOM\ConstraintInterface $constraint) { @@ -90,21 +91,22 @@ protected function convertConstraint(QOM\ConstraintInterface $constraint) // This should not happen, but who knows... $class = get_class($constraint); + throw new InvalidArgumentException("Invalid operand: $class"); } /** - * DynamicOperand ::= PropertyValue | LowerCase | UpperCase + * DynamicOperand ::= PropertyValue | LowerCase | UpperCase. * * LowerCase ::= 'LOWER(' DynamicOperand ')' * UpperCase ::= 'UPPER(' DynamicOperand ')' * - * @param QOM\DynamicOperandInterface $operand - * - * @return string + * @param QOM\DynamicOperandInterface $operand * * @throws NotSupportedOperandException * @throws InvalidArgumentException + * + * @return string */ protected function convertDynamicOperand(QOM\DynamicOperandInterface $operand) { diff --git a/src/PHPCR/Util/QOM/QomToSql2QueryConverter.php b/src/PHPCR/Util/QOM/QomToSql2QueryConverter.php index 45f2601..aec6a6d 100644 --- a/src/PHPCR/Util/QOM/QomToSql2QueryConverter.php +++ b/src/PHPCR/Util/QOM/QomToSql2QueryConverter.php @@ -14,13 +14,13 @@ class QomToSql2QueryConverter extends BaseQomToSqlQueryConverter { /** - * Source ::= Selector | Join + * Source ::= Selector | Join. * * @param QOM\SourceInterface $source * - * @return string - * * @throws InvalidArgumentException + * + * @return string */ protected function convertSource(QOM\SourceInterface $source) { @@ -38,14 +38,15 @@ protected function convertSource(QOM\SourceInterface $source) * Join ::= left [JoinType] 'JOIN' right 'ON' JoinCondition * // If JoinType is omitted INNER is assumed. * left ::= Source - * right ::= Source + * right ::= Source. * * JoinType ::= Inner | LeftOuter | RightOuter * Inner ::= 'INNER' * LeftOuter ::= 'LEFT OUTER' * RightOuter ::= 'RIGHT OUTER' * - * @param QOM\JoinInterface $join + * @param QOM\JoinInterface $join + * * @return string */ protected function convertJoin(QOM\JoinInterface $join) @@ -61,13 +62,13 @@ protected function convertJoin(QOM\JoinInterface $join) * JoinCondition ::= EquiJoinCondition | * SameNodeJoinCondition | * ChildNodeJoinCondition | - * DescendantNodeJoinCondition + * DescendantNodeJoinCondition. * - * @param QOM\JoinConditionInterface $condition - * - * @return string + * @param QOM\JoinConditionInterface $condition * * @throws InvalidArgumentException + * + * @return string */ protected function convertJoinCondition(QOM\JoinConditionInterface $condition) { @@ -93,9 +94,10 @@ protected function convertJoinCondition(QOM\JoinConditionInterface $condition) * selector1Name ::= selectorName * selector2Name ::= selectorName * property1Name ::= propertyName - * property2Name ::= propertyName + * property2Name ::= propertyName. + * + * @param QOM\EquiJoinConditionInterface $condition * - * @param QOM\EquiJoinConditionInterface $condition * @return string */ protected function convertEquiJoinCondition(QOM\EquiJoinConditionInterface $condition) @@ -112,9 +114,10 @@ protected function convertEquiJoinCondition(QOM\EquiJoinConditionInterface $cond * 'ISSAMENODE(' selector1Name ',' * selector2Name * [',' selector2Path] ')' - * selector2Path ::= Path + * selector2Path ::= Path. + * + * @param QOM\SameNodeJoinConditionInterface $condition * - * @param QOM\SameNodeJoinConditionInterface $condition * @return string */ protected function convertSameNodeJoinCondition(QOM\SameNodeJoinConditionInterface $condition) @@ -130,9 +133,10 @@ protected function convertSameNodeJoinCondition(QOM\SameNodeJoinConditionInterfa * 'ISCHILDNODE(' childSelectorName ',' * parentSelectorName ')' * childSelectorName ::= selectorName - * parentSelectorName ::= selectorName + * parentSelectorName ::= selectorName. + * + * @param QOM\ChildNodeJoinConditionInterface $condition * - * @param QOM\ChildNodeJoinConditionInterface $condition * @return string */ protected function convertChildNodeJoinCondition(QOM\ChildNodeJoinConditionInterface $condition) @@ -147,9 +151,10 @@ protected function convertChildNodeJoinCondition(QOM\ChildNodeJoinConditionInter * 'ISDESCENDANTNODE(' descendantSelectorName ',' * ancestorSelectorName ')' * descendantSelectorName ::= selectorName - * ancestorSelectorName ::= selectorName + * ancestorSelectorName ::= selectorName. + * + * @param QOM\DescendantNodeJoinConditionInterface $condition * - * @param QOM\DescendantNodeJoinConditionInterface $condition * @return string */ protected function convertDescendantNodeJoinCondition(QOM\DescendantNodeJoinConditionInterface $condition) @@ -162,7 +167,7 @@ protected function convertDescendantNodeJoinCondition(QOM\DescendantNodeJoinCond /** * Constraint ::= And | Or | Not | Comparison | * PropertyExistence | FullTextSearch | - * SameNode | ChildNode | DescendantNode + * SameNode | ChildNode | DescendantNode. * * And ::= constraint1 'AND' constraint2 * Or ::= constraint1 'OR' constraint2 @@ -180,11 +185,11 @@ protected function convertDescendantNodeJoinCondition(QOM\DescendantNodeJoinCond * // If only one selector exists in this query, explicit * specification of the selectorName is optional * - * @param QOM\ConstraintInterface $constraint - * - * @return string + * @param QOM\ConstraintInterface $constraint * * @throws InvalidArgumentException + * + * @return string */ protected function convertConstraint(QOM\ConstraintInterface $constraint) { @@ -233,13 +238,13 @@ 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)); } /** * DynamicOperand ::= PropertyValue | Length | NodeName | * NodeLocalName | FullTextSearchScore | - * LowerCase | UpperCase + * LowerCase | UpperCase. * * Length ::= 'LENGTH(' PropertyValue ')' * NodeName ::= 'NAME(' [selectorName] ')' // If only one selector exists @@ -248,11 +253,11 @@ protected function convertConstraint(QOM\ConstraintInterface $constraint) * LowerCase ::= 'LOWER(' DynamicOperand ')' * UpperCase ::= 'UPPER(' DynamicOperand ')' * - * @param QOM\DynamicOperandInterface $operand - * - * @return string + * @param QOM\DynamicOperandInterface $operand * * @throws InvalidArgumentException + * + * @return string */ protected function convertDynamicOperand(QOM\DynamicOperandInterface $operand) { diff --git a/src/PHPCR/Util/QOM/QueryBuilder.php b/src/PHPCR/Util/QOM/QueryBuilder.php index 7597190..23c6c12 100644 --- a/src/PHPCR/Util/QOM/QueryBuilder.php +++ b/src/PHPCR/Util/QOM/QueryBuilder.php @@ -4,15 +4,15 @@ use InvalidArgumentException; use PHPCR\Query\QOM\ColumnInterface; -use PHPCR\Query\QOM\OrderingInterface; -use PHPCR\Query\QOM\QueryObjectModelFactoryInterface; -use PHPCR\Query\QOM\DynamicOperandInterface; use PHPCR\Query\QOM\ConstraintInterface; -use PHPCR\Query\QOM\SourceInterface; +use PHPCR\Query\QOM\DynamicOperandInterface; use PHPCR\Query\QOM\JoinConditionInterface; +use PHPCR\Query\QOM\OrderingInterface; use PHPCR\Query\QOM\QueryObjectModelConstantsInterface; -use PHPCR\Query\QueryInterface; +use PHPCR\Query\QOM\QueryObjectModelFactoryInterface; use PHPCR\Query\QOM\QueryObjectModelInterface; +use PHPCR\Query\QOM\SourceInterface; +use PHPCR\Query\QueryInterface; use PHPCR\Query\QueryResultInterface; use RuntimeException; @@ -21,7 +21,6 @@ * * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * * @author Nacho Martín * @author Guilherme Blanco * @author Benjamin Eberlei @@ -33,7 +32,7 @@ class QueryBuilder const STATE_CLEAN = 1; /** - * @var integer The state of the query object. Can be dirty or clean. + * @var int The state of the query object. Can be dirty or clean. */ private $state = self::STATE_CLEAN; @@ -43,12 +42,12 @@ class QueryBuilder private $qomFactory; /** - * @var integer The maximum number of results to retrieve. + * @var int The maximum number of results to retrieve. */ private $firstResult = null; /** - * @var integer The maximum number of results to retrieve. + * @var int The maximum number of results to retrieve. */ private $maxResults = null; @@ -73,7 +72,7 @@ class QueryBuilder private $source = null; /** - * QOM tree + * QOM tree. * * @var QueryObjectModelInterface */ @@ -85,7 +84,7 @@ class QueryBuilder private $params = []; /** - * Initializes a new QueryBuilder + * Initializes a new QueryBuilder. * * @param QueryObjectModelFactoryInterface $qomFactory */ @@ -95,14 +94,14 @@ public function __construct(QueryObjectModelFactoryInterface $qomFactory) } /** - * Get a query builder instance from an existing query + * 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. - * * @throws InvalidArgumentException + * + * @return QueryBuilder This QueryBuilder instance. */ public function setFromQuery($statement, $language) { @@ -125,7 +124,7 @@ public function setFromQuery($statement, $language) } /** - * Get the associated QOMFactory for this query builder + * Get the associated QOMFactory for this query builder. * * @return QueryObjectModelFactoryInterface */ @@ -135,7 +134,7 @@ public function getQOMFactory() } /** - * Shortcut for getQOMFactory() + * Shortcut for getQOMFactory(). */ public function qomf() { @@ -145,7 +144,7 @@ public function qomf() /** * sets the position of the first result to retrieve (the "offset"). * - * @param integer $firstResult The First result to return. + * @param int $firstResult The First result to return. * * @return QueryBuilder This QueryBuilder instance. */ @@ -160,7 +159,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 integer The position of the first result. + * @return int The position of the first result. */ public function getFirstResult() { @@ -168,10 +167,9 @@ public function getFirstResult() } /** - * * Sets the maximum number of results to retrieve (the "limit"). * - * @param integer $maxResults The maximum number of results to retrieve. + * @param int $maxResults The maximum number of results to retrieve. * * @return QueryBuilder This QueryBuilder instance. */ @@ -186,7 +184,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 integer Maximum number of results. + * @return int Maximum number of results. */ public function getMaxResults() { @@ -209,9 +207,9 @@ public function getOrderings() * @param DynamicOperandInterface $sort The ordering expression. * @param string $order The ordering direction. * - * @return QueryBuilder This QueryBuilder instance. - * * @throws InvalidArgumentException + * + * @return QueryBuilder This QueryBuilder instance. */ public function addOrderBy(DynamicOperandInterface $sort, $order = 'ASC') { @@ -266,7 +264,7 @@ public function where(ConstraintInterface $constraint) } /** - * Returns the constraint to apply + * Returns the constraint to apply. * * @return ConstraintInterface the constraint to be applied */ @@ -277,7 +275,7 @@ public function getConstraint() /** * Creates a new constraint formed by applying a logical AND to the - * existing constraint and the new one + * existing constraint and the new one. * * Order of ands is important: * @@ -307,7 +305,7 @@ public function andWhere(ConstraintInterface $constraint) /** * Creates a new constraint formed by applying a logical OR to the - * existing constraint and the new one + * existing constraint and the new one. * * Order of ands is important: * @@ -336,7 +334,7 @@ public function orWhere(ConstraintInterface $constraint) } /** - * Returns the columns to be selected + * Returns the columns to be selected. * * @return ColumnInterface[] The columns to be selected */ @@ -346,7 +344,7 @@ public function getColumns() } /** - * Sets the columns to be selected + * Sets the columns to be selected. * * @param ColumnInterface[] $columns The columns to be selected * @@ -427,9 +425,9 @@ public function getSource() * @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. */ public function join(SourceInterface $rightSource, JoinConditionInterface $joinCondition) { @@ -442,9 +440,9 @@ public function join(SourceInterface $rightSource, JoinConditionInterface $joinC * @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. */ public function innerJoin(SourceInterface $rightSource, JoinConditionInterface $joinCondition) { @@ -457,9 +455,9 @@ public function innerJoin(SourceInterface $rightSource, JoinConditionInterface $ * @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. */ public function leftJoin(SourceInterface $rightSource, JoinConditionInterface $joinCondition) { @@ -472,9 +470,9 @@ public function leftJoin(SourceInterface $rightSource, JoinConditionInterface $j * @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. */ public function rightJoin(SourceInterface $rightSource, JoinConditionInterface $joinCondition) { @@ -488,9 +486,9 @@ public function rightJoin(SourceInterface $rightSource, JoinConditionInterface $ * @param string $joinType as specified in PHPCR\Query\QOM\QueryObjectModelConstantsInterface * @param JoinConditionInterface $joinCondition * - * @return QueryBuilder This QueryBuilder instance. - * * @throws RuntimeException if there is not an existing source. + * + * @return QueryBuilder This QueryBuilder instance. */ public function joinWithType(SourceInterface $rightSource, $joinType, JoinConditionInterface $joinCondition) { @@ -505,7 +503,7 @@ public function joinWithType(SourceInterface $rightSource, $joinType, JoinCondit } /** - * Gets the query built + * Gets the query built. * * @return QueryObjectModelInterface */ diff --git a/src/PHPCR/Util/QOM/Sql1Generator.php b/src/PHPCR/Util/QOM/Sql1Generator.php index 1f1bfc3..c06a061 100644 --- a/src/PHPCR/Util/QOM/Sql1Generator.php +++ b/src/PHPCR/Util/QOM/Sql1Generator.php @@ -12,10 +12,11 @@ class Sql1Generator extends BaseSqlGenerator { /** * Selector ::= nodeTypeName - * nodeTypeName ::= Name + * 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) * - * @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 */ public function evalSelector($nodeTypeName, $selectorName = null) @@ -36,15 +37,15 @@ protected function getPathForDescendantQuery($path) $sql1 = '/%'; } else { $path = trim($path, "\"'/"); - $sql1 = "/" . str_replace("/", "[%]/", $path) ; - $sql1 .= "[%]/%"; + $sql1 = '/'.str_replace('/', '[%]/', $path); + $sql1 .= '[%]/%'; } return $sql1; } /** - * SameNode ::= 'jcr:path like Path/% and not jcr:path like Path/%/%' + * SameNode ::= 'jcr:path like Path/% and not jcr:path like Path/%/%'. * * @param string $path * @param string $selectorName @@ -54,14 +55,14 @@ protected function getPathForDescendantQuery($path) public function evalChildNode($path, $selectorName = null) { $path = $this->getPathForDescendantQuery($path); - $sql1 = "jcr:path LIKE '" . $path ."'"; - $sql1 .= " AND NOT jcr:path LIKE '" . $path . "/%'"; + $sql1 = "jcr:path LIKE '".$path."'"; + $sql1 .= " AND NOT jcr:path LIKE '".$path."/%'"; return $sql1; } /** - * Emulate descendant query with LIKE query + * Emulate descendant query with LIKE query. * * @param string $path * @@ -71,48 +72,49 @@ public function evalDescendantNode($path) { $path = $this->getPathForDescendantQuery($path); - return "jcr:path LIKE '" . $path . "'"; + return "jcr:path LIKE '".$path."'"; } /** * PropertyExistence ::= - * propertyName 'IS NOT 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 */ public function evalPropertyExistence($selectorName, $propertyName) { - return $propertyName . " IS NOT NULL"; + return $propertyName.' IS NOT NULL'; } /** * FullTextSearch ::= * 'CONTAINS(' (propertyName | '*') ') ',' * FullTextSearchExpression ')' - * FullTextSearchExpression ::= BindVariable | ''' FullTextSearchLiteral ''' + * FullTextSearchExpression ::= BindVariable | ''' FullTextSearchLiteral '''. + * + * @param string $selectorName unusued + * @param string $searchExpression + * @param string $propertyName * - * @param string $selectorName unusued - * @param string $searchExpression - * @param string $propertyName * @return string */ public function evalFullTextSearch($selectorName, $searchExpression, $propertyName = null) { - $propertyName = $propertyName ? : '*'; + $propertyName = $propertyName ?: '*'; $sql1 = 'CONTAINS('; $sql1 .= $propertyName; - $sql1 .= ', ' . $searchExpression . ')'; + $sql1 .= ', '.$searchExpression.')'; return $sql1; } /** - * columns ::= (Column ',' {Column}) | '*' + * columns ::= (Column ',' {Column}) | '*'. * * @param $columns * @@ -139,7 +141,7 @@ public function evalColumns($columns) } /** - * PropertyValue ::= propertyName + * PropertyValue ::= propertyName. * * @param string $propertyName * @param string $selectorName unused in SQL1 @@ -151,10 +153,9 @@ public function evalPropertyValue($propertyName, $selectorName = null) return $propertyName; } - /** * Column ::= (propertyName) - * propertyName ::= Name + * propertyName ::= Name. * * No support for column name ('AS' columnName) in SQL1 * @@ -163,7 +164,6 @@ public function evalPropertyValue($propertyName, $selectorName = null) * * @return string */ - public function evalColumn($selectorName = null, $propertyName = null) { return $propertyName; @@ -171,9 +171,10 @@ public function evalColumn($selectorName = null, $propertyName = null) /** * Path ::= simplePath - * simplePath ::= A JCR Name that contains only SQL-legal characters + * simplePath ::= A JCR Name that contains only SQL-legal characters. + * + * @param string $path * - * @param string $path * @return string */ public function evalPath($path) @@ -182,7 +183,7 @@ public function evalPath($path) } /** - * {@inheritDoc} + * {@inheritdoc} * * No explicit support, do some tricks where possible. */ @@ -195,7 +196,7 @@ public function evalCastLiteral($literal, $type) return $literal; case 'DOUBLE': if ((int) $literal == $literal) { - return $literal .".0"; + return $literal.'.0'; } return $literal; diff --git a/src/PHPCR/Util/QOM/Sql2Generator.php b/src/PHPCR/Util/QOM/Sql2Generator.php index 95e2146..a938911 100644 --- a/src/PHPCR/Util/QOM/Sql2Generator.php +++ b/src/PHPCR/Util/QOM/Sql2Generator.php @@ -14,13 +14,13 @@ class Sql2Generator extends BaseSqlGenerator { /** * Selector ::= nodeTypeName ['AS' selectorName] - * nodeTypeName ::= Name + * 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. + * 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. + * the nodeTypeName, the alias is declared. * * @return string */ @@ -30,7 +30,7 @@ public function evalSelector($nodeTypeName, $selectorName = null) if (null !== $selectorName && $nodeTypeName !== $selectorName) { // if the selector name is the same as the type name, this is implicit for sql2 - $sql2 .= ' AS ' . $selectorName; + $sql2 .= ' AS '.$selectorName; } return $sql2; @@ -40,7 +40,7 @@ public function evalSelector($nodeTypeName, $selectorName = null) * Join ::= left [JoinType] 'JOIN' right 'ON' JoinCondition * // If JoinType is omitted INNER is assumed. * left ::= Source - * right ::= Source + * right ::= Source. * * @param string $left * @param string $right @@ -58,9 +58,10 @@ public function evalJoin($left, $right, $joinCondition, $joinType = '') * JoinType ::= Inner | LeftOuter | RightOuter * Inner ::= 'INNER' * LeftOuter ::= 'LEFT OUTER' - * RightOuter ::= 'RIGHT OUTER' + * RightOuter ::= 'RIGHT OUTER'. + * + * @param string $joinType * - * @param string $joinType * @return string */ public function evalJoinType($joinType) @@ -83,17 +84,18 @@ public function evalJoinType($joinType) * selector1Name ::= selectorName * selector2Name ::= selectorName * property1Name ::= propertyName - * property2Name ::= propertyName + * property2Name ::= propertyName. + * + * @param string $sel1Name + * @param string $prop1Name + * @param string $sel2Name + * @param string $prop2Name * - * @param string $sel1Name - * @param string $prop1Name - * @param string $sel2Name - * @param string $prop2Name * @return string */ public function evalEquiJoinCondition($sel1Name, $prop1Name, $sel2Name, $prop2Name) { - return $this->evalPropertyValue($prop1Name, $sel1Name) . '=' .$this->evalPropertyValue($prop2Name, $sel2Name); + return $this->evalPropertyValue($prop1Name, $sel1Name).'='.$this->evalPropertyValue($prop2Name, $sel2Name); } /** @@ -101,21 +103,21 @@ public function evalEquiJoinCondition($sel1Name, $prop1Name, $sel2Name, $prop2Na * 'ISSAMENODE(' selector1Name ',' * selector2Name * [',' selector2Path] ')' - * selector2Path ::= Path + * selector2Path ::= Path. + * + * @param string $sel1Name + * @param string $sel2Name + * @param string $sel2Path * - * @param string $sel1Name - * @param string $sel2Name - * @param string $sel2Path * @return string */ public function evalSameNodeJoinCondition($sel1Name, $sel2Name, $sel2Path = null) { $sql2 = 'ISSAMENODE(' - . $this->addBracketsIfNeeded($sel1Name) . ', ' - . $this->addBracketsIfNeeded($sel2Name) - ; + .$this->addBracketsIfNeeded($sel1Name).', ' + .$this->addBracketsIfNeeded($sel2Name); if (null !== $sel2Path) { - $sql2 .= ', ' . $sel2Path; + $sql2 .= ', '.$sel2Path; } $sql2 .= ')'; @@ -127,18 +129,18 @@ public function evalSameNodeJoinCondition($sel1Name, $sel2Name, $sel2Path = null * 'ISCHILDNODE(' childSelectorName ',' * parentSelectorName ')' * childSelectorName ::= selectorName - * parentSelectorName ::= selectorName + * parentSelectorName ::= selectorName. + * + * @param string $childSelectorName + * @param string $parentSelectorName * - * @param string $childSelectorName - * @param string $parentSelectorName * @return string */ public function evalChildNodeJoinCondition($childSelectorName, $parentSelectorName) { return 'ISCHILDNODE(' - . $this->addBracketsIfNeeded($childSelectorName) . ', ' - . $this->addBracketsIfNeeded($parentSelectorName) . ')' - ; + .$this->addBracketsIfNeeded($childSelectorName).', ' + .$this->addBracketsIfNeeded($parentSelectorName).')'; } /** @@ -146,22 +148,22 @@ public function evalChildNodeJoinCondition($childSelectorName, $parentSelectorNa * 'ISDESCENDANTNODE(' descendantSelectorName ',' * ancestorSelectorName ')' * descendantSelectorName ::= selectorName - * ancestorSelectorName ::= selectorName + * ancestorSelectorName ::= selectorName. + * + * @param string $descendantSelectorName + * @param string $ancestorselectorName * - * @param string $descendantSelectorName - * @param string $ancestorselectorName * @return string */ public function evalDescendantNodeJoinCondition($descendantSelectorName, $ancestorselectorName) { return 'ISDESCENDANTNODE(' - . $this->addBracketsIfNeeded($descendantSelectorName) . ', ' - . $this->addBracketsIfNeeded($ancestorselectorName) . ')' - ; + .$this->addBracketsIfNeeded($descendantSelectorName).', ' + .$this->addBracketsIfNeeded($ancestorselectorName).')'; } /** - * SameNode ::= 'ISSAMENODE(' [selectorName ','] Path ')' + * SameNode ::= 'ISSAMENODE(' [selectorName ','] Path ')'. * * @param string $path * @param string $selectorName @@ -171,14 +173,14 @@ public function evalDescendantNodeJoinCondition($descendantSelectorName, $ancest public function evalSameNode($path, $selectorName = null) { $sql2 = 'ISSAMENODE('; - $sql2 .= null === $selectorName ? $path : $this->addBracketsIfNeeded($selectorName) . ', ' . $path; + $sql2 .= null === $selectorName ? $path : $this->addBracketsIfNeeded($selectorName).', '.$path; $sql2 .= ')'; return $sql2; } /** - * SameNode ::= 'ISCHILDNODE(' [selectorName ','] Path ')' + * SameNode ::= 'ISCHILDNODE(' [selectorName ','] Path ')'. * * @param string $path * @param string $selectorName @@ -188,14 +190,14 @@ public function evalSameNode($path, $selectorName = null) public function evalChildNode($path, $selectorName = null) { $sql2 = 'ISCHILDNODE('; - $sql2 .= null === $selectorName ? $path : $this->addBracketsIfNeeded($selectorName) . ', ' . $path; + $sql2 .= null === $selectorName ? $path : $this->addBracketsIfNeeded($selectorName).', '.$path; $sql2 .= ')'; return $sql2; } /** - * SameNode ::= 'ISDESCENDANTNODE(' [selectorName ','] Path ')' + * SameNode ::= 'ISDESCENDANTNODE(' [selectorName ','] Path ')'. * * @param string $path * @param string $selectorName @@ -205,7 +207,7 @@ public function evalChildNode($path, $selectorName = null) public function evalDescendantNode($path, $selectorName = null) { $sql2 = 'ISDESCENDANTNODE('; - $sql2 .= null === $selectorName ? $path : $this->addBracketsIfNeeded($selectorName) . ', ' . $path; + $sql2 .= null === $selectorName ? $path : $this->addBracketsIfNeeded($selectorName).', '.$path; $sql2 .= ')'; return $sql2; @@ -216,7 +218,7 @@ public function evalDescendantNode($path, $selectorName = null) * selectorName'.'propertyName 'IS NOT NULL' | * propertyName 'IS NOT NULL' If only one * selector exists in - * this query + * this query. * * @param $selectorName * @param $propertyName @@ -225,7 +227,7 @@ public function evalDescendantNode($path, $selectorName = null) */ public function evalPropertyExistence($selectorName, $propertyName) { - return $this->evalPropertyValue($propertyName, $selectorName) . " IS NOT NULL"; + return $this->evalPropertyValue($propertyName, $selectorName).' IS NOT NULL'; } /** @@ -233,10 +235,12 @@ public function evalPropertyExistence($selectorName, $propertyName) * 'CONTAINS(' ([selectorName'.']propertyName | * selectorName'.*') ',' * FullTextSearchExpression ')' - * FullTextSearchExpression ::= BindVariable | ''' FullTextSearchLiteral ''' - * @param string $selectorName unusued - * @param string $searchExpression - * @param string $propertyName + * FullTextSearchExpression ::= BindVariable | ''' FullTextSearchLiteral '''. + * + * @param string $selectorName unusued + * @param string $searchExpression + * @param string $propertyName + * * @return string */ public function evalFullTextSearch($selectorName, $searchExpression, $propertyName = null) @@ -245,15 +249,16 @@ public function evalFullTextSearch($selectorName, $searchExpression, $propertyNa $sql2 = 'CONTAINS('; $sql2 .= $this->evalPropertyValue($propertyName, $selectorName); - $sql2 .= ', ' . $searchExpression . ')'; + $sql2 .= ', '.$searchExpression.')'; return $sql2; } /** - * Length ::= 'LENGTH(' PropertyValue ')' + * Length ::= 'LENGTH(' PropertyValue ')'. + * + * @param string $propertyValue * - * @param string $propertyValue * @return string */ public function evalLength($propertyValue) @@ -262,7 +267,7 @@ public function evalLength($propertyValue) } /** - * NodeName ::= 'NAME(' [selectorName] ')' + * NodeName ::= 'NAME(' [selectorName] ')'. * * @param string $selectorValue * @@ -274,7 +279,7 @@ public function evalNodeName($selectorValue = null) } /** - * NodeLocalName ::= 'LOCALNAME(' [selectorName] ')' + * NodeLocalName ::= 'LOCALNAME(' [selectorName] ')'. * * @param string $selectorValue * @@ -286,7 +291,7 @@ public function evalNodeLocalName($selectorValue = null) } /** - * FullTextSearchScore ::= 'SCORE(' [selectorName] ')' + * FullTextSearchScore ::= 'SCORE(' [selectorName] ')'. * * @param string $selectorValue * @@ -298,7 +303,7 @@ public function evalFullTextSearchScore($selectorValue = null) } /** - * PropertyValue ::= [selectorName'.'] propertyName // If only one selector exists + * PropertyValue ::= [selectorName'.'] propertyName // If only one selector exists. * * @param string $propertyName * @param string $selectorName @@ -307,7 +312,7 @@ public function evalFullTextSearchScore($selectorValue = null) */ public function evalPropertyValue($propertyName, $selectorName = null) { - $sql2 = null !== $selectorName ? $this->addBracketsIfNeeded($selectorName) . '.' : ''; + $sql2 = null !== $selectorName ? $this->addBracketsIfNeeded($selectorName).'.' : ''; if ('*' !== $propertyName && substr($propertyName, 0, 1) !== '[') { $propertyName = "[$propertyName]"; } @@ -317,7 +322,7 @@ public function evalPropertyValue($propertyName, $selectorName = null) } /** - * columns ::= (Column ',' {Column}) | '*' + * columns ::= (Column ',' {Column}) | '*'. * * @param $columns * @@ -349,7 +354,7 @@ public function evalColumns($columns) * (selectorName'.*') // If only one selector exists * selectorName ::= Name * propertyName ::= Name - * columnName ::= Name + * columnName ::= Name. * * @param string $selectorName * @param string $propertyName @@ -361,12 +366,12 @@ public function evalColumn($selectorName, $propertyName = null, $colname = null) { $sql2 = ''; if (null !== $selectorName && null === $propertyName && null === $colname) { - $sql2 .= $this->addBracketsIfNeeded($selectorName) . '.*'; + $sql2 .= $this->addBracketsIfNeeded($selectorName).'.*'; } else { $sql2 .= $this->evalPropertyValue($propertyName, $selectorName); if (null !== $colname && $colname !== $propertyName) { // if the column name is the same as the property name, this is implicit for sql2 - $sql2 .= ' AS ' . $colname; + $sql2 .= ' AS '.$colname; } } @@ -376,9 +381,10 @@ 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 + * simplePath ::= A JCR Name that contains only SQL-legal characters. + * + * @param string $path * - * @param string $path * @return string */ public function evalPath($path) @@ -388,19 +394,17 @@ public function evalPath($path) // only ensure proper quoting if the user did not quote himself, we trust him to get it right if he did. if (substr($path, 0, 1) !== '[' && substr($path, -1) !== ']') { if (false !== strpos($sql2, ' ') || false !== strpos($sql2, '.')) { - $sql2 = '"' . $sql2 . '"'; + $sql2 = '"'.$sql2.'"'; } - $sql2 = '[' . $sql2 . ']'; + $sql2 = '['.$sql2.']'; } return $sql2; } - - return null; } /** - * {@inheritDoc} + * {@inheritdoc} * * CastLiteral ::= 'CAST(' UncastLiteral ' AS ' PropertyType ')' */ @@ -410,7 +414,7 @@ public function evalCastLiteral($literal, $type) } /** - * Add square brackets around a selector if needed + * Add square brackets around a selector if needed. * * @param string $selector * diff --git a/src/PHPCR/Util/QOM/Sql2Scanner.php b/src/PHPCR/Util/QOM/Sql2Scanner.php index e69ef25..9e8bc68 100644 --- a/src/PHPCR/Util/QOM/Sql2Scanner.php +++ b/src/PHPCR/Util/QOM/Sql2Scanner.php @@ -13,35 +13,35 @@ class Sql2Scanner { /** - * The SQL2 query currently being parsed + * The SQL2 query currently being parsed. * * @var string */ protected $sql2; /** - * Token scanning result of the SQL2 string + * Token scanning result of the SQL2 string. * * @var array */ protected $tokens; /** - * Delimiters between tokens + * Delimiters between tokens. * * @var array */ protected $delimiters; /** - * Parsing position in the SQL string + * Parsing position in the SQL string. * * @var int */ protected $curpos = 0; /** - * Construct a scanner with the given SQL2 statement + * Construct a scanner with the given SQL2 statement. * * @param string $sql2 */ @@ -69,7 +69,7 @@ public function lookupNextToken($offset = 0) } /** - * Get the delimiter that separated the two previous tokens + * Get the delimiter that separated the two previous tokens. * * @return string */ @@ -99,15 +99,15 @@ 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 boolean $case_insensitive + * @param string $token The expected token + * @param bool $case_insensitive * * @throws InvalidQueryException */ public function expectToken($token, $case_insensitive = true) { $nextToken = $this->fetchNextToken(); - if (! $this->tokenIs($nextToken, $token, $case_insensitive)) { + if (!$this->tokenIs($nextToken, $token, $case_insensitive)) { throw new InvalidQueryException("Syntax error: Expected '$token', found '$nextToken' in {$this->sql2}"); } } @@ -115,10 +115,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. + * * @see expectToken * - * @param array $tokens - * @param boolean $case_insensitive + * @param array $tokens + * @param bool $case_insensitive * * @throws InvalidQueryException */ @@ -130,12 +131,13 @@ public function expectTokens($tokens, $case_insensitive = true) } /** - * Test the equality of two tokens + * Test the equality of two tokens. + * + * @param string $token + * @param string $value + * @param bool $case_insensitive * - * @param string $token - * @param string $value - * @param boolean $case_insensitive - * @return boolean + * @return bool */ public function tokenIs($token, $value, $case_insensitive = true) { @@ -149,9 +151,10 @@ public function tokenIs($token, $value, $case_insensitive = true) } /** - * Scan a SQL2 string a extract the tokens + * Scan a SQL2 string a extract the tokens. + * + * @param string $sql2 * - * @param string $sql2 * @return array */ protected function scan($sql2) diff --git a/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php b/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php index 80eccd0..d3a7a46 100644 --- a/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php +++ b/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php @@ -5,6 +5,7 @@ use DateTime; use Exception; use InvalidArgumentException; +use Jackalope\Query\QOM\Selector; use LogicException; use PHPCR\PropertyType; use PHPCR\Query\InvalidQueryException; @@ -29,7 +30,6 @@ use PHPCR\Query\QOM\SelectorInterface; use PHPCR\Query\QOM\SourceInterface; use PHPCR\Query\QOM\StaticOperandInterface; -use Jackalope\Query\QOM\Selector; use PHPCR\Util\ValueConverter; /** @@ -41,21 +41,21 @@ class Sql2ToQomQueryConverter { /** - * The factory to create QOM objects + * The factory to create QOM objects. * * @var QueryObjectModelFactoryInterface */ protected $factory; /** - * Scanner to parse SQL2 + * Scanner to parse SQL2. * * @var Sql2Scanner; */ protected $scanner; /** - * The SQL2 query (the converter is not reentrant) + * The SQL2 query (the converter is not reentrant). * * @var string */ @@ -72,7 +72,7 @@ class Sql2ToQomQueryConverter protected $implicitSelectorName = null; /** - * Instantiate a converter + * Instantiate a converter. * * @param QueryObjectModelFactoryInterface $factory * @param ValueConverter $valueConverter To override default converter. @@ -85,13 +85,13 @@ public function __construct(QueryObjectModelFactoryInterface $factory, ValueConv /** * 6.7.1. Query - * Parse an SQL2 query and return the corresponding QOM QueryObjectModel + * Parse an SQL2 query and return the corresponding QOM QueryObjectModel. * * @param string $sql2 * - * @return QueryObjectModelInterface - * * @throws InvalidQueryException + * + * @return QueryObjectModelInterface */ public function parse($sql2) { @@ -123,7 +123,7 @@ public function parse($sql2) $orderings = $this->parseOrderings(); break; default: - throw new InvalidQueryException('Error parsing query, unknown query part "' . $this->scanner->lookupNextToken() . '" in: ' . $this->sql2); + throw new InvalidQueryException('Error parsing query, unknown query part "'.$this->scanner->lookupNextToken().'" in: '.$this->sql2); } } @@ -140,7 +140,7 @@ public function parse($sql2) /** * 6.7.2. Source - * Parse an SQL2 source definition and return the corresponding QOM Source + * Parse an SQL2 source definition and return the corresponding QOM Source. * * @return SourceInterface */ @@ -161,7 +161,7 @@ protected function parseSource() /** * 6.7.3. Selector - * Parse an SQL2 selector and return a QOM\Selector + * Parse an SQL2 selector and return a QOM\Selector. * * @return SelectorInterface */ @@ -182,7 +182,7 @@ protected function parseSelector() } /** - * 6.7.4. Name + * 6.7.4. Name. * * @return string */ @@ -194,7 +194,7 @@ protected function parseName() /** * 6.7.5. Join * 6.7.6. Join type - * Parse an SQL2 join source and return a QOM\Join + * Parse an SQL2 join source and return a QOM\Join. * * @param SourceInterface $leftSelector the left selector as it has been read by parseSource * @@ -210,11 +210,11 @@ protected function parseJoin(SourceInterface $leftSelector) } /** - * 6.7.6. Join type - * - * @return string + * 6.7.6. Join type. * * @throws InvalidQueryException + * + * @return string */ protected function parseJoinType() { @@ -245,7 +245,7 @@ protected function parseJoinType() /** * 6.7.7. JoinCondition - * Parse an SQL2 join condition and return a JoinConditionInterface + * Parse an SQL2 join condition and return a JoinConditionInterface. * * @return JoinConditionInterface */ @@ -271,7 +271,7 @@ protected function parseJoinCondition() /** * 6.7.8. EquiJoinCondition - * Parse an SQL2 equijoin condition and return a EquiJoinConditionInterface + * Parse an SQL2 equijoin condition and return a EquiJoinConditionInterface. * * @return EquiJoinConditionInterface */ @@ -286,7 +286,7 @@ protected function parseEquiJoin() /** * 6.7.9 SameNodeJoinCondition - * Parse an SQL2 same node join condition and return a SameNodeJoinConditionInterface + * Parse an SQL2 same node join condition and return a SameNodeJoinConditionInterface. * * @return SameNodeJoinConditionInterface */ @@ -312,7 +312,7 @@ protected function parseSameNodeJoinCondition() /** * 6.7.10 ChildNodeJoinCondition - * Parse an SQL2 child node join condition and return a ChildNodeJoinConditionInterface + * Parse an SQL2 child node join condition and return a ChildNodeJoinConditionInterface. * * @return ChildNodeJoinConditionInterface */ @@ -329,7 +329,7 @@ protected function parseChildNodeJoinCondition() /** * 6.7.11 DescendantNodeJoinCondition - * Parse an SQL2 descendant node join condition and return a DescendantNodeJoinConditionInterface + * Parse an SQL2 descendant node join condition and return a DescendantNodeJoinConditionInterface. * * @return DescendantNodeJoinConditionInterface */ @@ -346,14 +346,14 @@ protected function parseDescendantNodeJoinCondition() /** * 6.7.13 And - * 6.7.14 Or + * 6.7.14 Or. * * @param ConstraintInterface $lhs Left hand side * @param int $minprec Precedence * - * @return ConstraintInterface - * * @throws Exception + * + * @return ConstraintInterface */ protected function parseConstraint($lhs = null, $minprec = 0) { @@ -362,7 +362,7 @@ protected function parseConstraint($lhs = null, $minprec = 0) } $opprec = [ - 'OR' => 1, + 'OR' => 1, 'AND' => 2, ]; @@ -400,7 +400,7 @@ protected function parseConstraint($lhs = null, $minprec = 0) } /** - * 6.7.12 Constraint + * 6.7.12 Constraint. * * @return ConstraintInterface */ @@ -456,7 +456,7 @@ protected function parsePrimaryConstraint() } /** - * 6.7.15 Not + * 6.7.15 Not. * * @return NotInterface */ @@ -468,11 +468,11 @@ protected function parseNot() } /** - * 6.7.16 Comparison - * - * @return ComparisonInterface + * 6.7.16 Comparison. * * @throws InvalidQueryException + * + * @return ComparisonInterface */ protected function parseComparison() { @@ -489,7 +489,7 @@ protected function parseComparison() } /** - * 6.7.17 Operator + * 6.7.17 Operator. * * @return string a constant from QueryObjectModelConstantsInterface */ @@ -517,7 +517,7 @@ protected function parseOperator() } /** - * 6.7.18 PropertyExistence + * 6.7.18 PropertyExistence. * * @return PropertyExistenceInterface */ @@ -539,7 +539,7 @@ protected function parsePropertyExistence() } /** - * 6.7.19 FullTextSearch + * 6.7.19 FullTextSearch. * * @return FullTextSearchInterface */ @@ -556,7 +556,7 @@ protected function parseFullTextSearch() } /** - * 6.7.20 SameNode + * 6.7.20 SameNode. */ protected function parseSameNode() { @@ -575,7 +575,7 @@ protected function parseSameNode() } /** - * 6.7.21 ChildNode + * 6.7.21 ChildNode. */ protected function parseChildNode() { @@ -594,7 +594,7 @@ protected function parseChildNode() } /** - * 6.7.22 DescendantNode + * 6.7.22 DescendantNode. */ protected function parseDescendantNode() { @@ -632,7 +632,7 @@ protected function parsePath() /** * Parse an SQL2 static operand * 6.7.35 BindVariable - * 6.7.36 Prefix + * 6.7.36 Prefix. * * @return StaticOperandInterface */ @@ -654,7 +654,7 @@ protected function parseStaticOperand() * 6.7.31 FullTextSearchScore * 6.7.32 LowerCase * 6.7.33 UpperCase - * Parse an SQL2 dynamic operand + * Parse an SQL2 dynamic operand. * * @return DynamicOperandInterface */ @@ -736,7 +736,7 @@ protected function parseDynamicOperand() /** * 6.7.27 PropertyValue - * Parse an SQL2 property value + * Parse an SQL2 property value. * * @return PropertyValueInterface */ @@ -782,6 +782,7 @@ protected function parseCastLiteral($token) $this->scanner->expectToken('AS'); $type = $this->scanner->fetchNextToken(); + try { $typeValue = PropertyType::valueFromName($type); } catch (InvalidArgumentException $e) { @@ -801,7 +802,7 @@ protected function parseCastLiteral($token) /** * 6.7.34 Literal - * Parse an SQL2 literal value + * Parse an SQL2 literal value. * * @return mixed */ @@ -837,7 +838,7 @@ protected function parseLiteralValue() $token = str_replace("''", "'", $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'; + $token .= ' 00:00:00'; } $token = DateTime::createFromFormat('Y-m-d H:i:s', $token); } @@ -853,7 +854,7 @@ protected function parseLiteralValue() } /** - * 6.7.37 Ordering + * 6.7.37 Ordering. */ protected function parseOrderings() { @@ -873,7 +874,7 @@ protected function parseOrderings() } /** - * 6.7.38 Order + * 6.7.38 Order. * * @return OrderingInterface */ @@ -900,7 +901,7 @@ protected function parseOrdering() } /** - * 6.7.39 Column + * 6.7.39 Column. * * Scan the SQL2 columns definitions and return data arrays to convert to * columns once the FROM is parsed. @@ -952,7 +953,7 @@ protected function buildColumns($data) /** * Get the next token and make sure to remove the brackets if the token is - * in the [ns:name] notation + * in the [ns:name] notation. * * @return string */ @@ -971,10 +972,10 @@ private function fetchTokenWithoutBrackets() /** * Parse something that is expected to be a property identifier. * - * @param boolean $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 + * specified, defaults to $this->defaultSelectorName */ private function parseIdentifier($checkSelector = true) { @@ -1025,10 +1026,10 @@ protected function updateImplicitSelectorName($selectorName) * * @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. + * there is more than one selector available. + * + * @return string the selector to use */ protected function ensureSelectorName($parsedName) { @@ -1042,14 +1043,14 @@ protected function ensureSelectorName($parsedName) return $parsedName; } if (is_array($this->implicitSelectorName)) { - throw new InvalidQueryException("Need an explicit selector name in join queries"); + throw new InvalidQueryException('Need an explicit selector name in join queries'); } return $this->implicitSelectorName; } /** - * Scan a single SQL2 column definition and return an array of information + * Scan a single SQL2 column definition and return an array of information. * * @return array */ @@ -1069,7 +1070,7 @@ protected function scanColumn() } /** - * Build a single SQL2 column definition + * Build a single SQL2 column definition. * * @param array $data with selector name, property name and column name. * diff --git a/src/PHPCR/Util/TraversingItemVisitor.php b/src/PHPCR/Util/TraversingItemVisitor.php index f2695b4..447b35d 100644 --- a/src/PHPCR/Util/TraversingItemVisitor.php +++ b/src/PHPCR/Util/TraversingItemVisitor.php @@ -2,12 +2,12 @@ namespace PHPCR\Util; -use SplQueue; use PHPCR\ItemInterface; -use PHPCR\PropertyInterface; -use PHPCR\NodeInterface; use PHPCR\ItemVisitorInterface; +use PHPCR\NodeInterface; +use PHPCR\PropertyInterface; use PHPCR\RepositoryException; +use SplQueue; /** * An implementation of ItemVisitor. @@ -24,7 +24,6 @@ * * @author Karsten Dambekalns * @author Day Management AG, Switzerland - * * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License * @@ -36,7 +35,7 @@ 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 boolean + * @var bool */ protected $breadthFirst = false; @@ -45,7 +44,7 @@ abstract class TraversingItemVisitor implements ItemVisitorInterface * -1, the hierarchy will be traversed until there are no more children of * the current item). * - * @var integer + * @var int */ protected $maxDepth = -1; @@ -66,20 +65,20 @@ abstract class TraversingItemVisitor implements ItemVisitorInterface /** * Used to track hierarchy depth of item currently being processed. * - * @var integer + * @var int */ protected $currentDepth; /** * Constructs a new instance of this class. * - * @param boolean $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). - * @param integer $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). + * @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). + * @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). * * @api */ @@ -96,7 +95,7 @@ public function __construct($breadthFirst = false, $maxDepth = -1) } /** - * Update the current depth level for indention + * Update the current depth level for indention. * * @param int $level */ @@ -109,10 +108,10 @@ public function setLevel($level) * Implement this method to add behavior performed before a Property is * visited. * - * @param ItemInterface $item the Item that is accepting this - * visitor. - * @param integer $depth hierarchy level of this node (the root node starts - * at depth 0). + * @param ItemInterface $item the Item that is accepting this + * visitor. + * @param int $depth hierarchy level of this node (the root node starts + * at depth 0). * * @throws RepositoryException if an error occurs. * @@ -124,10 +123,10 @@ abstract protected function entering(ItemInterface $item, $depth); * Implement this method to add behavior performed after a Property is * visited. * - * @param ItemInterface $item the Item that is accepting this - * visitor. - * @param integer $depth hierarchy level of this property (the root node - * starts at depth 0). + * @param ItemInterface $item the Item that is accepting this + * visitor. + * @param int $depth hierarchy level of this property (the root node + * starts at depth 0). * * @throws RepositoryException if an error occurs. * @@ -145,7 +144,7 @@ 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. * @@ -160,18 +159,18 @@ public function visit(ItemInterface $item) $this->entering($item, $this->currentDepth); $this->leaving($item, $this->currentDepth); } else { - /** @var $item NodeInterface */ + /* @var $item NodeInterface */ try { if ($this->breadthFirst === false) { $this->entering($item, $this->currentDepth); if ($this->maxDepth === -1 || $this->currentDepth < $this->maxDepth) { $this->currentDepth++; foreach ($item->getProperties() as $property) { - /** @var $property PropertyInterface */ + /* @var $property PropertyInterface */ $property->accept($this); } foreach ($item->getNodes() as $node) { - /** @var $node NodeInterface */ + /* @var $node NodeInterface */ $node->accept($this); } $this->currentDepth--; @@ -183,11 +182,11 @@ public function visit(ItemInterface $item) if ($this->maxDepth === -1 || $this->currentDepth < $this->maxDepth) { foreach ($item->getProperties() as $property) { - /** @var $property PropertyInterface */ + /* @var $property PropertyInterface */ $property->accept($this); } foreach ($item->getNodes() as $node) { - /** @var $node NodeInterface */ + /* @var $node NodeInterface */ $node->accept($this); } } @@ -205,6 +204,7 @@ public function visit(ItemInterface $item) } } catch (RepositoryException $exception) { $this->currentDepth = 0; + throw $exception; } } diff --git a/src/PHPCR/Util/TreeWalker.php b/src/PHPCR/Util/TreeWalker.php index 5c2b22b..670c413 100644 --- a/src/PHPCR/Util/TreeWalker.php +++ b/src/PHPCR/Util/TreeWalker.php @@ -7,45 +7,44 @@ use PHPCR\PropertyInterface; /** - * TODO: this should base on the TraversingItemVisitor + * TODO: this should base on the TraversingItemVisitor. * * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * * @author Daniel Barsotti */ class TreeWalker { /** - * Visitor for nodes + * Visitor for nodes. * * @var ItemVisitorInterface */ protected $nodeVisitor; /** - * Visitor for properties + * Visitor for properties. * * @var ItemVisitorInterface */ protected $propertyVisitor; /** - * Filters to apply to decide whether a node needs to be visited + * Filters to apply to decide whether a node needs to be visited. * * @var TreeWalkerFilterInterface[] */ protected $nodeFilters = []; /** - * Filters to apply to decide whether a property needs to be visited + * Filters to apply to decide whether a property needs to be visited. * * @var TreeWalkerFilterInterface[] */ protected $propertyFilters = []; /** - * Instantiate a tree walker + * Instantiate a tree walker. * * @param ItemVisitorInterface $nodeVisitor The visitor for the nodes * @param ItemVisitorInterface $propertyVisitor The visitor for the nodes properties @@ -57,7 +56,7 @@ public function __construct(ItemVisitorInterface $nodeVisitor, ItemVisitorInterf } /** - * Add a filter to select the nodes that will be traversed + * Add a filter to select the nodes that will be traversed. * * @param TreeWalkerFilterInterface $filter */ @@ -69,7 +68,7 @@ public function addNodeFilter(TreeWalkerFilterInterface $filter) } /** - * Add a filter to select the properties that will be traversed + * Add a filter to select the properties that will be traversed. * * @param TreeWalkerFilterInterface $filter */ @@ -81,16 +80,16 @@ public function addPropertyFilter(TreeWalkerFilterInterface $filter) } /** - * Return whether a node must be traversed or not + * Return whether a node must be traversed or not. * * @param NodeInterface $node * - * @return boolean + * @return bool */ protected function mustVisitNode(NodeInterface $node) { foreach ($this->nodeFilters as $filter) { - if (! $filter->mustVisit($node)) { + if (!$filter->mustVisit($node)) { return false; } } @@ -99,16 +98,16 @@ protected function mustVisitNode(NodeInterface $node) } /** - * Return whether a node property must be traversed or not + * Return whether a node property must be traversed or not. * * @param PropertyInterface $property * - * @return boolean + * @return bool */ protected function mustVisitProperty(PropertyInterface $property) { foreach ($this->propertyFilters as $filter) { - if (! $filter->mustVisit($property)) { + if (!$filter->mustVisit($property)) { return false; } } @@ -117,7 +116,7 @@ protected function mustVisitProperty(PropertyInterface $property) } /** - * Traverse a node + * Traverse a node. * * @param NodeInterface $node * @param int $recurse Max recursion level diff --git a/src/PHPCR/Util/TreeWalkerFilterInterface.php b/src/PHPCR/Util/TreeWalkerFilterInterface.php index fe681af..41272d7 100644 --- a/src/PHPCR/Util/TreeWalkerFilterInterface.php +++ b/src/PHPCR/Util/TreeWalkerFilterInterface.php @@ -7,13 +7,12 @@ /** * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * * @author Daniel Barsotti */ interface TreeWalkerFilterInterface { /** - * Whether to visit the passed item + * Whether to visit the passed item. * * @param ItemInterface $item * diff --git a/src/PHPCR/Util/ValueConverter.php b/src/PHPCR/Util/ValueConverter.php index c39d16d..904e6bf 100644 --- a/src/PHPCR/Util/ValueConverter.php +++ b/src/PHPCR/Util/ValueConverter.php @@ -19,7 +19,6 @@ * * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004 * @license http://opensource.org/licenses/MIT MIT License - * * @author David Buchmann * * @api @@ -42,13 +41,13 @@ class ValueConverter * formatting spec for dates (sYYYY-MM-DDThh:mm:ss.sssTZD) according to * 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 boolean $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 + * @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 + * + * @return int One of the type constants */ public function determineType($value, $weak = false) { @@ -86,34 +85,34 @@ public function determineType($value, $weak = false) * * Table based on JCR spec * - - - - - - - - - - - - - - - - -

STRING (1)BINARY (2)LONG (3)DOUBLE (4)DATE (5)BOOLEAN (6)NAME(7)PATH (8)REFERENCE (9/10)URI (11)DECIMAL (12)
STRINGxUtf-8 encodedcast to intcast to floatSYYYY-MM-DDThh:Mm:ss.sssTZD'' is false, else trueif valid name, nameif valid path, as namecheck valid uuidRFC 3986string
BINARYUtf-8xConverted to string and then interpreted as above
LONGcast to stringString, then Utf-8xcast to floatUnix Time0 false else trueValueFormatExceptionValueFormatExceptionValueFormatExceptionValueFormatExceptioncast to string
DOUBLEcast to stringString, then Utf-8cast to intxUnix Time0.0 is false, else trueValueFormatExceptionValueFormatExceptionValueFormatExceptionValueFormatExceptioncast to string
DATESYYYY-MM-DDThh:
Mm:ss.sssTZD
String, then Utf-8Unix timestampUnix timestampxtrueValueFormatExceptionValueFormatExceptionValueFormatExceptionValueFormatExceptionUnix timestamp
BOOLEANcast to stringString, then Utf-80/10.0/1.0ValueFormatExceptionx'0'/'1'ValueFormatExceptionValueFormatExceptionValueFormatExceptionValueFormatException
NAMEQualified formString, then Utf-8ValueFormatExceptionValueFormatExceptionValueFormatExceptionValueFormatExceptionxnoop (relative path)ValueFormatException„./“ and qualified name. % encode illegal charactersValueFormatException
PATHStandard formString, then Utf-8ValueFormatExceptionValueFormatExceptionValueFormatExceptionValueFormatExceptionif relative path lenght 1 noop / otherwise ValueFormatExceptionxValueFormatException„./“ if not starting with /. % encode illegal charactersValueFormatException
REFERENCEnoopString, then Utf-8ValueFormatExceptionValueFormatExceptionValueFormatExceptionValueFormatExceptionValueFormatExceptionValueFormatExceptionxValueFormatExceptionValueFormatException
URInoopString, then Utf-8ValueFormatExceptionValueFormatExceptionValueFormatExceptionValueFormatExceptionsingle name: decode %, remove ./ else ValueFormatExceptionDecode %, remove leading ./ . if not star w. name, / or ./ then ValueFormatExceptionValueFormatExceptionxValueFormatException
DECIMALnoopUtf-8 encodedcast to intcast to floatUnix Time0 false else trueValueFormatExceptionValueFormatExceptionValueFormatExceptionValueFormatExceptionx
+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *

STRING (1)BINARY (2)LONG (3)DOUBLE (4)DATE (5)BOOLEAN (6)NAME(7)PATH (8)REFERENCE (9/10)URI (11)DECIMAL (12)
STRINGxUtf-8 encodedcast to intcast to floatSYYYY-MM-DDThh:Mm:ss.sssTZD'' is false, else trueif valid name, nameif valid path, as namecheck valid uuidRFC 3986string
BINARYUtf-8xConverted to string and then interpreted as above
LONGcast to stringString, then Utf-8xcast to floatUnix Time0 false else trueValueFormatExceptionValueFormatExceptionValueFormatExceptionValueFormatExceptioncast to string
DOUBLEcast to stringString, then Utf-8cast to intxUnix Time0.0 is false, else trueValueFormatExceptionValueFormatExceptionValueFormatExceptionValueFormatExceptioncast to string
DATESYYYY-MM-DDThh:
Mm:ss.sssTZD
String, then Utf-8Unix timestampUnix timestampxtrueValueFormatExceptionValueFormatExceptionValueFormatExceptionValueFormatExceptionUnix timestamp
BOOLEANcast to stringString, then Utf-80/10.0/1.0ValueFormatExceptionx'0'/'1'ValueFormatExceptionValueFormatExceptionValueFormatExceptionValueFormatException
NAMEQualified formString, then Utf-8ValueFormatExceptionValueFormatExceptionValueFormatExceptionValueFormatExceptionxnoop (relative path)ValueFormatException„./“ and qualified name. % encode illegal charactersValueFormatException
PATHStandard formString, then Utf-8ValueFormatExceptionValueFormatExceptionValueFormatExceptionValueFormatExceptionif relative path lenght 1 noop / otherwise ValueFormatExceptionxValueFormatException„./“ if not starting with /. % encode illegal charactersValueFormatException
REFERENCEnoopString, then Utf-8ValueFormatExceptionValueFormatExceptionValueFormatExceptionValueFormatExceptionValueFormatExceptionValueFormatExceptionxValueFormatExceptionValueFormatException
URInoopString, then Utf-8ValueFormatExceptionValueFormatExceptionValueFormatExceptionValueFormatExceptionsingle name: decode %, remove ./ else ValueFormatExceptionDecode %, remove leading ./ . if not star w. name, / or ./ then ValueFormatExceptionValueFormatExceptionxValueFormatException
DECIMALnoopUtf-8 encodedcast to intcast to floatUnix Time0 false else trueValueFormatExceptionValueFormatExceptionValueFormatExceptionValueFormatExceptionx
* * @param mixed $value The value or value array to check and convert * @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) * - * @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 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) + * * @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) @@ -145,8 +144,8 @@ public function convertType($value, $type, $srcType = PropertyType::UNDEFINED) && $value instanceof NodeInterface ) { /** @var $value NodeInterface */ - if (! $value->isNodeType('mix:referenceable')) { - throw new ValueFormatException('Node ' . $value->getPath() . ' is not referenceable'); + if (!$value->isNodeType('mix:referenceable')) { + throw new ValueFormatException('Node '.$value->getPath().' is not referenceable'); } $value = $value->getIdentifier(); } @@ -155,15 +154,15 @@ 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 */ + /* @var $value DateTime */ // Milliseconds formatting is not possible in PHP so we // construct it by cutting microseconds to 3 positions. // This might not be as accurate as "real" rounded milliseconds. - return $value->format('Y-m-d\TH:i:s.') . - substr($value->format('u'), 0, 3) . + return $value->format('Y-m-d\TH:i:s.'). + substr($value->format('u'), 0, 3). $value->format('P'); case PropertyType::NAME: case PropertyType::PATH: @@ -184,7 +183,7 @@ public function convertType($value, $type, $srcType = PropertyType::UNDEFINED) if (is_resource($value)) { return $value; } - if (! is_string($value)) { + if (!is_string($value)) { $value = $this->convertType($value, PropertyType::STRING, $srcType); } $f = fopen('php://memory', 'rwb+'); @@ -200,20 +199,20 @@ public function convertType($value, $type, $srcType = PropertyType::UNDEFINED) case PropertyType::DOUBLE: case PropertyType::BOOLEAN: case PropertyType::DECIMAL: - return (integer) $value; + return (int) $value; case PropertyType::DATE: - if (! $value instanceof DateTime) { + if (!$value instanceof DateTime) { throw new RepositoryException('something weird'); } - /** @var $value DateTime */ + /* @var $value DateTime */ return $value->getTimestamp(); } if (is_object($value)) { throw new ValueFormatException('Cannot convert object of class "'.get_class($value).'" to a LONG'); } - throw new ValueFormatException('Cannot convert "'.var_export($value, true).'" to a LONG'); + throw new ValueFormatException('Cannot convert "'.var_export($value, true).'" to a LONG'); case PropertyType::DOUBLE: switch ($srcType) { case PropertyType::STRING: @@ -221,21 +220,21 @@ public function convertType($value, $type, $srcType = PropertyType::UNDEFINED) case PropertyType::DOUBLE: case PropertyType::BOOLEAN: case PropertyType::DECIMAL: - return (double) $value; + return (float) $value; case PropertyType::DATE: - if (! $value instanceof DateTime) { + if (!$value instanceof DateTime) { throw new RepositoryException('something weird'); } - /** @var $value DateTime */ + /* @var $value DateTime */ - return (double) $value->getTimestamp(); + 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 "'.var_export($value, true).'" to a DOUBLE'); + throw new ValueFormatException('Cannot convert "'.var_export($value, true).'" to a DOUBLE'); case PropertyType::DATE: switch ($srcType) { case PropertyType::STRING: @@ -243,6 +242,7 @@ public function convertType($value, $type, $srcType = PropertyType::UNDEFINED) if ($value instanceof DateTime) { return $value; } + try { return new DateTime($value); } catch (Exception $e) { @@ -259,27 +259,27 @@ public function convertType($value, $type, $srcType = PropertyType::UNDEFINED) if (is_object($value)) { throw new ValueFormatException('Cannot convert object of class "'.get_class($value).'" to a DATE'); } - throw new ValueFormatException('Cannot convert "'.var_export($value, true).'" to DATE'); + throw new ValueFormatException('Cannot convert "'.var_export($value, true).'" to DATE'); case PropertyType::BOOLEAN: switch ($srcType) { case PropertyType::STRING: case PropertyType::LONG: case PropertyType::DOUBLE: case PropertyType::BOOLEAN: - return (boolean) $value; + return (bool) $value; case PropertyType::DATE: - /** @var $value DateTime */ + /* @var $value DateTime */ - return (boolean) $value->getTimestamp(); + return (bool) $value->getTimestamp(); case PropertyType::DECIMAL: - return (boolean) ((double) $value); // '0' is false too + 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 "'.var_export($value, true).'" to a BOOLEAN'); + throw new ValueFormatException('Cannot convert "'.var_export($value, true).'" to a BOOLEAN'); case PropertyType::NAME: switch ($srcType) { case PropertyType::STRING: @@ -294,8 +294,8 @@ public function convertType($value, $type, $srcType = PropertyType::UNDEFINED) if (is_object($value)) { throw new ValueFormatException('Cannot convert object of class "'.get_class($value).'" to a NAME'); } - throw new ValueFormatException('Cannot convert "'.var_export($value, true).'" to NAME'); + throw new ValueFormatException('Cannot convert "'.var_export($value, true).'" to NAME'); case PropertyType::PATH: switch ($srcType) { case PropertyType::STRING: @@ -311,8 +311,8 @@ public function convertType($value, $type, $srcType = PropertyType::UNDEFINED) if (is_object($value)) { throw new ValueFormatException('Cannot convert object of class "'.get_class($value).'" to a PATH'); } - throw new ValueFormatException('Cannot convert "'.var_export($value, true).'" to PATH'); + throw new ValueFormatException('Cannot convert "'.var_export($value, true).'" to PATH'); case PropertyType::REFERENCE: case PropertyType::WEAKREFERENCE: switch ($srcType) { @@ -329,8 +329,8 @@ public function convertType($value, $type, $srcType = PropertyType::UNDEFINED) if (is_object($value)) { throw new ValueFormatException('Cannot convert object of class "'.get_class($value).'" to a unique id'); } - throw new ValueFormatException('Cannot convert "'.var_export($value, true).'" to unique id'); + throw new ValueFormatException('Cannot convert "'.var_export($value, true).'" to unique id'); case PropertyType::URI: switch ($srcType) { case PropertyType::STRING: @@ -353,8 +353,8 @@ public function convertType($value, $type, $srcType = PropertyType::UNDEFINED) if (is_object($value)) { throw new ValueFormatException('Cannot convert object of class "'.get_class($value).'" to a URI'); } - throw new ValueFormatException('Cannot convert "'.var_export($value, true).'" to URI'); + throw new ValueFormatException('Cannot convert "'.var_export($value, true).'" to URI'); case PropertyType::DECIMAL: switch ($srcType) { case PropertyType::STRING: @@ -366,15 +366,15 @@ public function convertType($value, $type, $srcType = PropertyType::UNDEFINED) case PropertyType::DECIMAL: return (string) $value; case PropertyType::DATE: - /** @var $value DateTime */ + /* @var $value DateTime */ 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 "'.var_export($value, true).'" to a DECIMAL'); + throw new ValueFormatException('Cannot convert "'.var_export($value, true).'" to a DECIMAL'); default: throw new ValueFormatException("Unexpected target type '$type' in conversion"); } diff --git a/tests/PHPCR/Tests/Util/CND/Fixtures/files/TestFile.php b/tests/PHPCR/Tests/Util/CND/Fixtures/files/TestFile.php index 4f3f098..b8db0e8 100644 --- a/tests/PHPCR/Tests/Util/CND/Fixtures/files/TestFile.php +++ b/tests/PHPCR/Tests/Util/CND/Fixtures/files/TestFile.php @@ -5,14 +5,14 @@ class TestClass { /** - * Block comment + * Block comment. */ public function testMethod($testParam) { // Line comment $string = 'This is a "Test // string"'; - return "Test string"; + return 'Test string'; } // String in "comment" diff --git a/tests/PHPCR/Tests/Util/CND/Reader/BufferReaderTest.php b/tests/PHPCR/Tests/Util/CND/Reader/BufferReaderTest.php index af07214..52a9d44 100644 --- a/tests/PHPCR/Tests/Util/CND/Reader/BufferReaderTest.php +++ b/tests/PHPCR/Tests/Util/CND/Reader/BufferReaderTest.php @@ -13,7 +13,7 @@ public function test__construct() $reader = new BufferReader($buffer); $this->assertInstanceOf(BufferReader::class, $reader); - $this->assertAttributeEquals(str_replace("\r\n", "\n", $buffer) . $reader->getEofMarker(), 'buffer', $reader); + $this->assertAttributeEquals(str_replace("\r\n", "\n", $buffer).$reader->getEofMarker(), 'buffer', $reader); $this->assertAttributeEquals(0, 'startPos', $reader); $this->assertAttributeEquals(0, 'forwardPos', $reader); diff --git a/tests/PHPCR/Tests/Util/CND/Reader/FileReaderTest.php b/tests/PHPCR/Tests/Util/CND/Reader/FileReaderTest.php index c65e6a9..cc9ca98 100644 --- a/tests/PHPCR/Tests/Util/CND/Reader/FileReaderTest.php +++ b/tests/PHPCR/Tests/Util/CND/Reader/FileReaderTest.php @@ -25,14 +25,14 @@ class FileReaderTest extends TestCase public function setUp() { - $this->filepath = __DIR__ . '/../Fixtures/files/TestFile.txt'; + $this->filepath = __DIR__.'/../Fixtures/files/TestFile.txt'; $this->reader = new FileReader($this->filepath); $this->lines = [ 'This is a test file...', '', '...containing dummy content.', - '' + '', ]; $this->chars = array_merge( diff --git a/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php b/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php index 1479cf5..1f31743 100644 --- a/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php +++ b/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php @@ -3,12 +3,12 @@ namespace PHPCR\Tests\Util\CND\Scanner; use ArrayIterator; -use PHPCR\Util\CND\Scanner\GenericScanner; use PHPCR\Util\CND\Reader\FileReader; +use PHPCR\Util\CND\Scanner\Context\DefaultScannerContext; +use PHPCR\Util\CND\Scanner\GenericScanner; use PHPCR\Util\CND\Scanner\GenericToken as Token; -use PHPCR\Util\CND\Scanner\TokenQueue; use PHPCR\Util\CND\Scanner\TokenFilter; -use PHPCR\Util\CND\Scanner\Context\DefaultScannerContext; +use PHPCR\Util\CND\Scanner\TokenQueue; use PHPUnit\Framework\TestCase; use Test; use TestClass; @@ -120,7 +120,7 @@ public function setUp() public function testScan() { - $reader = new FileReader(__DIR__ . '/../Fixtures/files/TestFile.php'); + $reader = new FileReader(__DIR__.'/../Fixtures/files/TestFile.php'); // Test the raw file with newlines and whitespaces $scanner = new GenericScanner(new DefaultScannerContext()); @@ -130,7 +130,7 @@ public function testScan() public function testFilteredScan() { - $reader = new FileReader(__DIR__ . '/../Fixtures/files/TestFile.php'); + $reader = new FileReader(__DIR__.'/../Fixtures/files/TestFile.php'); // Test the raw file with newlines and whitespaces $context = new DefaultScannerContext(); @@ -153,7 +153,7 @@ protected function assertTokens($tokens, TokenQueue $queue) while ($it->valid()) { $expectedToken = $it->current(); - $this->assertFalse($queue->isEof(), 'There is no more tokens, expected = ' . $expectedToken[1]); + $this->assertFalse($queue->isEof(), 'There is no more tokens, expected = '.$expectedToken[1]); $this->assertToken($expectedToken[0], $expectedToken[1], $token); diff --git a/tests/PHPCR/Tests/Util/Console/Command/BaseCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/BaseCommandTest.php index 21abea3..307b140 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/BaseCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/BaseCommandTest.php @@ -6,17 +6,17 @@ use PHPCR\Query\QueryManagerInterface; use PHPCR\Query\RowInterface; use PHPCR\RepositoryInterface; +use PHPCR\SessionInterface; use PHPCR\Tests\Stubs\MockNode; use PHPCR\Tests\Stubs\MockRow; -use PHPUnit_Framework_MockObject_MockObject; +use PHPCR\Util\Console\Helper\PhpcrConsoleDumperHelper; +use PHPCR\Util\Console\Helper\PhpcrHelper; +use PHPCR\WorkspaceInterface; use PHPUnit\Framework\TestCase; +use PHPUnit_Framework_MockObject_MockObject; use Symfony\Component\Console\Application; -use Symfony\Component\Console\Tester\CommandTester; use Symfony\Component\Console\Helper\HelperSet; -use PHPCR\SessionInterface; -use PHPCR\WorkspaceInterface; -use PHPCR\Util\Console\Helper\PhpcrConsoleDumperHelper; -use PHPCR\Util\Console\Helper\PhpcrHelper; +use Symfony\Component\Console\Tester\CommandTester; require_once __DIR__.'/../../../Stubs/MockNode.php'; require_once __DIR__.'/../../../Stubs/MockNodeTypeManager.php'; @@ -81,33 +81,28 @@ public function setUp() $this->dumperHelper = $this->getMockBuilder(PhpcrConsoleDumperHelper::class) ->disableOriginalConstructor() - ->getMock() - ; + ->getMock(); $this->helperSet = new HelperSet([ - 'phpcr' => new PhpcrHelper($this->session), + 'phpcr' => new PhpcrHelper($this->session), 'phpcr_console_dumper' => $this->dumperHelper, ]); $this->session->expects($this->any()) ->method('getWorkspace') - ->will($this->returnValue($this->workspace)) - ; + ->will($this->returnValue($this->workspace)); $this->workspace->expects($this->any()) ->method('getName') - ->will($this->returnValue('test')) - ; + ->will($this->returnValue('test')); $this->workspace->expects($this->any()) ->method('getQueryManager') - ->will($this->returnValue($this->queryManager)) - ; + ->will($this->returnValue($this->queryManager)); $this->queryManager->expects($this->any()) ->method('getSupportedQueryLanguages') - ->will($this->returnValue(['JCR-SQL2'])) - ; + ->will($this->returnValue(['JCR-SQL2'])); $this->application = new Application(); $this->application->setHelperSet($this->helperSet); diff --git a/tests/PHPCR/Tests/Util/Console/Command/NodeDumpCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodeDumpCommandTest.php index 46cfc57..f958c55 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodeDumpCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodeDumpCommandTest.php @@ -4,9 +4,9 @@ use Exception; use PHPCR\ItemNotFoundException; -use PHPCR\Util\UUIDHelper; -use PHPCR\Util\TreeWalker; use PHPCR\Util\Console\Command\NodeDumpCommand; +use PHPCR\Util\TreeWalker; +use PHPCR\Util\UUIDHelper; class NodeDumpCommandTest extends BaseCommandTest { @@ -18,8 +18,7 @@ public function setUp() parent::setUp(); $this->treeWalker = $this->getMockBuilder(TreeWalker::class) ->disableOriginalConstructor() - ->getMock() - ; + ->getMock(); $ndCommand = new NodeDumpCommand(); $this->application->add($ndCommand); @@ -30,21 +29,18 @@ public function testCommand() $this->dumperHelper ->expects($this->once()) ->method('getTreeWalker') - ->will($this->returnValue($this->treeWalker)) - ; + ->will($this->returnValue($this->treeWalker)); $this->session ->expects($this->once()) ->method('getNode') ->with('/') - ->will($this->returnValue($this->node1)) - ; + ->will($this->returnValue($this->node1)); $this->treeWalker ->expects($this->once()) ->method('traverse') - ->with($this->node1) - ; + ->with($this->node1); $this->executeCommand('phpcr:node:dump', []); } @@ -56,21 +52,18 @@ public function testCommandIdentifier() $this->dumperHelper ->expects($this->once()) ->method('getTreeWalker') - ->will($this->returnValue($this->treeWalker)) - ; + ->will($this->returnValue($this->treeWalker)); $this->session ->expects($this->once()) ->method('getNodeByIdentifier') ->with($uuid) - ->will($this->returnValue($this->node1)) - ; + ->will($this->returnValue($this->node1)); $this->treeWalker ->expects($this->once()) ->method('traverse') - ->with($this->node1) - ; + ->with($this->node1); $this->executeCommand('phpcr:node:dump', ['identifier' => $uuid]); } @@ -89,8 +82,7 @@ public function testNotFound() ->expects($this->once()) ->method('getNode') ->with('/') - ->will($this->throwException(new ItemNotFoundException())) - ; + ->will($this->throwException(new ItemNotFoundException())); $ct = $this->executeCommand('phpcr:node:dump', [], 1); $this->assertContains('does not exist', $ct->getDisplay()); diff --git a/tests/PHPCR/Tests/Util/Console/Command/NodeMoveCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodeMoveCommandTest.php index 3f0fcf5..132aafb 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodeMoveCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodeMoveCommandTest.php @@ -18,12 +18,10 @@ public function testCommand($args) { $this->session->expects($this->once()) ->method('move') - ->with($args['source'], $args['destination']) - ; + ->with($args['source'], $args['destination']); $this->session->expects($this->once()) - ->method('save') - ; + ->method('save'); $this->application->add(new NodeMoveCommand()); $this->executeCommand('phpcr:node:move', $args); diff --git a/tests/PHPCR/Tests/Util/Console/Command/NodeRemoveCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodeRemoveCommandTest.php index 822fe4a..f78bd10 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodeRemoveCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodeRemoveCommandTest.php @@ -22,7 +22,7 @@ public function testRemove() $this->executeCommand('phpcr:node:remove', [ '--force' => true, - 'path' => '/cms', + 'path' => '/cms', ]); } @@ -32,7 +32,7 @@ public function testRemoveRoot() $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 4d3d7d6..668aafb 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodeTouchCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodeTouchCommandTest.php @@ -6,11 +6,11 @@ use PHPCR\NodeType\NodeTypeInterface; use PHPCR\PathNotFoundException; use PHPCR\Tests\Stubs\MockNode; -use PHPCR\Util\Console\Helper\PhpcrHelper; use PHPCR\Util\Console\Command\NodeTouchCommand; +use PHPCR\Util\Console\Helper\PhpcrHelper; /** - * Currently very minimal test for touch command + * Currently very minimal test for touch command. */ class NodeTouchCommandTest extends BaseCommandTest { @@ -23,24 +23,21 @@ public function setUp() { parent::setUp(); - $command = new NodeTouchCommand; + $command = new NodeTouchCommand(); $this->application->add($command); // Override default concrete instance with mock $this->phpcrHelper = $this->getMockBuilder(PhpcrHelper::class) ->disableOriginalConstructor() - ->getMock() - ; + ->getMock(); $this->phpcrHelper->expects($this->any()) ->method('getSession') - ->will($this->returnValue($this->session)) - ; + ->will($this->returnValue($this->session)); $this->phpcrHelper->expects($this->any()) ->method('getName') - ->will($this->returnValue('phpcr')) - ; + ->will($this->returnValue('phpcr')); $this->helperSet->set($this->phpcrHelper); } @@ -59,14 +56,14 @@ public function testTouch() case '/cms': throw new PathNotFoundException(); } - throw new Exception('Unexpected ' . $path); + + throw new Exception('Unexpected '.$path); })); $this->node1->expects($this->once()) ->method('addNode') ->with('cms') - ->will($this->returnValue($child)) - ; + ->will($this->returnValue($child)); $this->session->expects($this->once()) ->method('save'); @@ -79,19 +76,16 @@ public function testUpdate() $nodeType = $this->createMock(NodeTypeInterface::class); $nodeType->expects($this->once()) ->method('getName') - ->will($this->returnValue('nt:unstructured')) - ; + ->will($this->returnValue('nt:unstructured')); $this->session->expects($this->exactly(1)) ->method('getNode') ->with('/cms') - ->will($this->returnValue($this->node1)) - ; + ->will($this->returnValue($this->node1)); $this->node1->expects($this->once()) ->method('getPrimaryNodeType') - ->will($this->returnValue($nodeType)) - ; + ->will($this->returnValue($nodeType)); $me = $this; @@ -100,21 +94,21 @@ public function testUpdate() ->will($this->returnCallback(function ($output, $node, $options) use ($me) { $me->assertEquals($me->node1, $node); $me->assertEquals([ - 'setProp' => ['foo=bar'], - 'removeProp' => ['bar'], - 'addMixins' => ['foo:bar'], + 'setProp' => ['foo=bar'], + 'removeProp' => ['bar'], + 'addMixins' => ['foo:bar'], 'removeMixins' => ['bar:foo'], - 'dump' => true, + 'dump' => true, ], $options); })); $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/NodeTypeListCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodeTypeListCommandTest.php index d25dd73..d906e7c 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodeTypeListCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodeTypeListCommandTest.php @@ -20,26 +20,22 @@ public function setUp() $this->application->add(new NodeTypeListCommand()); $this->nodeTypeManager = $this->getMockBuilder(MockNodeTypeManager::class) ->disableOriginalConstructor() - ->getMock() - ; + ->getMock(); } public function testNodeTypeList() { $this->session->expects($this->once()) ->method('getWorkspace') - ->will($this->returnValue($this->workspace)) - ; + ->will($this->returnValue($this->workspace)); $this->workspace->expects($this->once()) ->method('getNodeTypeManager') - ->will($this->returnValue($this->nodeTypeManager)) - ; + ->will($this->returnValue($this->nodeTypeManager)); $this->nodeTypeManager->expects($this->once()) ->method('getAllNodeTypes') - ->will($this->returnValue([])) - ; + ->will($this->returnValue([])); $this->executeCommand('phpcr:node-type:list', []); } diff --git a/tests/PHPCR/Tests/Util/Console/Command/NodeTypeRegisterCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodeTypeRegisterCommandTest.php index 06e3f7b..8618bc5 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodeTypeRegisterCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodeTypeRegisterCommandTest.php @@ -20,21 +20,18 @@ public function setUp() $this->application->add(new NodeTypeRegisterCommand()); $this->nodeTypeManager = $this->getMockBuilder(MockNodeTypeManager::class) ->disableOriginalConstructor() - ->getMock() - ; + ->getMock(); } public function testNodeTypeRegister() { $this->session->expects($this->once()) ->method('getWorkspace') - ->will($this->returnValue($this->workspace)) - ; + ->will($this->returnValue($this->workspace)); $this->workspace->expects($this->once()) ->method('getNodeTypeManager') - ->will($this->returnValue($this->nodeTypeManager)) - ; + ->will($this->returnValue($this->nodeTypeManager)); $this->nodeTypeManager->expects($this->once()) ->method('registerNodeTypesCnd'); diff --git a/tests/PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php index b07b67e..c93f7a8 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php @@ -31,11 +31,11 @@ public function provideNodeUpdate() [['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', ]], ]; } @@ -46,31 +46,26 @@ protected function setupQueryManager($options) $this->session->expects($this->any()) ->method('getWorkspace') - ->will($this->returnValue($this->workspace)) - ; + ->will($this->returnValue($this->workspace)); $this->workspace->expects($this->any()) ->method('getQueryManager') - ->will($this->returnValue($this->queryManager)) - ; + ->will($this->returnValue($this->queryManager)); $this->queryManager->expects($this->any()) ->method('createQuery') ->with($options['query'], 'JCR-SQL2') - ->will($this->returnValue($this->query)) - ; + ->will($this->returnValue($this->query)); $this->query->expects($this->any()) ->method('execute') ->will($this->returnValue([ $this->row1, - ])) - ; + ])); $this->row1->expects($this->any()) ->method('getNode') - ->will($this->returnValue($this->node1)) - ; + ->will($this->returnValue($this->node1)); } /** @@ -79,12 +74,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']) { @@ -94,12 +89,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' => [], ]; foreach ($options['setProp'] as $setProp) { @@ -141,13 +136,13 @@ 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'); - } + }, ], ]; @@ -155,13 +150,11 @@ function ($session, $node) { $this->node1->expects($this->exactly(2)) ->method('setProperty') - ->with('foo', 'bar') - ; + ->with('foo', 'bar'); $this->session->expects($this->once()) ->method('getNodeByIdentifier') - ->with('/foo') - ; + ->with('/foo'); $this->executeCommand('phpcr:nodes:update', $args); } diff --git a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceCreateCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceCreateCommandTest.php index ce07824..9e9a15f 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceCreateCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceCreateCommandTest.php @@ -2,8 +2,8 @@ namespace PHPCR\Tests\Util\Console\Command; -use PHPCR\Util\Console\Command\WorkspaceCreateCommand; use PHPCR\RepositoryInterface; +use PHPCR\Util\Console\Command\WorkspaceCreateCommand; class WorkspaceCreateCommandTest extends BaseCommandTest { @@ -18,32 +18,27 @@ public function testCreate() { $this->session->expects($this->once()) ->method('getWorkspace') - ->will($this->returnValue($this->workspace)) - ; + ->will($this->returnValue($this->workspace)); $this->session->expects($this->once()) ->method('getRepository') - ->will($this->returnValue($this->repository)) - ; + ->will($this->returnValue($this->repository)); $this->repository->expects($this->once()) ->method('getDescriptor') ->with(RepositoryInterface::OPTION_WORKSPACE_MANAGEMENT_SUPPORTED) - ->will($this->returnValue(true)) - ; + ->will($this->returnValue(true)); $this->workspace->expects($this->once()) ->method('createWorkspace') - ->with('test_workspace') - ; + ->with('test_workspace'); $this->workspace->expects($this->once()) ->method('getAccessibleWorkspaceNames') - ->will($this->returnValue(['default'])) - ; + ->will($this->returnValue(['default'])); $this->executeCommand('phpcr:workspace:create', [ - 'name' => 'test_workspace' + 'name' => 'test_workspace', ]); } @@ -54,24 +49,20 @@ public function testCreateExisting() { $this->session->expects($this->exactly(2)) ->method('getWorkspace') - ->will($this->returnValue($this->workspace)) - ; + ->will($this->returnValue($this->workspace)); $this->session->expects($this->exactly(2)) ->method('getRepository') - ->will($this->returnValue($this->repository)) - ; + ->will($this->returnValue($this->repository)); $this->repository->expects($this->exactly(2)) ->method('getDescriptor') ->with(RepositoryInterface::OPTION_WORKSPACE_MANAGEMENT_SUPPORTED) - ->will($this->returnValue(true)) - ; + ->will($this->returnValue(true)); $this->workspace->expects($this->exactly(2)) ->method('getAccessibleWorkspaceNames') - ->will($this->returnValue(['default', 'test'])) - ; + ->will($this->returnValue(['default', 'test'])); $tester = $this->executeCommand( 'phpcr:workspace:create', @@ -84,8 +75,8 @@ public function testCreateExisting() $tester = $this->executeCommand( 'phpcr:workspace:create', [ - 'name' => 'test', - '--ignore-existing' => true + '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 d17c40e..c660f1d 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceDeleteCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceDeleteCommandTest.php @@ -2,8 +2,8 @@ namespace PHPCR\Tests\Util\Console\Command; -use PHPCR\Util\Console\Command\WorkspaceDeleteCommand; use PHPCR\RepositoryInterface; +use PHPCR\Util\Console\Command\WorkspaceDeleteCommand; class WorkspaceDeleteCommandTest extends BaseCommandTest { @@ -18,32 +18,27 @@ public function testDelete() { $this->session->expects($this->once()) ->method('getWorkspace') - ->will($this->returnValue($this->workspace)) - ; + ->will($this->returnValue($this->workspace)); $this->workspace->expects($this->once()) ->method('getAccessibleWorkspaceNames') - ->will($this->returnValue(['default', 'test_workspace', 'other'])) - ; + ->will($this->returnValue(['default', 'test_workspace', 'other'])); $this->session->expects($this->once()) ->method('getRepository') - ->will($this->returnValue($this->repository)) - ; + ->will($this->returnValue($this->repository)); $this->repository->expects($this->once()) ->method('getDescriptor') ->with(RepositoryInterface::OPTION_WORKSPACE_MANAGEMENT_SUPPORTED) - ->will($this->returnValue(true)) - ; + ->will($this->returnValue(true)); $this->workspace->expects($this->once()) ->method('deleteWorkspace') - ->with('test_workspace') - ; + ->with('test_workspace'); $ct = $this->executeCommand('phpcr:workspace:delete', [ - 'name' => 'test_workspace', + 'name' => 'test_workspace', '--force' => 'true', ]); @@ -54,16 +49,14 @@ public function testDeleteNonexistent() { $this->session->expects($this->once()) ->method('getWorkspace') - ->will($this->returnValue($this->workspace)) - ; + ->will($this->returnValue($this->workspace)); $this->workspace->expects($this->once()) ->method('getAccessibleWorkspaceNames') - ->will($this->returnValue(['default', 'other'])) - ; + ->will($this->returnValue(['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/WorkspaceExportCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceExportCommandTest.php index 578c79b..1a73da4 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceExportCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceExportCommandTest.php @@ -2,8 +2,8 @@ namespace PHPCR\Tests\Util\Console\Command; -use PHPCR\Util\Console\Command\WorkspaceExportCommand; use PHPCR\RepositoryInterface; +use PHPCR\Util\Console\Command\WorkspaceExportCommand; class WorkspaceExportCommandTest extends BaseCommandTest { @@ -36,7 +36,7 @@ public function testNodeTypeList() $this->assertFileNotExists('test', 'test export file must not exist, it will be overwritten'); $ct = $this->executeCommand('phpcr:workspace:export', [ - 'filename' => 'test' + 'filename' => 'test', ]); if (method_exists($ct, 'getStatusCode')) { diff --git a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceImportCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceImportCommandTest.php index 99679d9..cd0049d 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceImportCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceImportCommandTest.php @@ -2,8 +2,8 @@ namespace PHPCR\Tests\Util\Console\Command; -use PHPCR\Util\Console\Command\WorkspaceImportCommand; use PHPCR\RepositoryInterface; +use PHPCR\Util\Console\Command\WorkspaceImportCommand; class WorkspaceImportCommandTest extends BaseCommandTest { @@ -29,7 +29,7 @@ public function testNodeTypeList() ->method('importXml'); $ct = $this->executeCommand('phpcr:workspace:import', [ - 'filename' => 'test_import.xml' + 'filename' => 'test_import.xml', ]); $this->assertContains('Successfully imported', $ct->getDisplay()); diff --git a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceListCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceListCommandTest.php index 36c6c00..ef1f507 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceListCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceListCommandTest.php @@ -22,13 +22,13 @@ public function testNodeTypeList() $this->workspace->expects($this->once()) ->method('getAccessibleWorkspaceNames') ->will($this->returnValue([ - 'foo', 'bar' + 'foo', 'bar', ])); $ct = $this->executeCommand('phpcr:workspace:list', [ ]); - $expected = <<outputMock = $this->createMock(OutputInterface::class); - $this->helper = new PhpcrConsoleDumperHelper; + $this->helper = new PhpcrConsoleDumperHelper(); } public function provideHelper() @@ -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); diff --git a/tests/PHPCR/Tests/Util/NodeHelperTest.php b/tests/PHPCR/Tests/Util/NodeHelperTest.php index 634d153..7ca98ff 100644 --- a/tests/PHPCR/Tests/Util/NodeHelperTest.php +++ b/tests/PHPCR/Tests/Util/NodeHelperTest.php @@ -4,8 +4,8 @@ use PHPCR\Tests\Stubs\MockNode; use PHPCR\Util\NodeHelper; -use PHPUnit_Framework_MockObject_MockObject; use PHPUnit\Framework\TestCase; +use PHPUnit_Framework_MockObject_MockObject; require_once __DIR__.'/../Stubs/MockNode.php'; @@ -89,26 +89,22 @@ public function testIsSystemItem() $sys->expects($this->once()) ->method('getDepth') - ->will($this->returnValue(0)) - ; + ->will($this->returnValue(0)); $sys->expects($this->once()) ->method('getName') - ->will($this->returnValue('jcr:root')) - ; + ->will($this->returnValue('jcr:root')); $this->assertTrue(NodeHelper::isSystemItem($sys)); $sys = $this->createMock(MockNode::class); $sys->expects($this->once()) ->method('getDepth') - ->will($this->returnValue(1)) - ; + ->will($this->returnValue(1)); $sys->expects($this->once()) ->method('getName') - ->will($this->returnValue('jcr:system')) - ; + ->will($this->returnValue('jcr:system')); $this->assertTrue(NodeHelper::isSystemItem($sys)); @@ -116,13 +112,12 @@ public function testIsSystemItem() $top = $this->createMock(MockNode::class); $top->expects($this->once()) ->method('getDepth') - ->will($this->returnValue(1)) - ; + ->will($this->returnValue(1)); $top->expects($this->once()) ->method('getName') ->will($this->returnValue('jcrname')) // this is NOT in the jcr namespace - ; +; $this->assertFalse(NodeHelper::isSystemItem($top)); @@ -130,8 +125,7 @@ public function testIsSystemItem() $deep = $this->createMock(MockNode::class); $deep->expects($this->once()) ->method('getDepth') - ->will($this->returnValue(2)) - ; + ->will($this->returnValue(2)); $this->assertFalse(NodeHelper::isSystemItem($deep)); } @@ -189,7 +183,7 @@ public function testCalculateOrderBeforeDeleted() $reorders = NodeHelper::calculateOrderBefore($old, $new); $expected = [ - 'two' => null, + 'two' => null, 'one' => 'three', // TODO: this is an unnecessary but harmless NOOP. we should try to eliminate ]; @@ -204,7 +198,7 @@ public function testBenchmarkOrderBeforeArray() $nodes = []; for ($i = 0; $i < 100000; $i++) { - $nodes[] = 'test' . $i; + $nodes[] = 'test'.$i; } $start = microtime(true); diff --git a/tests/PHPCR/Tests/Util/PathHelperTest.php b/tests/PHPCR/Tests/Util/PathHelperTest.php index 78f6239..32d7116 100644 --- a/tests/PHPCR/Tests/Util/PathHelperTest.php +++ b/tests/PHPCR/Tests/Util/PathHelperTest.php @@ -5,8 +5,8 @@ use PHPCR\NamespaceException; use PHPCR\RepositoryException; use PHPCR\Util\PathHelper; -use stdClass; use PHPUnit\Framework\TestCase; +use stdClass; class PathHelperTest extends TestCase { @@ -124,7 +124,7 @@ public function dataproviderInvalidLocalNames() ['jcr:nodename'], ['/path'], ['.'], - ['..'] + ['..'], ]; } diff --git a/tests/PHPCR/Tests/Util/QOM/QueryBuilderTest.php b/tests/PHPCR/Tests/Util/QOM/QueryBuilderTest.php index a99fa92..8c69833 100644 --- a/tests/PHPCR/Tests/Util/QOM/QueryBuilderTest.php +++ b/tests/PHPCR/Tests/Util/QOM/QueryBuilderTest.php @@ -11,8 +11,8 @@ use PHPCR\Query\QOM\SameNodeJoinConditionInterface; use PHPCR\Query\QOM\SourceInterface; use PHPCR\Util\QOM\QueryBuilder; -use PHPUnit_Framework_MockObject_MockObject; use PHPUnit\Framework\TestCase; +use PHPUnit_Framework_MockObject_MockObject; use RuntimeException; class QueryBuilderTest extends TestCase @@ -53,8 +53,7 @@ private function createDynamicOperandMock() $dynamicOperand = $this->getMockBuilder(DynamicOperandInterface::class) ->setMethods([]) ->setConstructorArgs([]) - ->getMock() - ; + ->getMock(); return $dynamicOperand; } @@ -146,8 +145,7 @@ private function createConstraintMock() $constraint = $this->getMockBuilder(ConstraintInterface::class) ->setMethods([]) ->setConstructorArgs([]) - ->getMock() - ; + ->getMock(); return $constraint; } @@ -268,8 +266,7 @@ public function testJoin() $source2, $this->equalTo(QueryObjectModelConstantsInterface::JCR_JOIN_TYPE_INNER), $joinCondition - ) - ; + ); $qb = new QueryBuilder($this->qf); $qb->from($source1); @@ -289,8 +286,7 @@ public function testRightJoin() $source2, $this->equalTo(QueryObjectModelConstantsInterface::JCR_JOIN_TYPE_RIGHT_OUTER), $joinCondition - ) - ; + ); $qb = new QueryBuilder($this->qf); $qb->from($source1); @@ -310,8 +306,7 @@ public function testLeftJoin() $source2, $this->equalTo(QueryObjectModelConstantsInterface::JCR_JOIN_TYPE_LEFT_OUTER), $joinCondition - ) - ; + ); $qb = new QueryBuilder($this->qf); $qb->from($source1); @@ -343,8 +338,7 @@ private function createQueryMock() $query = $this->getMockBuilder(QueryObjectModelInterface::class) ->setMethods([]) ->setConstructorArgs([]) - ->getMock() - ; + ->getMock(); return $query; } diff --git a/tests/PHPCR/Tests/Util/QOM/Sql1GeneratorTest.php b/tests/PHPCR/Tests/Util/QOM/Sql1GeneratorTest.php index 4909138..e956916 100644 --- a/tests/PHPCR/Tests/Util/QOM/Sql1GeneratorTest.php +++ b/tests/PHPCR/Tests/Util/QOM/Sql1GeneratorTest.php @@ -84,9 +84,9 @@ public function testFullTextSearch() public function testColumns() { $literal = $this->generator->evalColumns(null); - $this->assertSame("s", $literal); + $this->assertSame('s', $literal); $literal = $this->generator->evalColumns(['bar', 'foo']); - $this->assertSame("bar, foo", $literal); + $this->assertSame('bar, foo', $literal); } public function testPropertyValue() diff --git a/tests/PHPCR/Tests/Util/ValueConverterTest.php b/tests/PHPCR/Tests/Util/ValueConverterTest.php index 02474b1..8a18d30 100644 --- a/tests/PHPCR/Tests/Util/ValueConverterTest.php +++ b/tests/PHPCR/Tests/Util/ValueConverterTest.php @@ -1,4 +1,5 @@ expects($this->any()) ->method('getIdentifier') - ->will($this->returnValue('38b7cf18-c417-477a-af0b-c1e92a290c9a')) - ; + ->will($this->returnValue('38b7cf18-c417-477a-af0b-c1e92a290c9a')); $nodeMock ->expects($this->any()) ->method('isNodeType') ->with('mix:referenceable') - ->will($this->returnValue(true)) - ; + ->will($this->returnValue(true)); return [ // String to... @@ -133,7 +132,7 @@ public function dataConversionMatrix() [123.1, PropertyType::DOUBLE, '123.1', PropertyType::DECIMAL], // Date to... - [$datetimeLong, PropertyType::DATE, $datetimeLong->format('Y-m-d\TH:i:s.') . substr($datetimeLong->format('u'), 0, 3) . $datetimeLong->format('P'), PropertyType::STRING], + [$datetimeLong, PropertyType::DATE, $datetimeLong->format('Y-m-d\TH:i:s.').substr($datetimeLong->format('u'), 0, 3).$datetimeLong->format('P'), PropertyType::STRING], [$datetimeLong, PropertyType::DATE, 123, PropertyType::LONG], [$datetimeLong, PropertyType::DATE, 123.0, PropertyType::DOUBLE], [$datetimeLong, PropertyType::DATE, $datetimeLong, PropertyType::DATE], @@ -271,10 +270,10 @@ public function dataConversionMatrix() } /** - * Skip binary target as its a special case + * Skip binary target as its a special case. * * @param mixed $value - * @param int $srcType PropertyType constant to convert from + * @param int $srcType PropertyType constant to convert from * @param $expected * @param $targetType * @@ -396,8 +395,7 @@ public function testConvertNewNode() $nodeMock ->expects($this->never()) ->method('isNew') - ->will($this->returnValue(true)) - ; + ->will($this->returnValue(true)); $this->valueConverter->convertType($nodeMock, PropertyType::STRING); } @@ -409,14 +407,12 @@ public function testConvertNonRefNode() $nodeMock ->expects($this->never()) ->method('isNew') - ->will($this->returnValue(false)) - ; + ->will($this->returnValue(false)); $nodeMock ->expects($this->once()) ->method('isNodeType') ->with('mix:referenceable') - ->will($this->returnValue(false)) - ; + ->will($this->returnValue(false)); $this->valueConverter->convertType($nodeMock, PropertyType::STRING); } @@ -430,7 +426,7 @@ public function dataDateTargetType() } /** - * Check if the util will survive a broken implementation + * Check if the util will survive a broken implementation. * * @dataProvider dataDateTargetType */ diff --git a/tests/bootstrap.php b/tests/bootstrap.php index 93b3d87..5a41be2 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -1,9 +1,10 @@ * @license http://www.apache.org/licenses/LICENSE-2.0 Apache Software License 2.0 + * * @link http://phpcr.github.io/ */ if (!class_exists('PHPUnit_Framework_TestCase') || From 3ab1b2351382a4d90b79e9084be399b5e6198d59 Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Mon, 18 Dec 2017 10:44:51 +0100 Subject: [PATCH 22/88] adjust tests to cs --- tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php b/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php index 1f31743..14bda9b 100644 --- a/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php +++ b/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php @@ -44,7 +44,7 @@ class GenericScannerTest extends TestCase // /** ... */ [Token::TK_WHITESPACE, ''], - [Token::TK_COMMENT, "/**\n * Block comment\n */"], + [Token::TK_COMMENT, "/**\n * Block comment.\n */"], [Token::TK_NEWLINE, ''], // public function testMethod($testParam) { @@ -86,7 +86,7 @@ class GenericScannerTest extends TestCase [Token::TK_WHITESPACE, ''], [Token::TK_IDENTIFIER, 'return'], [Token::TK_WHITESPACE, ''], - [Token::TK_STRING, '"Test string"'], + [Token::TK_STRING, '\'Test string\''], [Token::TK_SYMBOL, ';'], [Token::TK_NEWLINE, ''], From eca206aa5c99f9b5e1c5585ec8170f072c36f26b Mon Sep 17 00:00:00 2001 From: Gabriel Caruso Date: Tue, 16 Jan 2018 20:54:48 -0200 Subject: [PATCH 23/88] Simplify returns --- src/PHPCR/Util/Console/Command/NodeTypeRegisterCommand.php | 6 +----- src/PHPCR/Util/UUIDHelper.php | 6 +----- 2 files changed, 2 insertions(+), 10 deletions(-) diff --git a/src/PHPCR/Util/Console/Command/NodeTypeRegisterCommand.php b/src/PHPCR/Util/Console/Command/NodeTypeRegisterCommand.php index 2020bcc..4072734 100644 --- a/src/PHPCR/Util/Console/Command/NodeTypeRegisterCommand.php +++ b/src/PHPCR/Util/Console/Command/NodeTypeRegisterCommand.php @@ -167,10 +167,6 @@ protected function getFilePaths($definitions) protected function fileIsNodeType($filename) { - if (substr($filename, -4) === '.cnd') { - return true; - } - - return false; + return substr($filename, -4) === '.cnd'; } } diff --git a/src/PHPCR/Util/UUIDHelper.php b/src/PHPCR/Util/UUIDHelper.php index faaa39f..130c365 100644 --- a/src/PHPCR/Util/UUIDHelper.php +++ b/src/PHPCR/Util/UUIDHelper.php @@ -22,11 +22,7 @@ class UUIDHelper public static function isUUID($id) { // UUID is HEX_CHAR{8}-HEX_CHAR{4}-HEX_CHAR{4}-HEX_CHAR{4}-HEX_CHAR{12} - if (1 === preg_match('/^[[:xdigit:]]{8}-[[:xdigit:]]{4}-[[:xdigit:]]{4}-[[:xdigit:]]{4}-[[:xdigit:]]{12}$/', $id)) { - return true; - } - - return false; + return 1 === preg_match('/^[[:xdigit:]]{8}-[[:xdigit:]]{4}-[[:xdigit:]]{4}-[[:xdigit:]]{4}-[[:xdigit:]]{12}$/', $id); } /** From a5ac217e46ff300a3654341cb2c4cb529dfcc03b Mon Sep 17 00:00:00 2001 From: Johannes Wachter Date: Mon, 5 Feb 2018 15:48:32 +0100 Subject: [PATCH 24/88] added option to control the uuid-behavior --- .../Command/WorkspaceImportCommand.php | 33 ++++++++++++++++--- .../Command/WorkspaceImportCommandTest.php | 29 ++++++++++++++-- 2 files changed, 55 insertions(+), 7 deletions(-) diff --git a/src/PHPCR/Util/Console/Command/WorkspaceImportCommand.php b/src/PHPCR/Util/Console/Command/WorkspaceImportCommand.php index cf327c1..185d747 100644 --- a/src/PHPCR/Util/Console/Command/WorkspaceImportCommand.php +++ b/src/PHPCR/Util/Console/Command/WorkspaceImportCommand.php @@ -17,6 +17,13 @@ */ class WorkspaceImportCommand extends BaseCommand { + 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, + ]; + /** * {@inheritdoc} */ @@ -28,6 +35,7 @@ protected function configure() ->setName('phpcr:workspace:import') ->addArgument('filename', null, 'The xml file to import') ->addOption('parentpath', 'p', InputOption::VALUE_OPTIONAL, 'Repository path to the parent where to import the file contents', '/') + ->addOption('uuid-behavior', null, InputOption::VALUE_REQUIRED, 'How to handle UUID collisions during the import', 'new') ->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 @@ -38,6 +46,17 @@ protected function configure() 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 ); } @@ -58,11 +77,15 @@ protected function execute(InputInterface $input, OutputInterface $output) return 1; } - $session->importXML( - $parentPath, - $filename, - ImportUUIDBehaviorInterface::IMPORT_UUID_CREATE_NEW - ); + $uuidBehavior = $input->getOption('uuid-behavior'); + if (!array_key_exists($uuidBehavior, self::UUID_BEHAVIOR)) { + $output->writeln(sprintf('UUID-Behavior "%s" is not supported', $uuidBehavior)); + $output->writeln(sprintf('Supported behaviors are %s', implode(', ', array_keys(self::UUID_BEHAVIOR)))); + + return 1; + } + + $session->importXML($parentPath, $filename, self::UUID_BEHAVIOR[$uuidBehavior]); $session->save(); $output->writeln(sprintf( diff --git a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceImportCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceImportCommandTest.php index cd0049d..f74adb6 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceImportCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceImportCommandTest.php @@ -2,6 +2,7 @@ namespace PHPCR\Tests\Util\Console\Command; +use PHPCR\ImportUUIDBehaviorInterface; use PHPCR\RepositoryInterface; use PHPCR\Util\Console\Command\WorkspaceImportCommand; @@ -14,7 +15,7 @@ public function setUp() $this->application->add(new WorkspaceImportCommand()); } - public function testNodeTypeList() + public function testImport() { $this->session->expects($this->once()) ->method('getRepository') @@ -26,7 +27,8 @@ public function testNodeTypeList() ->will($this->returnValue(true)); $this->session->expects($this->once()) - ->method('importXml'); + ->method('importXml') + ->with('/', 'test_import.xml', ImportUUIDBehaviorInterface::IMPORT_UUID_CREATE_NEW); $ct = $this->executeCommand('phpcr:workspace:import', [ 'filename' => 'test_import.xml', @@ -34,4 +36,27 @@ public function testNodeTypeList() $this->assertContains('Successfully imported', $ct->getDisplay()); } + + public function testImportUuidBehaviorThrow() + { + $this->session->expects($this->once()) + ->method('getRepository') + ->will($this->returnValue($this->repository)); + + $this->repository->expects($this->once()) + ->method('getDescriptor') + ->with(RepositoryInterface::OPTION_XML_IMPORT_SUPPORTED) + ->will($this->returnValue(true)); + + $this->session->expects($this->once()) + ->method('importXml') + ->with('/', 'test_import.xml', ImportUUIDBehaviorInterface::IMPORT_UUID_COLLISION_THROW); + + $ct = $this->executeCommand('phpcr:workspace:import', [ + 'filename' => 'test_import.xml', + '--uuid-behavior' => 'throw', + ]); + + $this->assertContains('Successfully imported', $ct->getDisplay()); + } } From 7301518ab9080b125868e41d0db855b8115c82a3 Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Tue, 6 Feb 2018 17:53:00 +0100 Subject: [PATCH 25/88] update changelog --- CHANGELOG.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 17c9b17..a56732a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,25 @@ Changelog ========= +1.4.0 +----- + +* Added option to phpcr:workspace:import command to be able to specify the UUID behavior on collisions during import + +1.3.2 +----- + +* Support Symfony 4 + +1.3.1 +----- + +* Support for PHP 7.2 + +1.3.0 +----- + +* Support for PHP 5.6/7.0/7.1 * **2017-11-18**: Removed hhvm test 1.2.7 From 9c3a01902b41459d41a611b0f0f165b7c5b37043 Mon Sep 17 00:00:00 2001 From: Johannes Wachter Date: Mon, 12 Feb 2018 15:26:09 +0100 Subject: [PATCH 26/88] changed static variable to const --- .../Util/Console/Command/WorkspaceImportCommand.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/PHPCR/Util/Console/Command/WorkspaceImportCommand.php b/src/PHPCR/Util/Console/Command/WorkspaceImportCommand.php index c5980cb..cd12d3f 100644 --- a/src/PHPCR/Util/Console/Command/WorkspaceImportCommand.php +++ b/src/PHPCR/Util/Console/Command/WorkspaceImportCommand.php @@ -18,12 +18,12 @@ */ class WorkspaceImportCommand extends BaseCommand { - private static $uuidBehavior = array( + 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, - ); + ]; /** * {@inheritDoc} @@ -80,14 +80,14 @@ protected function execute(InputInterface $input, OutputInterface $output) } $uuidBehavior = $input->getOption('uuid-behavior'); - if (!array_key_exists($uuidBehavior, self::$uuidBehavior)) { + if (!array_key_exists($uuidBehavior, self::UUID_BEHAVIOR)) { $output->writeln(sprintf('UUID-Behavior "%s" is not supported', $uuidBehavior)); - $output->writeln(sprintf('Supported behaviors are %s', implode(', ', array_keys(self::$uuidBehavior)))); + $output->writeln(sprintf('Supported behaviors are %s', implode(', ', array_keys(self::UUID_BEHAVIOR)))); return 1; } - $session->importXML($parentPath, $filename, self::$uuidBehavior[$uuidBehavior]); + $session->importXML($parentPath, $filename, self::UUID_BEHAVIOR[$uuidBehavior]); $session->save(); $output->writeln(sprintf( From d30f84f6f38bb23d3b449dcb61bc79c6802492a0 Mon Sep 17 00:00:00 2001 From: Johannes Wachter Date: Tue, 13 Feb 2018 08:03:21 +0100 Subject: [PATCH 27/88] removed unused option in testcase --- .../PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php index 3d6b194..b07b67e 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php @@ -94,7 +94,6 @@ public function testNodeUpdate($options) $this->setupQueryManager($options); $args = [ - '--query-language' => 'jcr-sql2', '--query' => $options['query'], '--no-interaction' => true, '--set-prop' => [], From 4d87b2360c5aa4f87b156825278d970b58f6ffa1 Mon Sep 17 00:00:00 2001 From: Alexander Schranz Date: Wed, 20 Nov 2019 00:27:52 +0100 Subject: [PATCH 28/88] Add support for symfony 5 --- .travis.yml | 6 ++++++ composer.json | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 129c8f7..9fb4428 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,6 +5,7 @@ php: - 7.0 - 7.1 - 7.2 + - 7.3 env: - PACKAGE_VERSION=high @@ -15,9 +16,14 @@ matrix: include: - php: 5.6 env: PACKAGE_VERSION=low + - php: 7.3 + env: + - PACKAGE_VERSION=high + - MINIMUM_STABILITY=dev before_script: - composer selfupdate + - if [[ "$MINIMUM_STABILITY" ]]; then composer config minimum-stability $MINIMUM_STABILITY ; fi - if [[ "$PACKAGE_VERSION" == "high" ]]; then composer update --prefer-source; fi - if [[ "$PACKAGE_VERSION" == "low" ]]; then composer update --prefer-lowest --prefer-source; fi diff --git a/composer.json b/composer.json index 60fdb35..f83ef9b 100644 --- a/composer.json +++ b/composer.json @@ -29,7 +29,7 @@ "require": { "php": "^5.6|^7.0", "phpcr/phpcr": "~2.1.0", - "symfony/console": "~2.3|~3.0|^4.0" + "symfony/console": "~2.3|~3.0|^4.0|^5.0" }, "require-dev": { "ramsey/uuid": "^3.5", From d21e3910ca45cd635ead3d973cc3ad6eb80a1b46 Mon Sep 17 00:00:00 2001 From: Alexander Schranz Date: Sat, 23 Nov 2019 11:23:34 +0100 Subject: [PATCH 29/88] Update dev branch alias --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index f83ef9b..4957ff3 100644 --- a/composer.json +++ b/composer.json @@ -49,7 +49,7 @@ "bin": ["bin/phpcr"], "extra": { "branch-alias": { - "dev-master": "1.3-dev" + "dev-master": "1.4-dev" } } } From ed112a3e5c50e8921b198f8ba55d359c9d9e5535 Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Mon, 9 Dec 2019 09:46:13 +0100 Subject: [PATCH 30/88] test with php 7.4 --- .travis.yml | 5 +++-- CHANGELOG.md | 6 ++++++ composer.json | 8 ++++---- phpunit.xml.dist | 15 +++++++++++++++ tests/bootstrap.php | 9 --------- tests/phpunit.xml.dist | 20 -------------------- 6 files changed, 28 insertions(+), 35 deletions(-) create mode 100644 phpunit.xml.dist delete mode 100644 tests/phpunit.xml.dist diff --git a/.travis.yml b/.travis.yml index 9fb4428..2e33f67 100644 --- a/.travis.yml +++ b/.travis.yml @@ -6,6 +6,7 @@ php: - 7.1 - 7.2 - 7.3 + - 7.4 env: - PACKAGE_VERSION=high @@ -16,7 +17,7 @@ matrix: include: - php: 5.6 env: PACKAGE_VERSION=low - - php: 7.3 + - php: 7.4 env: - PACKAGE_VERSION=high - MINIMUM_STABILITY=dev @@ -27,7 +28,7 @@ before_script: - if [[ "$PACKAGE_VERSION" == "high" ]]; then composer update --prefer-source; fi - if [[ "$PACKAGE_VERSION" == "low" ]]; then composer update --prefer-lowest --prefer-source; fi -script: php vendor/bin/phpunit -c tests/phpunit.xml.dist +script: php vendor/bin/phpunit notifications: irc: "irc.freenode.org#jackalope" diff --git a/CHANGELOG.md b/CHANGELOG.md index a56732a..9209011 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,12 @@ Changelog ========= +1.4.1 +----- + +* Support Symfony 5 +* Test with PHP 7.3 and 7.4 + 1.4.0 ----- diff --git a/composer.json b/composer.json index 4957ff3..260727d 100644 --- a/composer.json +++ b/composer.json @@ -27,16 +27,16 @@ } ], "require": { - "php": "^5.6|^7.0", + "php": "^5.6 || ^7.0", "phpcr/phpcr": "~2.1.0", - "symfony/console": "~2.3|~3.0|^4.0|^5.0" + "symfony/console": "^2.3|^3.0|^4.0|^5.0" }, "require-dev": { "ramsey/uuid": "^3.5", - "phpunit/phpunit": "^5.7" + "phpunit/phpunit": "^5.7 || ^6.0 || ^7.0" }, "suggest": { - "ramsey/uuid": "A PHP 5.4+ library for generating RFC 4122 version 1, 3, 4, and 5 universally unique identifiers (UUID)." + "ramsey/uuid": "A library for generating RFC 4122 version 1, 3, 4, and 5 universally unique identifiers (UUID)." }, "conflict": { "jackalope/jackalope-jackrabbit": "<1.2.1" diff --git a/phpunit.xml.dist b/phpunit.xml.dist new file mode 100644 index 0000000..42bb21e --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1,15 @@ + + + + + + ./tests + + + diff --git a/tests/bootstrap.php b/tests/bootstrap.php index 5a41be2..cabe086 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -7,15 +7,6 @@ * * @link http://phpcr.github.io/ */ -if (!class_exists('PHPUnit_Framework_TestCase') || - version_compare(PHPUnit_Runner_Version::id(), '3.5') < 0 -) { - die('PHPUnit framework is required, at least 3.5 version'); -} - -if (!class_exists('PHPUnit_Framework_MockObject_MockBuilder')) { - die('PHPUnit MockObject plugin is required, at least 1.0.8 version'); -} // $file2 for run tests if phpcr-utils lib inside of vendor directory. $file = __DIR__.'/../vendor/autoload.php'; diff --git a/tests/phpunit.xml.dist b/tests/phpunit.xml.dist deleted file mode 100644 index 6fd2fb1..0000000 --- a/tests/phpunit.xml.dist +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - ./ - - - From 62c0ca04885199f9dd93e9bbd8ffc83897cbd092 Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Mon, 9 Dec 2019 10:24:32 +0100 Subject: [PATCH 31/88] use namespaced mock objects --- .../Util/Console/Command/BaseCommandTest.php | 16 ++++++++-------- .../Util/Console/Command/NodeDumpCommandTest.php | 3 ++- .../Console/Command/NodeTouchCommandTest.php | 3 ++- .../Console/Command/NodeTypeListCommandTest.php | 4 ++-- .../Command/NodeTypeRegisterCommandTest.php | 4 ++-- .../Console/Command/NodesUpdateCommandTest.php | 4 ++-- .../Command/WorkspaceQueryCommandTest.php | 4 ++-- tests/PHPCR/Tests/Util/NodeHelperTest.php | 8 ++++---- tests/PHPCR/Tests/Util/QOM/QueryBuilderTest.php | 6 +++--- 9 files changed, 27 insertions(+), 25 deletions(-) diff --git a/tests/PHPCR/Tests/Util/Console/Command/BaseCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/BaseCommandTest.php index 307b140..54083a4 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/BaseCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/BaseCommandTest.php @@ -12,8 +12,8 @@ use PHPCR\Util\Console\Helper\PhpcrConsoleDumperHelper; use PHPCR\Util\Console\Helper\PhpcrHelper; use PHPCR\WorkspaceInterface; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use PHPUnit_Framework_MockObject_MockObject; use Symfony\Component\Console\Application; use Symfony\Component\Console\Helper\HelperSet; use Symfony\Component\Console\Tester\CommandTester; @@ -25,37 +25,37 @@ abstract class BaseCommandTest extends TestCase { /** - * @var SessionInterface|PHPUnit_Framework_MockObject_MockObject + * @var SessionInterface|MockObject * */ public $session; /** - * @var WorkspaceInterface|PHPUnit_Framework_MockObject_MockObject + * @var WorkspaceInterface|MockObject */ public $workspace; /** - * @var RepositoryInterface|PHPUnit_Framework_MockObject_MockObject + * @var RepositoryInterface|MockObject */ public $repository; /** - * @var PhpcrConsoleDumperHelper|PHPUnit_Framework_MockObject_MockObject + * @var PhpcrConsoleDumperHelper|MockObject */ public $dumperHelper; /** - * @var NodeInterface|PHPUnit_Framework_MockObject_MockObject + * @var NodeInterface|MockObject */ public $node1; /** - * @var RowInterface|PHPUnit_Framework_MockObject_MockObject + * @var RowInterface|MockObject */ public $row1; /** - * @var QueryManagerInterface|PHPUnit_Framework_MockObject_MockObject + * @var QueryManagerInterface|MockObject */ public $queryManager; diff --git a/tests/PHPCR/Tests/Util/Console/Command/NodeDumpCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodeDumpCommandTest.php index f958c55..75be9b6 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodeDumpCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodeDumpCommandTest.php @@ -7,10 +7,11 @@ use PHPCR\Util\Console\Command\NodeDumpCommand; use PHPCR\Util\TreeWalker; use PHPCR\Util\UUIDHelper; +use PHPUnit\Framework\MockObject\MockObject; class NodeDumpCommandTest extends BaseCommandTest { - /** @var TreeWalker|\PHPUnit_Framework_MockObject_MockObject */ + /** @var TreeWalker|MockObject */ protected $treeWalker; public function setUp() diff --git a/tests/PHPCR/Tests/Util/Console/Command/NodeTouchCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodeTouchCommandTest.php index 668aafb..ee0dcd2 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodeTouchCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodeTouchCommandTest.php @@ -8,6 +8,7 @@ use PHPCR\Tests\Stubs\MockNode; use PHPCR\Util\Console\Command\NodeTouchCommand; use PHPCR\Util\Console\Helper\PhpcrHelper; +use PHPUnit\Framework\MockObject\MockObject; /** * Currently very minimal test for touch command. @@ -15,7 +16,7 @@ class NodeTouchCommandTest extends BaseCommandTest { /** - * @var PhpcrHelper|\PHPUnit_Framework_MockObject_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 d906e7c..ea81be9 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodeTypeListCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodeTypeListCommandTest.php @@ -4,12 +4,12 @@ use PHPCR\Tests\Stubs\MockNodeTypeManager; use PHPCR\Util\Console\Command\NodeTypeListCommand; -use PHPUnit_Framework_MockObject_MockObject; +use PHPUnit\Framework\MockObject\MockObject; class NodeTypeListCommandTest extends BaseCommandTest { /** - * @var MockNodeTypeManager|PHPUnit_Framework_MockObject_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 8618bc5..c2f00a5 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodeTypeRegisterCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodeTypeRegisterCommandTest.php @@ -4,12 +4,12 @@ use PHPCR\Tests\Stubs\MockNodeTypeManager; use PHPCR\Util\Console\Command\NodeTypeRegisterCommand; -use PHPUnit_Framework_MockObject_MockObject; +use PHPUnit\Framework\MockObject\MockObject; class NodeTypeRegisterCommandTest extends BaseCommandTest { /** - * @var MockNodeTypeManager|PHPUnit_Framework_MockObject_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 c93f7a8..56195c1 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php @@ -5,12 +5,12 @@ use InvalidArgumentException; use PHPCR\Query\QueryInterface; use PHPCR\Util\Console\Command\NodesUpdateCommand; -use PHPUnit_Framework_MockObject_MockObject; +use PHPUnit\Framework\MockObject\MockObject; class NodesUpdateCommandTest extends BaseCommandTest { /** - * @var QueryInterface|PHPUnit_Framework_MockObject_MockObject + * @var QueryInterface|MockObject */ private $query; diff --git a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceQueryCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceQueryCommandTest.php index edee537..112d161 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceQueryCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceQueryCommandTest.php @@ -4,12 +4,12 @@ use PHPCR\Query\QueryInterface; use PHPCR\Util\Console\Command\WorkspaceQueryCommand; -use PHPUnit_Framework_MockObject_MockObject; +use PHPUnit\Framework\MockObject\MockObject; class WorkspaceQueryCommandTest extends BaseCommandTest { /** - * @var QueryInterface|PHPUnit_Framework_MockObject_MockObject + * @var QueryInterface|MockObject */ protected $query; diff --git a/tests/PHPCR/Tests/Util/NodeHelperTest.php b/tests/PHPCR/Tests/Util/NodeHelperTest.php index 7ca98ff..6453883 100644 --- a/tests/PHPCR/Tests/Util/NodeHelperTest.php +++ b/tests/PHPCR/Tests/Util/NodeHelperTest.php @@ -4,8 +4,8 @@ use PHPCR\Tests\Stubs\MockNode; use PHPCR\Util\NodeHelper; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use PHPUnit_Framework_MockObject_MockObject; require_once __DIR__.'/../Stubs/MockNode.php'; @@ -84,7 +84,7 @@ public function testGenerateAutoNodeNameInvalid($hint) public function testIsSystemItem() { - /** @var MockNode|PHPUnit_Framework_MockObject_MockObject $sys */ + /** @var MockNode|MockObject $sys */ $sys = $this->createMock(MockNode::class); $sys->expects($this->once()) @@ -108,7 +108,7 @@ public function testIsSystemItem() $this->assertTrue(NodeHelper::isSystemItem($sys)); - /** @var MockNode|PHPUnit_Framework_MockObject_MockObject $top */ + /** @var MockNode|MockObject $top */ $top = $this->createMock(MockNode::class); $top->expects($this->once()) ->method('getDepth') @@ -121,7 +121,7 @@ public function testIsSystemItem() $this->assertFalse(NodeHelper::isSystemItem($top)); - /** @var MockNode|PHPUnit_Framework_MockObject_MockObject $deep */ + /** @var MockNode|MockObject $deep */ $deep = $this->createMock(MockNode::class); $deep->expects($this->once()) ->method('getDepth') diff --git a/tests/PHPCR/Tests/Util/QOM/QueryBuilderTest.php b/tests/PHPCR/Tests/Util/QOM/QueryBuilderTest.php index 8c69833..573a1b0 100644 --- a/tests/PHPCR/Tests/Util/QOM/QueryBuilderTest.php +++ b/tests/PHPCR/Tests/Util/QOM/QueryBuilderTest.php @@ -11,14 +11,14 @@ use PHPCR\Query\QOM\SameNodeJoinConditionInterface; use PHPCR\Query\QOM\SourceInterface; use PHPCR\Util\QOM\QueryBuilder; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use PHPUnit_Framework_MockObject_MockObject; use RuntimeException; class QueryBuilderTest extends TestCase { /** - * @var PHPUnit_Framework_MockObject_MockObject|QueryObjectModelFactoryInterface + * @var MockObject|QueryObjectModelFactoryInterface */ protected $qf; @@ -330,7 +330,7 @@ public function testGetQuery() } /** - * @return QueryObjectModelInterface|PHPUnit_Framework_MockObject_MockObject + * @return QueryObjectModelInterface|MockObject */ private function createQueryMock() { From 6591f92a3ca0f0e469831977d739d9bd5864ea48 Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Tue, 6 Oct 2020 09:10:14 +0000 Subject: [PATCH 32/88] Apply fixes from StyleCI --- src/PHPCR/Util/CND/Parser/CndParser.php | 2 +- .../Command/BaseNodeManipulationCommand.php | 20 ++++++++++---- .../Util/Console/Command/NodeDumpCommand.php | 3 ++- .../Util/Console/Command/NodeMoveCommand.php | 6 +++-- .../Console/Command/NodeRemoveCommand.php | 3 ++- .../Util/Console/Command/NodeTouchCommand.php | 19 ++++++++----- .../Console/Command/NodeTypeListCommand.php | 3 ++- .../Command/NodeTypeRegisterCommand.php | 3 ++- .../Console/Command/NodesUpdateCommand.php | 14 ++++++---- .../Command/WorkspaceCreateCommand.php | 11 ++++---- .../Command/WorkspaceDeleteCommand.php | 3 ++- .../Command/WorkspaceExportCommand.php | 3 ++- .../Command/WorkspaceImportCommand.php | 3 ++- .../Console/Command/WorkspaceListCommand.php | 3 ++- .../Console/Command/WorkspacePurgeCommand.php | 3 ++- src/PHPCR/Util/Console/Helper/PhpcrHelper.php | 9 ++++--- src/PHPCR/Util/PathHelper.php | 3 ++- .../Util/QOM/BaseQomToSqlQueryConverter.php | 6 +++-- .../Util/QOM/QomToSql1QueryConverter.php | 12 ++++++--- .../Util/QOM/QomToSql2QueryConverter.php | 27 ++++++++++++------- src/PHPCR/Util/UUIDHelper.php | 10 ++++--- .../Util/CND/Scanner/GenericScannerTest.php | 16 +++++++---- tests/PHPCR/Tests/Util/ValueConverterTest.php | 6 +++-- 23 files changed, 126 insertions(+), 62 deletions(-) diff --git a/src/PHPCR/Util/CND/Parser/CndParser.php b/src/PHPCR/Util/CND/Parser/CndParser.php index 4ae8a9a..0a18429 100644 --- a/src/PHPCR/Util/CND/Parser/CndParser.php +++ b/src/PHPCR/Util/CND/Parser/CndParser.php @@ -369,7 +369,7 @@ protected function parsePropDef(NodeTypeTemplateInterface $nodeType) protected function parsePropertyType(PropertyDefinitionTemplateInterface $property) { $types = ['STRING', 'BINARY', 'LONG', 'DOUBLE', 'BOOLEAN', 'DATE', 'NAME', 'PATH', - 'REFERENCE', 'WEAKREFERENCE', 'DECIMAL', 'URI', 'UNDEFINED', '*', '?', ]; + 'REFERENCE', 'WEAKREFERENCE', 'DECIMAL', 'URI', 'UNDEFINED', '*', '?', ]; if (!$this->checkTokenIn(Token::TK_IDENTIFIER, $types, true)) { throw new ParserException($this->tokenQueue, sprintf('Invalid property type: %s', $this->tokenQueue->get()->getData())); diff --git a/src/PHPCR/Util/Console/Command/BaseNodeManipulationCommand.php b/src/PHPCR/Util/Console/Command/BaseNodeManipulationCommand.php index a797b2f..9633e45 100644 --- a/src/PHPCR/Util/Console/Command/BaseNodeManipulationCommand.php +++ b/src/PHPCR/Util/Console/Command/BaseNodeManipulationCommand.php @@ -17,27 +17,37 @@ abstract class BaseNodeManipulationCommand extends BaseCommand */ protected function configureNodeManipulationInput() { - $this->addOption('set-prop', 'p', + $this->addOption( + 'set-prop', + 'p', InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Set node property on nodes use foo=bar' ); - $this->addOption('remove-prop', 'r', + $this->addOption( + 'remove-prop', + 'r', InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Remove property from nodes' ); - $this->addOption('add-mixin', null, + $this->addOption( + 'add-mixin', + null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Add a mixin to the nodes' ); - $this->addOption('remove-mixin', null, + $this->addOption( + 'remove-mixin', + null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Remove mixin from the nodes' ); - $this->addOption('apply-closure', null, + $this->addOption( + 'apply-closure', + null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Apply a closure to each node, closures are passed PHPCR\Session and PHPCR\NodeInterface' ); diff --git a/src/PHPCR/Util/Console/Command/NodeDumpCommand.php b/src/PHPCR/Util/Console/Command/NodeDumpCommand.php index 576973e..10cdf18 100644 --- a/src/PHPCR/Util/Console/Command/NodeDumpCommand.php +++ b/src/PHPCR/Util/Console/Command/NodeDumpCommand.php @@ -40,7 +40,8 @@ protected function configure() ->addOption('ref-format', 'uuid', InputOption::VALUE_REQUIRED, 'Set the way references should be displayed when dumping reference properties - either "uuid" (default) or "path"') ->addArgument('identifier', InputArgument::OPTIONAL, 'Root path to dump', '/') ->setDescription('Dump subtrees of the content repository') - ->setHelp(<<<'HERE' + ->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. diff --git a/src/PHPCR/Util/Console/Command/NodeMoveCommand.php b/src/PHPCR/Util/Console/Command/NodeMoveCommand.php index ef3699f..d0f3fd4 100644 --- a/src/PHPCR/Util/Console/Command/NodeMoveCommand.php +++ b/src/PHPCR/Util/Console/Command/NodeMoveCommand.php @@ -29,7 +29,8 @@ protected function configure() ->addArgument('source', InputArgument::REQUIRED, 'Path of node to move') ->addArgument('destination', InputArgument::REQUIRED, 'Destination for node') ->setDescription('Moves a node from one path to another') - ->setHelp(<<<'EOF' + ->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. @@ -55,7 +56,8 @@ protected function execute(InputInterface $input, OutputInterface $output) $output->writeln(sprintf( 'Moving %s to %s', - $sourcePath, $destPath + $sourcePath, + $destPath )); $session->move($sourcePath, $destPath); diff --git a/src/PHPCR/Util/Console/Command/NodeRemoveCommand.php b/src/PHPCR/Util/Console/Command/NodeRemoveCommand.php index bf7ec0f..f9a3127 100644 --- a/src/PHPCR/Util/Console/Command/NodeRemoveCommand.php +++ b/src/PHPCR/Util/Console/Command/NodeRemoveCommand.php @@ -36,7 +36,8 @@ protected function configure() ->addArgument('path', InputArgument::REQUIRED, 'Path of the node to purge') ->addOption('force', null, InputOption::VALUE_NONE, 'Use to bypass the confirmation dialog') ->addOption('only-children', null, InputOption::VALUE_NONE, 'Use to only purge children of specified path') - ->setHelp(<<<'EOF' + ->setHelp( + <<<'EOF' The phpcr:node:remove command will remove the given node or the children of the given node according to the options given. diff --git a/src/PHPCR/Util/Console/Command/NodeTouchCommand.php b/src/PHPCR/Util/Console/Command/NodeTouchCommand.php index 0ede6d1..7ca3f0e 100644 --- a/src/PHPCR/Util/Console/Command/NodeTouchCommand.php +++ b/src/PHPCR/Util/Console/Command/NodeTouchCommand.php @@ -39,17 +39,21 @@ protected function configure() 'Path at which to create the new node' ) ->addOption( - 'type', 't', + 'type', + 't', InputOption::VALUE_OPTIONAL, 'Node type, default nt:unstructured', 'nt:unstructured' ) - ->addOption('dump', 'd', + ->addOption( + 'dump', + 'd', InputOption::VALUE_NONE, 'Dump a string reperesentation of the created / modified node.' ) ->setDescription('Create or modify a node') - ->setHelp(<<<'HERE' + ->setHelp( + <<<'HERE' This command allows you to create or modify a node at the specified path. For example:: @@ -65,7 +69,7 @@ protected function configure() $ ./bin/phpcr phpcr:touch /foobar --type=my:nodetype --set-prop=bar=myvalue --remove-prop=foo --dump HERE -); + ); } /** @@ -104,7 +108,8 @@ protected function execute(InputInterface $input, OutputInterface $output) if ($nodeType != $type) { $output->writeln(sprintf( 'You have specified node type "%s" but the existing node is of type "%s"', - $type, $nodeType + $type, + $nodeType )); return 1; @@ -125,7 +130,9 @@ protected function execute(InputInterface $input, OutputInterface $output) } $output->writeln(sprintf( - 'Creating node: %s [%s]', $path, $type + 'Creating node: %s [%s]', + $path, + $type )); $node = $parentNode->addNode($nodeName, $type); diff --git a/src/PHPCR/Util/Console/Command/NodeTypeListCommand.php b/src/PHPCR/Util/Console/Command/NodeTypeListCommand.php index 060ea9e..2f95fa5 100644 --- a/src/PHPCR/Util/Console/Command/NodeTypeListCommand.php +++ b/src/PHPCR/Util/Console/Command/NodeTypeListCommand.php @@ -23,7 +23,8 @@ protected function configure() $this ->setName('phpcr:node-type:list') ->setDescription('List all available node types in the repository') - ->setHelp(<<<'EOT' + ->setHelp( + <<<'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 4072734..9cf78ed 100644 --- a/src/PHPCR/Util/Console/Command/NodeTypeRegisterCommand.php +++ b/src/PHPCR/Util/Console/Command/NodeTypeRegisterCommand.php @@ -36,7 +36,8 @@ protected function configure() ->setDescription('Register node types in the PHPCR repository') ->addArgument('cnd-file', InputArgument::IS_ARRAY, 'Register namespaces and node types from a "Compact Node Type Definition" .cnd file(s)') ->addOption('allow-update', null, InputOption::VALUE_NONE, 'Overwrite existig node type') - ->setHelp(<<<'EOT' + ->setHelp( + <<<'EOT' Register node types in the PHPCR repository. This command allows to register node types in the repository that are defined diff --git a/src/PHPCR/Util/Console/Command/NodesUpdateCommand.php b/src/PHPCR/Util/Console/Command/NodesUpdateCommand.php index 4f24644..6b13eb2 100644 --- a/src/PHPCR/Util/Console/Command/NodesUpdateCommand.php +++ b/src/PHPCR/Util/Console/Command/NodesUpdateCommand.php @@ -33,24 +33,28 @@ protected function configure() $this->setName('phpcr:nodes:update') ->addOption( - 'query', null, + 'query', + null, InputOption::VALUE_REQUIRED, 'Query used to select the nodes' ) ->addOption( - 'query-language', 'l', + 'query-language', + 'l', InputOption::VALUE_OPTIONAL, 'The query language (e.g. sql, jcr_sql2)', 'jcr-sql2' ) ->addOption( - 'persist-counter', 'c', + 'persist-counter', + 'c', InputOption::VALUE_OPTIONAL, 'Save the session every x requests', '100' ) ->setDescription('Command to manipulate the nodes in the workspace.') - ->setHelp(<<setHelp( + <<phpcr:nodes:update can manipulate the properties of nodes found using the given query. @@ -77,7 +81,7 @@ protected function configure() 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 90f0935..c0ac8a6 100644 --- a/src/PHPCR/Util/Console/Command/WorkspaceCreateCommand.php +++ b/src/PHPCR/Util/Console/Command/WorkspaceCreateCommand.php @@ -27,13 +27,14 @@ protected function configure() ->setName('phpcr:workspace:create') ->addArgument('name', InputArgument::REQUIRED, 'Name of the workspace to create') ->addOption( - 'ignore-existing', - null, - InputOption::VALUE_NONE, - 'If set, an existing workspace will return a success code' + 'ignore-existing', + null, + InputOption::VALUE_NONE, + 'If set, an existing workspace will return a success code' ) ->setDescription('Create a workspace in the configured repository') - ->setHelp(<<<'EOT' + ->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. diff --git a/src/PHPCR/Util/Console/Command/WorkspaceDeleteCommand.php b/src/PHPCR/Util/Console/Command/WorkspaceDeleteCommand.php index ea8aeae..9200fe6 100644 --- a/src/PHPCR/Util/Console/Command/WorkspaceDeleteCommand.php +++ b/src/PHPCR/Util/Console/Command/WorkspaceDeleteCommand.php @@ -27,7 +27,8 @@ protected function configure() ->addArgument('name', InputArgument::REQUIRED, 'Name of the workspace to delete') ->addOption('force', null, InputOption::VALUE_NONE, 'Use to bypass the confirmation dialog') ->setDescription('Delete a workspace from the configured repository') - ->setHelp(<<<'EOT' + ->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 diff --git a/src/PHPCR/Util/Console/Command/WorkspaceExportCommand.php b/src/PHPCR/Util/Console/Command/WorkspaceExportCommand.php index a4bc178..5708e79 100644 --- a/src/PHPCR/Util/Console/Command/WorkspaceExportCommand.php +++ b/src/PHPCR/Util/Console/Command/WorkspaceExportCommand.php @@ -31,7 +31,8 @@ protected function configure() ->addOption('skip_binary', null, InputOption::VALUE_OPTIONAL, 'Set to "yes" to skip binaries', 'no') ->addOption('recurse', null, InputOption::VALUE_OPTIONAL, 'Set to "no" to prevent recursion', 'yes') ->setDescription('Export nodes from the repository, either to the JCR system view format or the document view format') - ->setHelp(<<<'EOF' + ->setHelp( + <<<'EOF' The export command uses the PHPCR SessionInterface::exportSystemView method to export parts of the repository into an XML document. diff --git a/src/PHPCR/Util/Console/Command/WorkspaceImportCommand.php b/src/PHPCR/Util/Console/Command/WorkspaceImportCommand.php index 185d747..4b6578d 100644 --- a/src/PHPCR/Util/Console/Command/WorkspaceImportCommand.php +++ b/src/PHPCR/Util/Console/Command/WorkspaceImportCommand.php @@ -37,7 +37,8 @@ protected function configure() ->addOption('parentpath', 'p', InputOption::VALUE_OPTIONAL, 'Repository path to the parent where to import the file contents', '/') ->addOption('uuid-behavior', null, InputOption::VALUE_REQUIRED, 'How to handle UUID collisions during the import', 'new') ->setDescription('Import xml data into the repository, either in JCR system view format or arbitrary xml') - ->setHelp(<<<'EOF' + ->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 diff --git a/src/PHPCR/Util/Console/Command/WorkspaceListCommand.php b/src/PHPCR/Util/Console/Command/WorkspaceListCommand.php index 967cbe9..3165f8b 100644 --- a/src/PHPCR/Util/Console/Command/WorkspaceListCommand.php +++ b/src/PHPCR/Util/Console/Command/WorkspaceListCommand.php @@ -22,7 +22,8 @@ protected function configure() $this ->setName('phpcr:workspace:list') ->setDescription('List all available workspaces in the configured repository') - ->setHelp(<<<'EOT' + ->setHelp( + <<<'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 487d013..c8c8f81 100644 --- a/src/PHPCR/Util/Console/Command/WorkspacePurgeCommand.php +++ b/src/PHPCR/Util/Console/Command/WorkspacePurgeCommand.php @@ -28,7 +28,8 @@ protected function configure() ->setName('phpcr:workspace:purge') ->setDescription('Remove all nodes from a workspace') ->addOption('force', null, InputOption::VALUE_NONE, 'Use to bypass the confirmation dialog') - ->setHelp(<<<'EOF' + ->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 diff --git a/src/PHPCR/Util/Console/Helper/PhpcrHelper.php b/src/PHPCR/Util/Console/Helper/PhpcrHelper.php index a168f86..8c0d7ce 100644 --- a/src/PHPCR/Util/Console/Helper/PhpcrHelper.php +++ b/src/PHPCR/Util/Console/Helper/PhpcrHelper.php @@ -76,7 +76,8 @@ public function processNode(OutputInterface $output, NodeInterface $node, array $parts = explode('=', $set); $output->writeln(sprintf( ' > Setting property %s to %s', - $parts[0], $parts[1] + $parts[0], + $parts[1] )); $node->setProperty($parts[0], $parts[1]); } @@ -134,7 +135,8 @@ public function processNode(OutputInterface $output, NodeInterface $node, array if (!is_string($value)) { $value = print_r($value, true); } - $output->writeln(sprintf(' - %s = %s', + $output->writeln(sprintf( + ' - %s = %s', $property->getName(), $value )); @@ -181,7 +183,8 @@ protected function validateQueryLanguage($language) throw new Exception(sprintf( 'Query language "%s" not supported, available query languages: %s', - $language, implode(',', $langs) + $language, + implode(',', $langs) )); } } diff --git a/src/PHPCR/Util/PathHelper.php b/src/PHPCR/Util/PathHelper.php index ddd7af6..0394163 100644 --- a/src/PHPCR/Util/PathHelper.php +++ b/src/PHPCR/Util/PathHelper.php @@ -272,7 +272,8 @@ public static function getNodeName($path) if (false === $strrpos) { self::error(sprintf( - 'Path "%s" must be an absolute path', $path + 'Path "%s" must be an absolute path', + $path ), true); } diff --git a/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php b/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php index fb252b1..c2a1ac2 100644 --- a/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php +++ b/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php @@ -143,7 +143,8 @@ protected function convertPropertyExistence(QOM\PropertyExistenceInterface $cons { return $this->generator->evalPropertyExistence( $constraint->getSelectorName(), - $constraint->getPropertyName()); + $constraint->getPropertyName() + ); } /** @@ -229,7 +230,8 @@ protected function convertPropertyValue(QOM\PropertyValueInterface $value) { return $this->generator->evalPropertyValue( $value->getPropertyName(), - $value->getSelectorName()); + $value->getSelectorName() + ); } /** diff --git a/src/PHPCR/Util/QOM/QomToSql1QueryConverter.php b/src/PHPCR/Util/QOM/QomToSql1QueryConverter.php index f6c327e..ae591b5 100644 --- a/src/PHPCR/Util/QOM/QomToSql1QueryConverter.php +++ b/src/PHPCR/Util/QOM/QomToSql1QueryConverter.php @@ -52,13 +52,15 @@ protected function convertConstraint(QOM\ConstraintInterface $constraint) if ($constraint instanceof QOM\AndInterface) { return $this->generator->evalAnd( $this->convertConstraint($constraint->getConstraint1()), - $this->convertConstraint($constraint->getConstraint2())); + $this->convertConstraint($constraint->getConstraint2()) + ); } if ($constraint instanceof QOM\OrInterface) { return $this->generator->evalOr( $this->convertConstraint($constraint->getConstraint1()), - $this->convertConstraint($constraint->getConstraint2())); + $this->convertConstraint($constraint->getConstraint2()) + ); } if ($constraint instanceof QOM\NotInterface) { @@ -81,12 +83,14 @@ protected function convertConstraint(QOM\ConstraintInterface $constraint) if ($constraint instanceof QOM\ChildNodeInterface) { return $this->generator->evalChildNode( - $this->convertPath($constraint->getParentPath())); + $this->convertPath($constraint->getParentPath()) + ); } if ($constraint instanceof QOM\DescendantNodeInterface) { return $this->generator->evalDescendantNode( - $this->convertPath($constraint->getAncestorPath())); + $this->convertPath($constraint->getAncestorPath()) + ); } // This should not happen, but who knows... diff --git a/src/PHPCR/Util/QOM/QomToSql2QueryConverter.php b/src/PHPCR/Util/QOM/QomToSql2QueryConverter.php index aec6a6d..7c92ed6 100644 --- a/src/PHPCR/Util/QOM/QomToSql2QueryConverter.php +++ b/src/PHPCR/Util/QOM/QomToSql2QueryConverter.php @@ -106,7 +106,8 @@ protected function convertEquiJoinCondition(QOM\EquiJoinConditionInterface $cond $condition->getSelector1Name(), $condition->getProperty1Name(), $condition->getSelector2Name(), - $condition->getProperty2Name()); + $condition->getProperty2Name() + ); } /** @@ -125,7 +126,8 @@ protected function convertSameNodeJoinCondition(QOM\SameNodeJoinConditionInterfa return $this->generator->evalSameNodeJoinCondition( $condition->getSelector1Name(), $condition->getSelector2Name(), - null !== $condition->getSelector2Path() ? $this->convertPath($condition->getSelector2Path()) : null); + null !== $condition->getSelector2Path() ? $this->convertPath($condition->getSelector2Path()) : null + ); } /** @@ -143,7 +145,8 @@ protected function convertChildNodeJoinCondition(QOM\ChildNodeJoinConditionInter { return $this->generator->evalChildNodeJoinCondition( $condition->getChildSelectorName(), - $condition->getParentSelectorName()); + $condition->getParentSelectorName() + ); } /** @@ -161,7 +164,8 @@ protected function convertDescendantNodeJoinCondition(QOM\DescendantNodeJoinCond { return $this->generator->evalDescendantNodeJoinCondition( $condition->getDescendantSelectorName(), - $condition->getAncestorSelectorName()); + $condition->getAncestorSelectorName() + ); } /** @@ -196,13 +200,15 @@ protected function convertConstraint(QOM\ConstraintInterface $constraint) if ($constraint instanceof QOM\AndInterface) { return $this->generator->evalAnd( $this->convertConstraint($constraint->getConstraint1()), - $this->convertConstraint($constraint->getConstraint2())); + $this->convertConstraint($constraint->getConstraint2()) + ); } if ($constraint instanceof QOM\OrInterface) { return $this->generator->evalOr( $this->convertConstraint($constraint->getConstraint1()), - $this->convertConstraint($constraint->getConstraint2())); + $this->convertConstraint($constraint->getConstraint2()) + ); } if ($constraint instanceof QOM\NotInterface) { @@ -222,19 +228,22 @@ protected function convertConstraint(QOM\ConstraintInterface $constraint) if ($constraint instanceof QOM\SameNodeInterface) { return $this->generator->evalSameNode( $this->convertPath($constraint->getPath()), - $constraint->getSelectorName()); + $constraint->getSelectorName() + ); } if ($constraint instanceof QOM\ChildNodeInterface) { return $this->generator->evalChildNode( $this->convertPath($constraint->getParentPath()), - $constraint->getSelectorName()); + $constraint->getSelectorName() + ); } if ($constraint instanceof QOM\DescendantNodeInterface) { return $this->generator->evalDescendantNode( $this->convertPath($constraint->getAncestorPath()), - $constraint->getSelectorName()); + $constraint->getSelectorName() + ); } // This should not happen, but who knows... diff --git a/src/PHPCR/Util/UUIDHelper.php b/src/PHPCR/Util/UUIDHelper.php index 130c365..c684c1e 100644 --- a/src/PHPCR/Util/UUIDHelper.php +++ b/src/PHPCR/Util/UUIDHelper.php @@ -43,9 +43,11 @@ public static function generateUUID() return $uuid4->toString(); } - return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x', + return sprintf( + '%04x%04x-%04x-%04x-%04x-%04x%04x%04x', // 32 bits for "time_low" - mt_rand(0, 0xffff), mt_rand(0, 0xffff), + mt_rand(0, 0xffff), + mt_rand(0, 0xffff), // 16 bits for "time_mid" mt_rand(0, 0xffff), @@ -60,7 +62,9 @@ public static function generateUUID() mt_rand(0, 0x3fff) | 0x8000, // 48 bits for "node" - mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff) + mt_rand(0, 0xffff), + mt_rand(0, 0xffff), + mt_rand(0, 0xffff) ); } } diff --git a/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php b/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php index 14bda9b..9b0e2d8 100644 --- a/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php +++ b/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php @@ -166,10 +166,16 @@ protected function assertTokens($tokens, TokenQueue $queue) protected function assertToken($type, $data, Token $token) { - $this->assertEquals($type, $token->getType(), - sprintf('Expected token [%s, %s], found [%s, %s]', Token::getTypeName($type), $data, Token::getTypeName($token->getType()), $token->getData())); - - $this->assertEquals($data, trim($token->getData()), - sprintf('Expected token [%s, %s], found [%s, %s]', Token::getTypeName($type), $data, Token::getTypeName($token->getType()), $token->getData())); + $this->assertEquals( + $type, + $token->getType(), + sprintf('Expected token [%s, %s], found [%s, %s]', Token::getTypeName($type), $data, Token::getTypeName($token->getType()), $token->getData()) + ); + + $this->assertEquals( + $data, + trim($token->getData()), + sprintf('Expected token [%s, %s], found [%s, %s]', Token::getTypeName($type), $data, Token::getTypeName($token->getType()), $token->getData()) + ); } } diff --git a/tests/PHPCR/Tests/Util/ValueConverterTest.php b/tests/PHPCR/Tests/Util/ValueConverterTest.php index 8a18d30..a5aaa41 100644 --- a/tests/PHPCR/Tests/Util/ValueConverterTest.php +++ b/tests/PHPCR/Tests/Util/ValueConverterTest.php @@ -331,9 +331,11 @@ public function testConvertTypeToBinary() public function testConvertTypeArray() { - $result = $this->valueConverter->convertType(['2012-01-10', '2012-02-12'], + $result = $this->valueConverter->convertType( + ['2012-01-10', '2012-02-12'], PropertyType::DATE, - PropertyType::STRING); + PropertyType::STRING + ); $this->assertInternalType('array', $result); $this->assertCount(2, $result); From b54210dd13f7b7c1c690f70e27881ec6eeee7192 Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Tue, 6 Oct 2020 11:08:44 +0200 Subject: [PATCH 33/88] php 8 --- .styleci.yml | 2 ++ .travis.yml | 5 ++- CHANGELOG.md | 6 ++++ composer.json | 6 ++-- .../Util/CND/Reader/BufferReaderTest.php | 30 +++++++++++----- .../Tests/Util/CND/Reader/FileReaderTest.php | 2 +- .../Util/CND/Scanner/GenericScannerTest.php | 2 +- .../Tests/Util/CND/Scanner/TokenQueueTest.php | 11 +++--- .../Tests/Util/CND/Scanner/TokenTest.php | 6 ++-- .../Util/Console/Command/BaseCommandTest.php | 18 +++++----- .../Console/Command/NodeDumpCommandTest.php | 12 +++---- .../Console/Command/NodeRemoveCommandTest.php | 2 +- .../Console/Command/NodeTouchCommandTest.php | 34 +++++++++---------- .../Command/NodeTypeListCommandTest.php | 8 ++--- .../Command/NodeTypeRegisterCommandTest.php | 6 ++-- .../Command/NodesUpdateCommandTest.php | 24 ++++++------- .../Command/WorkspaceCreateCommandTest.php | 22 ++++++------ .../Command/WorkspaceDeleteCommandTest.php | 18 +++++----- .../Command/WorkspaceExportCommandTest.php | 15 +++++--- .../Command/WorkspaceImportCommandTest.php | 14 ++++---- .../Command/WorkspaceListCommandTest.php | 8 ++--- .../Command/WorkspacePurgeCommandTest.php | 8 ++--- .../Command/WorkspaceQueryCommandTest.php | 20 +++++------ .../Helper/PhpcrConsoleDumperHelperTest.php | 2 +- tests/PHPCR/Tests/Util/NodeHelperTest.php | 19 ++++++----- tests/PHPCR/Tests/Util/PathHelperTest.php | 10 ++---- .../PHPCR/Tests/Util/QOM/QueryBuilderTest.php | 8 ++--- .../Tests/Util/QOM/Sql1GeneratorTest.php | 2 +- .../Tests/Util/QOM/Sql2GeneratorTest.php | 2 +- .../Util/QOM/Sql2ToQomQueryConverterTest.php | 6 ++-- tests/PHPCR/Tests/Util/ValueConverterTest.php | 22 ++++++------ 31 files changed, 183 insertions(+), 167 deletions(-) diff --git a/.styleci.yml b/.styleci.yml index 989801f..5e45ebb 100644 --- a/.styleci.yml +++ b/.styleci.yml @@ -2,3 +2,5 @@ preset: recommended enabled: - no_useless_else +disabled: + - align_double_arrow diff --git a/.travis.yml b/.travis.yml index 2e33f67..0705a33 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,12 +1,11 @@ language: php php: - - 5.6 - - 7.0 - 7.1 - 7.2 - 7.3 - 7.4 + - nightly env: - PACKAGE_VERSION=high @@ -15,7 +14,7 @@ sudo: false matrix: include: - - php: 5.6 + - php: 7.1 env: PACKAGE_VERSION=low - php: 7.4 env: diff --git a/CHANGELOG.md b/CHANGELOG.md index 9209011..02c5aa5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,12 @@ Changelog ========= +1.5.0 +----- + +* Support PHP 8 +* Drop support for PHP 5.6 and 7.0 + 1.4.1 ----- diff --git a/composer.json b/composer.json index 260727d..fe78ebf 100644 --- a/composer.json +++ b/composer.json @@ -27,13 +27,13 @@ } ], "require": { - "php": "^5.6 || ^7.0", + "php": "^7.1 || ^8.0", "phpcr/phpcr": "~2.1.0", - "symfony/console": "^2.3|^3.0|^4.0|^5.0" + "symfony/console": "^2.3 || ^3.0 || ^4.0 || ^5.0" }, "require-dev": { "ramsey/uuid": "^3.5", - "phpunit/phpunit": "^5.7 || ^6.0 || ^7.0" + "phpunit/phpunit": "^7.5 || ^8.0 || ^9.0" }, "suggest": { "ramsey/uuid": "A library for generating RFC 4122 version 1, 3, 4, and 5 universally unique identifiers (UUID)." diff --git a/tests/PHPCR/Tests/Util/CND/Reader/BufferReaderTest.php b/tests/PHPCR/Tests/Util/CND/Reader/BufferReaderTest.php index 52a9d44..86fd747 100644 --- a/tests/PHPCR/Tests/Util/CND/Reader/BufferReaderTest.php +++ b/tests/PHPCR/Tests/Util/CND/Reader/BufferReaderTest.php @@ -7,15 +7,21 @@ class BufferReaderTest extends TestCase { - public function test__construct() + public function test__construct(): void { $buffer = "Some random\nor\r\nstring"; $reader = new BufferReader($buffer); - $this->assertInstanceOf(BufferReader::class, $reader); - $this->assertAttributeEquals(str_replace("\r\n", "\n", $buffer).$reader->getEofMarker(), 'buffer', $reader); - $this->assertAttributeEquals(0, 'startPos', $reader); - $this->assertAttributeEquals(0, 'forwardPos', $reader); + $reflection = new \ReflectionClass($reader); + $bufferProperty = $reflection->getProperty('buffer'); + $bufferProperty->setAccessible(true); + $this->assertSame(str_replace("\r\n", "\n", $buffer).$reader->getEofMarker(), $bufferProperty->getValue($reader)); + $startPos = $reflection->getProperty('startPos'); + $startPos->setAccessible(true); + $this->assertSame(0, $startPos->getValue($reader)); + $forwardPos = $reflection->getProperty('forwardPos'); + $forwardPos->setAccessible(true); + $this->assertSame(0, $forwardPos->getValue($reader)); $this->assertEquals(1, $reader->getCurrentLine()); $this->assertEquals(1, $reader->getCurrentColumn()); @@ -90,10 +96,16 @@ public function test__constructEmptyString() { $reader = new BufferReader(''); - $this->assertInstanceOf(BufferReader::class, $reader); - $this->assertAttributeEquals($reader->getEofMarker(), 'buffer', $reader); - $this->assertAttributeEquals(0, 'startPos', $reader); - $this->assertAttributeEquals(0, 'forwardPos', $reader); + $reflection = new \ReflectionClass($reader); + $buffer = $reflection->getProperty('buffer'); + $buffer->setAccessible(true); + $this->assertSame($reader->getEofMarker(), $buffer->getValue($reader)); + $startPos = $reflection->getProperty('startPos'); + $startPos->setAccessible(true); + $this->assertSame(0, $startPos->getValue($reader)); + $forwardPos = $reflection->getProperty('forwardPos'); + $forwardPos->setAccessible(true); + $this->assertSame(0, $forwardPos->getValue($reader)); $this->assertEquals(1, $reader->getCurrentLine()); $this->assertEquals(1, $reader->getCurrentColumn()); diff --git a/tests/PHPCR/Tests/Util/CND/Reader/FileReaderTest.php b/tests/PHPCR/Tests/Util/CND/Reader/FileReaderTest.php index cc9ca98..23329e4 100644 --- a/tests/PHPCR/Tests/Util/CND/Reader/FileReaderTest.php +++ b/tests/PHPCR/Tests/Util/CND/Reader/FileReaderTest.php @@ -23,7 +23,7 @@ class FileReaderTest extends TestCase */ private $lines; - public function setUp() + public function setUp(): void { $this->filepath = __DIR__.'/../Fixtures/files/TestFile.txt'; $this->reader = new FileReader($this->filepath); diff --git a/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php b/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php index 9b0e2d8..dab5d01 100644 --- a/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php +++ b/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php @@ -108,7 +108,7 @@ class GenericScannerTest extends TestCase protected $expectedTokensNoEmptyToken; - public function setUp() + public function setUp(): void { $this->expectedTokensNoEmptyToken = []; foreach ($this->expectedTokens as $token) { diff --git a/tests/PHPCR/Tests/Util/CND/Scanner/TokenQueueTest.php b/tests/PHPCR/Tests/Util/CND/Scanner/TokenQueueTest.php index d2831e1..7af6afb 100644 --- a/tests/PHPCR/Tests/Util/CND/Scanner/TokenQueueTest.php +++ b/tests/PHPCR/Tests/Util/CND/Scanner/TokenQueueTest.php @@ -33,7 +33,7 @@ class TokenQueueTest extends TestCase */ private $queue; - public function setUp() + public function setUp(): void { $this->token0 = new Token(0, 'token 0'); $this->token1 = new Token(1, 'token 1'); @@ -50,13 +50,16 @@ public function setUp() public function testAdd() { $queue = new TokenQueue(); - $this->assertAttributeEquals([], 'tokens', $queue); + $reflection = new \ReflectionClass($queue); + $tokens = $reflection->getProperty('tokens'); + $tokens->setAccessible(true); + $this->assertSame([], $tokens->getValue($queue)); $queue->add($this->token0); - $this->assertAttributeEquals([$this->token0], 'tokens', $queue); + $this->assertSame([$this->token0], $tokens->getValue($queue)); $queue->add($this->token1); - $this->assertAttributeEquals([$this->token0, $this->token1], 'tokens', $queue); + $this->assertSame([$this->token0, $this->token1], $tokens->getValue($queue)); } public function testResetAndPeek() diff --git a/tests/PHPCR/Tests/Util/CND/Scanner/TokenTest.php b/tests/PHPCR/Tests/Util/CND/Scanner/TokenTest.php index 718b5ce..8f81190 100644 --- a/tests/PHPCR/Tests/Util/CND/Scanner/TokenTest.php +++ b/tests/PHPCR/Tests/Util/CND/Scanner/TokenTest.php @@ -12,15 +12,15 @@ class TokenTest extends TestCase */ private $token; - public function setUp() + public function setUp(): void { $this->token = new Token(123, 'foobar'); } public function test__construct() { - $this->assertAttributeEquals(123, 'type', $this->token); - $this->assertAttributeEquals('foobar', 'data', $this->token); + $this->assertSame(123, $this->token->type); + $this->assertSame('foobar', $this->token->data); } public function testGetData() diff --git a/tests/PHPCR/Tests/Util/Console/Command/BaseCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/BaseCommandTest.php index 54083a4..f935b7d 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/BaseCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/BaseCommandTest.php @@ -69,7 +69,7 @@ abstract class BaseCommandTest extends TestCase */ public $application; - public function setUp() + public function setUp(): void { $this->session = $this->createMock(SessionInterface::class); $this->workspace = $this->createMock(WorkspaceInterface::class); @@ -88,21 +88,21 @@ public function setUp() 'phpcr_console_dumper' => $this->dumperHelper, ]); - $this->session->expects($this->any()) + $this->session ->method('getWorkspace') - ->will($this->returnValue($this->workspace)); + ->willReturn($this->workspace); - $this->workspace->expects($this->any()) + $this->workspace ->method('getName') - ->will($this->returnValue('test')); + ->willReturn('test'); - $this->workspace->expects($this->any()) + $this->workspace ->method('getQueryManager') - ->will($this->returnValue($this->queryManager)); + ->willReturn($this->queryManager); - $this->queryManager->expects($this->any()) + $this->queryManager ->method('getSupportedQueryLanguages') - ->will($this->returnValue(['JCR-SQL2'])); + ->willReturn(['JCR-SQL2']); $this->application = new Application(); $this->application->setHelperSet($this->helperSet); diff --git a/tests/PHPCR/Tests/Util/Console/Command/NodeDumpCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodeDumpCommandTest.php index 75be9b6..993d486 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodeDumpCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodeDumpCommandTest.php @@ -14,7 +14,7 @@ class NodeDumpCommandTest extends BaseCommandTest /** @var TreeWalker|MockObject */ protected $treeWalker; - public function setUp() + public function setUp(): void { parent::setUp(); $this->treeWalker = $this->getMockBuilder(TreeWalker::class) @@ -30,13 +30,13 @@ public function testCommand() $this->dumperHelper ->expects($this->once()) ->method('getTreeWalker') - ->will($this->returnValue($this->treeWalker)); + ->willReturn($this->treeWalker); $this->session ->expects($this->once()) ->method('getNode') ->with('/') - ->will($this->returnValue($this->node1)); + ->willReturn($this->node1); $this->treeWalker ->expects($this->once()) @@ -53,13 +53,13 @@ public function testCommandIdentifier() $this->dumperHelper ->expects($this->once()) ->method('getTreeWalker') - ->will($this->returnValue($this->treeWalker)); + ->willReturn($this->treeWalker); $this->session ->expects($this->once()) ->method('getNodeByIdentifier') ->with($uuid) - ->will($this->returnValue($this->node1)); + ->willReturn($this->node1); $this->treeWalker ->expects($this->once()) @@ -86,6 +86,6 @@ public function testNotFound() ->will($this->throwException(new ItemNotFoundException())); $ct = $this->executeCommand('phpcr:node:dump', [], 1); - $this->assertContains('does not exist', $ct->getDisplay()); + $this->assertStringContainsString('does not exist', $ct->getDisplay()); } } diff --git a/tests/PHPCR/Tests/Util/Console/Command/NodeRemoveCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodeRemoveCommandTest.php index f78bd10..c103ee4 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodeRemoveCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodeRemoveCommandTest.php @@ -7,7 +7,7 @@ class NodeRemoveCommandTest extends BaseCommandTest { - public function setUp() + public function setUp(): void { parent::setUp(); diff --git a/tests/PHPCR/Tests/Util/Console/Command/NodeTouchCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodeTouchCommandTest.php index ee0dcd2..0bbb59a 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodeTouchCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodeTouchCommandTest.php @@ -20,7 +20,7 @@ class NodeTouchCommandTest extends BaseCommandTest */ public $phpcrHelper; - public function setUp() + public function setUp(): void { parent::setUp(); @@ -32,13 +32,13 @@ public function setUp() ->disableOriginalConstructor() ->getMock(); - $this->phpcrHelper->expects($this->any()) + $this->phpcrHelper ->method('getSession') - ->will($this->returnValue($this->session)); + ->willReturn($this->session); - $this->phpcrHelper->expects($this->any()) + $this->phpcrHelper ->method('getName') - ->will($this->returnValue('phpcr')); + ->willReturn('phpcr'); $this->helperSet->set($this->phpcrHelper); } @@ -50,7 +50,7 @@ public function testTouch() $this->session->expects($this->exactly(2)) ->method('getNode') - ->will($this->returnCallback(function ($path) use ($node) { + ->willReturnCallback(function ($path) use ($node) { switch ($path) { case '/': return $node; @@ -59,12 +59,12 @@ public function testTouch() } throw new Exception('Unexpected '.$path); - })); + }); $this->node1->expects($this->once()) ->method('addNode') ->with('cms') - ->will($this->returnValue($child)); + ->willReturn($child); $this->session->expects($this->once()) ->method('save'); @@ -77,31 +77,31 @@ public function testUpdate() $nodeType = $this->createMock(NodeTypeInterface::class); $nodeType->expects($this->once()) ->method('getName') - ->will($this->returnValue('nt:unstructured')); + ->willReturn('nt:unstructured'); $this->session->expects($this->exactly(1)) ->method('getNode') ->with('/cms') - ->will($this->returnValue($this->node1)); + ->willReturn($this->node1); $this->node1->expects($this->once()) ->method('getPrimaryNodeType') - ->will($this->returnValue($nodeType)); + ->willReturn($nodeType); $me = $this; $this->phpcrHelper->expects($this->once()) ->method('processNode') - ->will($this->returnCallback(function ($output, $node, $options) use ($me) { + ->willReturnCallback(function ($output, $node, $options) use ($me) { $me->assertEquals($me->node1, $node); $me->assertEquals([ - 'setProp' => ['foo=bar'], - 'removeProp' => ['bar'], - 'addMixins' => ['foo:bar'], + 'setProp' => ['foo=bar'], + 'removeProp' => ['bar'], + 'addMixins' => ['foo:bar'], 'removeMixins' => ['bar:foo'], - 'dump' => true, + 'dump' => true, ], $options); - })); + }); $this->executeCommand('phpcr:node:touch', [ 'path' => '/cms', diff --git a/tests/PHPCR/Tests/Util/Console/Command/NodeTypeListCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodeTypeListCommandTest.php index ea81be9..f74f6fd 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodeTypeListCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodeTypeListCommandTest.php @@ -13,7 +13,7 @@ class NodeTypeListCommandTest extends BaseCommandTest */ private $nodeTypeManager; - public function setUp() + public function setUp(): void { parent::setUp(); @@ -27,15 +27,15 @@ public function testNodeTypeList() { $this->session->expects($this->once()) ->method('getWorkspace') - ->will($this->returnValue($this->workspace)); + ->willReturn($this->workspace); $this->workspace->expects($this->once()) ->method('getNodeTypeManager') - ->will($this->returnValue($this->nodeTypeManager)); + ->willReturn($this->nodeTypeManager); $this->nodeTypeManager->expects($this->once()) ->method('getAllNodeTypes') - ->will($this->returnValue([])); + ->willReturn([]); $this->executeCommand('phpcr:node-type:list', []); } diff --git a/tests/PHPCR/Tests/Util/Console/Command/NodeTypeRegisterCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodeTypeRegisterCommandTest.php index c2f00a5..b39fe38 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodeTypeRegisterCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodeTypeRegisterCommandTest.php @@ -13,7 +13,7 @@ class NodeTypeRegisterCommandTest extends BaseCommandTest */ private $nodeTypeManager; - public function setUp() + public function setUp(): void { parent::setUp(); @@ -27,11 +27,11 @@ public function testNodeTypeRegister() { $this->session->expects($this->once()) ->method('getWorkspace') - ->will($this->returnValue($this->workspace)); + ->willReturn($this->workspace); $this->workspace->expects($this->once()) ->method('getNodeTypeManager') - ->will($this->returnValue($this->nodeTypeManager)); + ->willReturn($this->nodeTypeManager); $this->nodeTypeManager->expects($this->once()) ->method('registerNodeTypesCnd'); diff --git a/tests/PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php index 56195c1..7d3a83e 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php @@ -14,7 +14,7 @@ class NodesUpdateCommandTest extends BaseCommandTest */ private $query; - public function setUp() + public function setUp(): void { parent::setUp(); @@ -44,28 +44,26 @@ protected function setupQueryManager($options) { $options = array_merge(['query' => ''], $options); - $this->session->expects($this->any()) + $this->session ->method('getWorkspace') - ->will($this->returnValue($this->workspace)); + ->willReturn($this->workspace); - $this->workspace->expects($this->any()) + $this->workspace ->method('getQueryManager') - ->will($this->returnValue($this->queryManager)); + ->willReturn($this->queryManager); - $this->queryManager->expects($this->any()) + $this->queryManager ->method('createQuery') ->with($options['query'], 'JCR-SQL2') - ->will($this->returnValue($this->query)); + ->willReturn($this->query); - $this->query->expects($this->any()) + $this->query ->method('execute') - ->will($this->returnValue([ - $this->row1, - ])); + ->willReturn([$this->row1]); - $this->row1->expects($this->any()) + $this->row1 ->method('getNode') - ->will($this->returnValue($this->node1)); + ->willReturn($this->node1); } /** diff --git a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceCreateCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceCreateCommandTest.php index 9e9a15f..7df686b 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceCreateCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceCreateCommandTest.php @@ -7,7 +7,7 @@ class WorkspaceCreateCommandTest extends BaseCommandTest { - public function setUp() + public function setUp(): void { parent::setUp(); @@ -18,16 +18,16 @@ public function testCreate() { $this->session->expects($this->once()) ->method('getWorkspace') - ->will($this->returnValue($this->workspace)); + ->willReturn($this->workspace); $this->session->expects($this->once()) ->method('getRepository') - ->will($this->returnValue($this->repository)); + ->willReturn($this->repository); $this->repository->expects($this->once()) ->method('getDescriptor') ->with(RepositoryInterface::OPTION_WORKSPACE_MANAGEMENT_SUPPORTED) - ->will($this->returnValue(true)); + ->willReturn(true); $this->workspace->expects($this->once()) ->method('createWorkspace') @@ -35,7 +35,7 @@ public function testCreate() $this->workspace->expects($this->once()) ->method('getAccessibleWorkspaceNames') - ->will($this->returnValue(['default'])); + ->willReturn(['default']); $this->executeCommand('phpcr:workspace:create', [ 'name' => 'test_workspace', @@ -49,20 +49,20 @@ public function testCreateExisting() { $this->session->expects($this->exactly(2)) ->method('getWorkspace') - ->will($this->returnValue($this->workspace)); + ->willReturn($this->workspace); $this->session->expects($this->exactly(2)) ->method('getRepository') - ->will($this->returnValue($this->repository)); + ->willReturn($this->repository); $this->repository->expects($this->exactly(2)) ->method('getDescriptor') ->with(RepositoryInterface::OPTION_WORKSPACE_MANAGEMENT_SUPPORTED) - ->will($this->returnValue(true)); + ->willReturn(true); $this->workspace->expects($this->exactly(2)) ->method('getAccessibleWorkspaceNames') - ->will($this->returnValue(['default', 'test'])); + ->willReturn(['default', 'test']); $tester = $this->executeCommand( 'phpcr:workspace:create', @@ -70,7 +70,7 @@ public function testCreateExisting() 2 ); - $this->assertContains('already has a workspace called "test"', $tester->getDisplay()); + $this->assertStringContainsString('already has a workspace called "test"', $tester->getDisplay()); $tester = $this->executeCommand( 'phpcr:workspace:create', @@ -81,6 +81,6 @@ public function testCreateExisting() 0 ); - $this->assertContains('already has a workspace called "test"', $tester->getDisplay()); + $this->assertStringContainsString('already has a workspace called "test"', $tester->getDisplay()); } } diff --git a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceDeleteCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceDeleteCommandTest.php index c660f1d..9808db4 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceDeleteCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceDeleteCommandTest.php @@ -7,7 +7,7 @@ class WorkspaceDeleteCommandTest extends BaseCommandTest { - public function setUp() + public function setUp(): void { parent::setUp(); @@ -18,20 +18,20 @@ public function testDelete() { $this->session->expects($this->once()) ->method('getWorkspace') - ->will($this->returnValue($this->workspace)); + ->willReturn($this->workspace); $this->workspace->expects($this->once()) ->method('getAccessibleWorkspaceNames') - ->will($this->returnValue(['default', 'test_workspace', 'other'])); + ->willReturn(['default', 'test_workspace', 'other']); $this->session->expects($this->once()) ->method('getRepository') - ->will($this->returnValue($this->repository)); + ->willReturn($this->repository); $this->repository->expects($this->once()) ->method('getDescriptor') ->with(RepositoryInterface::OPTION_WORKSPACE_MANAGEMENT_SUPPORTED) - ->will($this->returnValue(true)); + ->willReturn(true); $this->workspace->expects($this->once()) ->method('deleteWorkspace') @@ -42,24 +42,24 @@ public function testDelete() '--force' => 'true', ]); - $this->assertContains("Deleted workspace 'test_workspace'.", $ct->getDisplay()); + $this->assertStringContainsString("Deleted workspace 'test_workspace'.", $ct->getDisplay()); } public function testDeleteNonexistent() { $this->session->expects($this->once()) ->method('getWorkspace') - ->will($this->returnValue($this->workspace)); + ->willReturn($this->workspace); $this->workspace->expects($this->once()) ->method('getAccessibleWorkspaceNames') - ->will($this->returnValue(['default', 'other'])); + ->willReturn(['default', 'other']); $ct = $this->executeCommand('phpcr:workspace:delete', [ 'name' => 'test_workspace', '--force' => 'true', ]); - $this->assertContains("Workspace 'test_workspace' does not exist.", $ct->getDisplay()); + $this->assertStringContainsString("Workspace 'test_workspace' does not exist.", $ct->getDisplay()); } } diff --git a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceExportCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceExportCommandTest.php index 1a73da4..a16e265 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceExportCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceExportCommandTest.php @@ -7,14 +7,14 @@ class WorkspaceExportCommandTest extends BaseCommandTest { - public function setUp() + public function setUp(): void { parent::setUp(); $this->application->add(new WorkspaceExportCommand()); } - public function tearDown() + public function tearDown(): void { unlink('test'); } @@ -23,17 +23,22 @@ public function testNodeTypeList() { $this->session->expects($this->once()) ->method('getRepository') - ->will($this->returnValue($this->repository)); + ->willReturn($this->repository); $this->repository->expects($this->once()) ->method('getDescriptor') ->with(RepositoryInterface::OPTION_XML_EXPORT_SUPPORTED) - ->will($this->returnValue(true)); + ->willReturn(true); $this->session->expects($this->once()) ->method('exportSystemView'); - $this->assertFileNotExists('test', 'test export file must not exist, it will be overwritten'); + if (method_exists($this, 'assertFileDoesNotExist')) { + $this->assertFileDoesNotExist('test', 'test export file must not exist, it will be overwritten'); + } else { + // support phpunit 8 and older, can be removed when we only support php 9 or newer + $this->assertFileNotExists('test', 'test export file must not exist, it will be overwritten'); + } $ct = $this->executeCommand('phpcr:workspace:export', [ 'filename' => 'test', diff --git a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceImportCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceImportCommandTest.php index f74adb6..d2b5ebd 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceImportCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceImportCommandTest.php @@ -8,7 +8,7 @@ class WorkspaceImportCommandTest extends BaseCommandTest { - public function setUp() + public function setUp(): void { parent::setUp(); @@ -19,12 +19,12 @@ public function testImport() { $this->session->expects($this->once()) ->method('getRepository') - ->will($this->returnValue($this->repository)); + ->willReturn($this->repository); $this->repository->expects($this->once()) ->method('getDescriptor') ->with(RepositoryInterface::OPTION_XML_IMPORT_SUPPORTED) - ->will($this->returnValue(true)); + ->willReturn(true); $this->session->expects($this->once()) ->method('importXml') @@ -34,19 +34,19 @@ public function testImport() 'filename' => 'test_import.xml', ]); - $this->assertContains('Successfully imported', $ct->getDisplay()); + $this->assertStringContainsString('Successfully imported', $ct->getDisplay()); } public function testImportUuidBehaviorThrow() { $this->session->expects($this->once()) ->method('getRepository') - ->will($this->returnValue($this->repository)); + ->willReturn($this->repository); $this->repository->expects($this->once()) ->method('getDescriptor') ->with(RepositoryInterface::OPTION_XML_IMPORT_SUPPORTED) - ->will($this->returnValue(true)); + ->willReturn(true); $this->session->expects($this->once()) ->method('importXml') @@ -57,6 +57,6 @@ public function testImportUuidBehaviorThrow() '--uuid-behavior' => 'throw', ]); - $this->assertContains('Successfully imported', $ct->getDisplay()); + $this->assertStringContainsString('Successfully imported', $ct->getDisplay()); } } diff --git a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceListCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceListCommandTest.php index ef1f507..86ef8fc 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceListCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceListCommandTest.php @@ -6,7 +6,7 @@ class WorkspaceListCommandTest extends BaseCommandTest { - public function setUp() + public function setUp(): void { parent::setUp(); @@ -17,13 +17,11 @@ public function testNodeTypeList() { $this->session->expects($this->once()) ->method('getWorkspace') - ->will($this->returnValue($this->workspace)); + ->willReturn($this->workspace); $this->workspace->expects($this->once()) ->method('getAccessibleWorkspaceNames') - ->will($this->returnValue([ - 'foo', 'bar', - ])); + ->willReturn(['foo', 'bar']); $ct = $this->executeCommand('phpcr:workspace:list', [ ]); diff --git a/tests/PHPCR/Tests/Util/Console/Command/WorkspacePurgeCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/WorkspacePurgeCommandTest.php index b85fab0..5938ac8 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/WorkspacePurgeCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/WorkspacePurgeCommandTest.php @@ -6,7 +6,7 @@ class WorkspacePurgeCommandTest extends BaseCommandTest { - public function setUp() + public function setUp(): void { parent::setUp(); @@ -17,15 +17,15 @@ public function testNodeTypePurge() { $this->session->expects($this->once()) ->method('getRootNode') - ->will($this->returnValue($this->node1)); + ->willReturn($this->node1); $this->node1->expects($this->once()) ->method('getProperties') - ->will($this->returnValue([])); + ->willReturn([]); $this->node1->expects($this->once()) ->method('getNodes') - ->will($this->returnValue([])); + ->willReturn([]); $this->executeCommand('phpcr:workspace:purge', [ '--force' => true, diff --git a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceQueryCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceQueryCommandTest.php index 112d161..9ab438b 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/WorkspaceQueryCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/WorkspaceQueryCommandTest.php @@ -13,7 +13,7 @@ class WorkspaceQueryCommandTest extends BaseCommandTest */ protected $query; - public function setUp() + public function setUp(): void { parent::setUp(); @@ -23,30 +23,30 @@ public function setUp() public function testQuery() { - $this->queryManager->expects($this->any()) + $this->queryManager ->method('getSupportedQueryLanguages') - ->will($this->returnValue(['JCR-SQL2'])); + ->willReturn(['JCR-SQL2']); - $this->session->expects($this->any()) + $this->session ->method('getWorkspace') - ->will($this->returnValue($this->workspace)); + ->willReturn($this->workspace); - $this->workspace->expects($this->any()) + $this->workspace ->method('getQueryManager') - ->will($this->returnValue($this->queryManager)); + ->willReturn($this->queryManager); $this->queryManager->expects($this->once()) ->method('createQuery') ->with('SELECT foo FROM foo', 'JCR-SQL2') - ->will($this->returnValue($this->query)); + ->willReturn($this->query); $this->query->expects($this->once()) ->method('getLanguage') - ->will($this->returnValue('FOOBAR')); + ->willReturn('FOOBAR'); $this->query->expects($this->once()) ->method('execute') - ->will($this->returnValue([])); + ->willReturn([]); $this->executeCommand('phpcr:workspace:query', [ 'query' => 'SELECT foo FROM foo', diff --git a/tests/PHPCR/Tests/Util/Console/Helper/PhpcrConsoleDumperHelperTest.php b/tests/PHPCR/Tests/Util/Console/Helper/PhpcrConsoleDumperHelperTest.php index f08d723..057b3a6 100644 --- a/tests/PHPCR/Tests/Util/Console/Helper/PhpcrConsoleDumperHelperTest.php +++ b/tests/PHPCR/Tests/Util/Console/Helper/PhpcrConsoleDumperHelperTest.php @@ -14,7 +14,7 @@ class PhpcrConsoleDumperHelperTest extends TestCase */ private $helper; - public function setUp() + public function setUp(): void { $this->outputMock = $this->createMock(OutputInterface::class); $this->helper = new PhpcrConsoleDumperHelper(); diff --git a/tests/PHPCR/Tests/Util/NodeHelperTest.php b/tests/PHPCR/Tests/Util/NodeHelperTest.php index 6453883..5a1f392 100644 --- a/tests/PHPCR/Tests/Util/NodeHelperTest.php +++ b/tests/PHPCR/Tests/Util/NodeHelperTest.php @@ -2,6 +2,7 @@ namespace PHPCR\Tests\Util; +use PHPCR\RepositoryException; use PHPCR\Tests\Stubs\MockNode; use PHPCR\Util\NodeHelper; use PHPUnit\Framework\MockObject\MockObject; @@ -67,7 +68,7 @@ public function testGenerateAutoNodeName($hint, $expect) { $result = NodeHelper::generateAutoNodeName($this->usedNames, $this->namespaces, 'a', $hint); if (true === $expect) { - $this->assertNotContains(':', $result); + $this->assertStringNotContainsString(':', $result); } else { $this->assertEquals($expect, substr($result, 0, strlen($expect))); } @@ -75,10 +76,10 @@ public function testGenerateAutoNodeName($hint, $expect) /** * @dataProvider invalidHints - * @expectedException \PHPCR\RepositoryException */ public function testGenerateAutoNodeNameInvalid($hint) { + $this->expectException(RepositoryException::class); NodeHelper::generateAutoNodeName($this->usedNames, $this->namespaces, 'a', $hint); } @@ -89,22 +90,22 @@ public function testIsSystemItem() $sys->expects($this->once()) ->method('getDepth') - ->will($this->returnValue(0)); + ->willReturn(0); $sys->expects($this->once()) ->method('getName') - ->will($this->returnValue('jcr:root')); + ->willReturn('jcr:root'); $this->assertTrue(NodeHelper::isSystemItem($sys)); $sys = $this->createMock(MockNode::class); $sys->expects($this->once()) ->method('getDepth') - ->will($this->returnValue(1)); + ->willReturn(1); $sys->expects($this->once()) ->method('getName') - ->will($this->returnValue('jcr:system')); + ->willReturn('jcr:system'); $this->assertTrue(NodeHelper::isSystemItem($sys)); @@ -112,11 +113,11 @@ public function testIsSystemItem() $top = $this->createMock(MockNode::class); $top->expects($this->once()) ->method('getDepth') - ->will($this->returnValue(1)); + ->willReturn(1); $top->expects($this->once()) ->method('getName') - ->will($this->returnValue('jcrname')) // this is NOT in the jcr namespace + ->willReturn('jcrname') // this is NOT in the jcr namespace ; $this->assertFalse(NodeHelper::isSystemItem($top)); @@ -125,7 +126,7 @@ public function testIsSystemItem() $deep = $this->createMock(MockNode::class); $deep->expects($this->once()) ->method('getDepth') - ->will($this->returnValue(2)); + ->willReturn(2); $this->assertFalse(NodeHelper::isSystemItem($deep)); } diff --git a/tests/PHPCR/Tests/Util/PathHelperTest.php b/tests/PHPCR/Tests/Util/PathHelperTest.php index 32d7116..14d0911 100644 --- a/tests/PHPCR/Tests/Util/PathHelperTest.php +++ b/tests/PHPCR/Tests/Util/PathHelperTest.php @@ -65,12 +65,10 @@ public function dataproviderValidAbsolutePathsWithNamespaces() ]; } - /** - * @expectedExceptionMessage invalidprefix and other-ns - */ public function testAssertInvalidNamespaceAbsolutePath() { $this->expectException(NamespaceException::class); + $this->expectExceptionMessage('invalidprefix and other-ns'); PathHelper::assertValidAbsolutePath('/invalidprefix:localname/other-ns:test/invalidprefix:node/bla', false, true, ['jcr', 'nt']); } @@ -199,11 +197,11 @@ public static function dataproviderAbsolutizePath() } /** - * @expectedException \PHPCR\RepositoryException * @dataProvider dataproviderAbsolutizePathInvalid */ public function testAbsolutizePathInvalidThrow($inputPath, $context, $target) { + $this->expectException(RepositoryException::class); PathHelper::absolutizePath($inputPath, $context, $target); } @@ -328,12 +326,10 @@ public function dataproviderGetLocalNodeName() ]; } - /** - * @expectedExceptionMessage must be an absolute path - */ public function testGetNodeNameMustBeAbsolute() { $this->expectException(RepositoryException::class); + $this->expectExceptionMessage('must be an absolute path'); PathHelper::getNodeName('foobar'); } diff --git a/tests/PHPCR/Tests/Util/QOM/QueryBuilderTest.php b/tests/PHPCR/Tests/Util/QOM/QueryBuilderTest.php index 573a1b0..a96ef09 100644 --- a/tests/PHPCR/Tests/Util/QOM/QueryBuilderTest.php +++ b/tests/PHPCR/Tests/Util/QOM/QueryBuilderTest.php @@ -22,7 +22,7 @@ class QueryBuilderTest extends TestCase */ protected $qf; - public function setUp() + public function setUp(): void { $this->qf = $this->getMockBuilder(QueryObjectModelFactoryInterface::class) ->setMethods([]) @@ -324,7 +324,7 @@ public function testGetQuery() $this->qf->expects($this->once()) ->method('createQuery') - ->will($this->returnValue('true')); + ->willReturn('true'); $qb->getQuery(); } @@ -363,7 +363,7 @@ public function testGetQueryWithOffsetAndLimit() $this->qf->expects($this->once()) ->method('createQuery') - ->will($this->returnValue($query)); + ->willReturn($query); $qb->getQuery(); } @@ -405,7 +405,7 @@ public function testExecute() $this->qf->expects($this->once()) ->method('createQuery') ->with($source, $constraint, [], []) - ->will($this->returnValue($query)); + ->willReturn($query); $qb = new QueryBuilder($this->qf); $qb->from($source) diff --git a/tests/PHPCR/Tests/Util/QOM/Sql1GeneratorTest.php b/tests/PHPCR/Tests/Util/QOM/Sql1GeneratorTest.php index e956916..aa0a7aa 100644 --- a/tests/PHPCR/Tests/Util/QOM/Sql1GeneratorTest.php +++ b/tests/PHPCR/Tests/Util/QOM/Sql1GeneratorTest.php @@ -14,7 +14,7 @@ class Sql1GeneratorTest extends TestCase */ protected $generator; - public function setUp() + public function setUp(): void { $this->generator = new Sql1Generator(new ValueConverter()); } diff --git a/tests/PHPCR/Tests/Util/QOM/Sql2GeneratorTest.php b/tests/PHPCR/Tests/Util/QOM/Sql2GeneratorTest.php index bf3d0f0..f28dff4 100644 --- a/tests/PHPCR/Tests/Util/QOM/Sql2GeneratorTest.php +++ b/tests/PHPCR/Tests/Util/QOM/Sql2GeneratorTest.php @@ -13,7 +13,7 @@ class Sql2GeneratorTest extends BaseSqlGeneratorTest */ protected $generator; - public function setUp() + public function setUp(): void { $this->generator = new Sql2Generator(new ValueConverter()); } diff --git a/tests/PHPCR/Tests/Util/QOM/Sql2ToQomQueryConverterTest.php b/tests/PHPCR/Tests/Util/QOM/Sql2ToQomQueryConverterTest.php index 79a8863..393e3e6 100644 --- a/tests/PHPCR/Tests/Util/QOM/Sql2ToQomQueryConverterTest.php +++ b/tests/PHPCR/Tests/Util/QOM/Sql2ToQomQueryConverterTest.php @@ -25,19 +25,17 @@ class Sql2ToQomQueryConverterTest extends TestCase */ protected $converter; - public function setUp() + public function setUp(): void { $this->qomFactory = $this->createMock(QueryObjectModelFactoryInterface::class); $this->valueConverter = $this->createMock(ValueConverter::class); $this->converter = new Sql2ToQomQueryConverter($this->qomFactory, $this->valueConverter); } - /** - * @expectedExceptionMessage Error parsing query - */ public function testInvalid() { $this->expectException(InvalidQueryException::class); + $this->expectExceptionMessage('Error parsing query'); $this->converter->parse('SELECTING WITH AN INVALID QUERY'); } diff --git a/tests/PHPCR/Tests/Util/ValueConverterTest.php b/tests/PHPCR/Tests/Util/ValueConverterTest.php index a5aaa41..e57bc46 100644 --- a/tests/PHPCR/Tests/Util/ValueConverterTest.php +++ b/tests/PHPCR/Tests/Util/ValueConverterTest.php @@ -22,7 +22,7 @@ class ValueConverterTest extends TestCase */ private $valueConverter; - public function setUp() + public function setUp(): void { $this->valueConverter = new ValueConverter(); } @@ -54,15 +54,13 @@ public function dataConversionMatrix() $nodeMock = $this->createMock(MockNode::class); $nodeMock - ->expects($this->any()) ->method('getIdentifier') - ->will($this->returnValue('38b7cf18-c417-477a-af0b-c1e92a290c9a')); + ->willReturn('38b7cf18-c417-477a-af0b-c1e92a290c9a'); $nodeMock - ->expects($this->any()) ->method('isNodeType') ->with('mix:referenceable') - ->will($this->returnValue(true)); + ->willReturn(true); return [ // String to... @@ -303,18 +301,18 @@ public function testConvertType($value, $srcType, $expected, $targetType) public function testConvertTypeToBinary() { $stream = $this->valueConverter->convertType('test string', PropertyType::BINARY); - $this->assertInternalType('resource', $stream); + $this->assertIsResource($stream); $string = stream_get_contents($stream); $this->assertEquals('test string', $string); $stream = $this->valueConverter->convertType('test string', PropertyType::BINARY, PropertyType::BINARY); - $this->assertInternalType('resource', $stream); + $this->assertIsResource($stream); $string = stream_get_contents($stream); $this->assertEquals('test string', $string); $date = new DateTime('20.12.2012'); $stream = $this->valueConverter->convertType($date, PropertyType::BINARY); - $this->assertInternalType('resource', $stream); + $this->assertIsResource($stream); $string = stream_get_contents($stream); $readDate = new DateTime($string); $this->assertEquals($date->getTimestamp(), $readDate->getTimestamp()); @@ -336,7 +334,7 @@ public function testConvertTypeArray() PropertyType::DATE, PropertyType::STRING ); - $this->assertInternalType('array', $result); + $this->assertIsArray($result); $this->assertCount(2, $result); $this->assertInstanceOf(DateTime::class, $result[0]); @@ -397,7 +395,7 @@ public function testConvertNewNode() $nodeMock ->expects($this->never()) ->method('isNew') - ->will($this->returnValue(true)); + ->willReturn(true); $this->valueConverter->convertType($nodeMock, PropertyType::STRING); } @@ -409,12 +407,12 @@ public function testConvertNonRefNode() $nodeMock ->expects($this->never()) ->method('isNew') - ->will($this->returnValue(false)); + ->willReturn(false); $nodeMock ->expects($this->once()) ->method('isNodeType') ->with('mix:referenceable') - ->will($this->returnValue(false)); + ->willReturn(false); $this->valueConverter->convertType($nodeMock, PropertyType::STRING); } From 1854d5dd4baee5c5cb2f87d2d56a8cb3ee26251a Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Thu, 8 Oct 2020 11:04:31 +0200 Subject: [PATCH 34/88] phpunit 9 --- .../Console/Command/NodesUpdateCommandTest.php | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/tests/PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php b/tests/PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php index 7d3a83e..542fe10 100644 --- a/tests/PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php +++ b/tests/PHPCR/Tests/Util/Console/Command/NodesUpdateCommandTest.php @@ -95,23 +95,22 @@ public function testNodeUpdate($options) '--remove-mixin' => [], ]; + $setPropertyArguments = []; foreach ($options['setProp'] as $setProp) { list($prop, $value) = $setProp; - $this->node1->expects($this->at(0)) - ->method('setProperty') - ->with($prop, $value); - + $setPropertyArguments[] = [$prop, $value, null]; $args['--set-prop'][] = $prop.'='.$value; } foreach ($options['removeProp'] as $prop) { - $this->node1->expects($this->at(1)) - ->method('setProperty') - ->with($prop, null); - + $setPropertyArguments[] = [$prop, null, null]; $args['--remove-prop'][] = $prop; } + $this->node1 + ->method('setProperty') + ->withConsecutive(...$setPropertyArguments); + foreach ($options['addMixin'] as $mixin) { $this->node1->expects($this->once()) ->method('addMixin') From 3be690cb40a30f702c5f9f475f1cd97af0641970 Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Thu, 8 Oct 2020 13:48:18 +0200 Subject: [PATCH 35/88] prepare release --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 02c5aa5..b44886b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,11 @@ Changelog ========= +1.5.1 +----- + +* Fix issues with PHPUnit 9 + 1.5.0 ----- From 7f8420e43db71a2797395a863f32a6b11e6c1ab9 Mon Sep 17 00:00:00 2001 From: Alexander Schranz Date: Fri, 22 Jan 2021 11:42:11 +0100 Subject: [PATCH 36/88] Add PHP 8 testcase and migrate to github actions (#193) * Add PHP 8 testcase and migrate to github actions --- .github/workflows/test-application.yaml | 43 +++++++++++++++++++++++++ .travis.yml | 33 ------------------- 2 files changed, 43 insertions(+), 33 deletions(-) create mode 100644 .github/workflows/test-application.yaml delete mode 100644 .travis.yml diff --git a/.github/workflows/test-application.yaml b/.github/workflows/test-application.yaml new file mode 100644 index 0000000..52d38ab --- /dev/null +++ b/.github/workflows/test-application.yaml @@ -0,0 +1,43 @@ +name: Test application + +on: + pull_request: + push: + branches: + - 'master' + - '[0-9]+.x' + - '[0-9]+.[0-9]+' + - '[0-9]+.[0-9]+.x' + +jobs: + test: + name: 'PHP ${{ matrix.php-version }} ${{ matrix.dependencies}}' + runs-on: ubuntu-20.04 + + strategy: + fail-fast: false + matrix: + include: + - php-version: '7.1' + dependencies: 'lowest' + - php-version: '7.4' + - php-version: '8.0' + + steps: + - name: Checkout project + uses: actions/checkout@v2 + + - name: Install and configure PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php-version }} + tools: 'composer:v2' + + - name: Install dependencies with Composer + uses: ramsey/composer-install@v1 + with: + dependency-versions: ${{ matrix.dependencies }} + composer-options: --prefer-dist + + - name: Execute test cases + run: vendor/bin/phpunit diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 0705a33..0000000 --- a/.travis.yml +++ /dev/null @@ -1,33 +0,0 @@ -language: php - -php: - - 7.1 - - 7.2 - - 7.3 - - 7.4 - - nightly - -env: - - PACKAGE_VERSION=high - -sudo: false - -matrix: - include: - - php: 7.1 - env: PACKAGE_VERSION=low - - php: 7.4 - env: - - PACKAGE_VERSION=high - - MINIMUM_STABILITY=dev - -before_script: - - composer selfupdate - - if [[ "$MINIMUM_STABILITY" ]]; then composer config minimum-stability $MINIMUM_STABILITY ; fi - - if [[ "$PACKAGE_VERSION" == "high" ]]; then composer update --prefer-source; fi - - if [[ "$PACKAGE_VERSION" == "low" ]]; then composer update --prefer-lowest --prefer-source; fi - -script: php vendor/bin/phpunit - -notifications: - irc: "irc.freenode.org#jackalope" From fcafc4c370bf6bf523b86aecc60c57e468cef97b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Florian=20Ko=CC=88rner?= Date: Mon, 12 Apr 2021 16:54:56 +0200 Subject: [PATCH 37/88] Fix: Sql2Scanner Delimiter Regex --- CHANGELOG.md | 5 ++ src/PHPCR/Util/QOM/Sql2Scanner.php | 2 +- .../PHPCR/Tests/Util/QOM/Sql2ScannerTest.php | 47 +++++++++++++++++++ 3 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 tests/PHPCR/Tests/Util/QOM/Sql2ScannerTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index b44886b..1277cc6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,11 @@ Changelog ========= +1.5.2 +----- + +* Fix SQL 2 scanner delimiter detection to handle that tokens don't necessarily have whitespace between them. + 1.5.1 ----- diff --git a/src/PHPCR/Util/QOM/Sql2Scanner.php b/src/PHPCR/Util/QOM/Sql2Scanner.php index 9e8bc68..fd5c563 100644 --- a/src/PHPCR/Util/QOM/Sql2Scanner.php +++ b/src/PHPCR/Util/QOM/Sql2Scanner.php @@ -171,7 +171,7 @@ protected function scan($sql2) $regexpTokens[] = preg_quote($token, '/'); } - $regexp = '/^'.implode('([ \t\n]+)', $regexpTokens).'$/'; + $regexp = '/^'.implode('([ \t\n]*)', $regexpTokens).'$/'; preg_match($regexp, $sql2, $this->delimiters); $this->delimiters[0] = ''; diff --git a/tests/PHPCR/Tests/Util/QOM/Sql2ScannerTest.php b/tests/PHPCR/Tests/Util/QOM/Sql2ScannerTest.php new file mode 100644 index 0000000..d3bda9c --- /dev/null +++ b/tests/PHPCR/Tests/Util/QOM/Sql2ScannerTest.php @@ -0,0 +1,47 @@ +fetchNextToken()) { + $this->assertEquals(array_shift($expected), $token); + } + } + + public function testDelimiter() + { + $scanner = new Sql2Scanner('SELECT page.* FROM [nt:unstructured] AS page'); + $expected = [ + '', + ' ', + '', + '', + ' ', + ' ', + ' ', + ' ', + ]; + + while ($token = $scanner->fetchNextToken()) { + $this->assertEquals(array_shift($expected), $scanner->getPreviousDelimiter()); + } + } +} From 9706c4be73de7ffbfcec09ca8d1ade193f2a08ba Mon Sep 17 00:00:00 2001 From: Jordi Date: Thu, 18 Nov 2021 08:50:15 +0100 Subject: [PATCH 38/88] Allow Symfony 6 --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index fe78ebf..3c26226 100644 --- a/composer.json +++ b/composer.json @@ -29,7 +29,7 @@ "require": { "php": "^7.1 || ^8.0", "phpcr/phpcr": "~2.1.0", - "symfony/console": "^2.3 || ^3.0 || ^4.0 || ^5.0" + "symfony/console": "^2.3 || ^3.0 || ^4.0 || ^5.0 || ^6.0" }, "require-dev": { "ramsey/uuid": "^3.5", From ab0c67e4e1d73bd45ed0427643b64880b1fbfbeb Mon Sep 17 00:00:00 2001 From: Jordi Sala Morales Date: Fri, 19 Nov 2021 08:28:59 +0100 Subject: [PATCH 39/88] Adapt workflow --- .github/workflows/test-application.yaml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.github/workflows/test-application.yaml b/.github/workflows/test-application.yaml index 52d38ab..caa44f9 100644 --- a/.github/workflows/test-application.yaml +++ b/.github/workflows/test-application.yaml @@ -22,6 +22,8 @@ jobs: dependencies: 'lowest' - php-version: '7.4' - php-version: '8.0' + - php-version: '8.0' + dev-dependencies: true steps: - name: Checkout project @@ -33,6 +35,10 @@ jobs: php-version: ${{ matrix.php-version }} tools: 'composer:v2' + - name: Allow unstable dependencies + if: matrix.dev-dependencies == true + run: composer config minimum-stability dev + - name: Install dependencies with Composer uses: ramsey/composer-install@v1 with: From 2669c539b0f89da0e2025141b1231fd5b8d28b94 Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Fri, 19 Nov 2021 09:48:49 +0100 Subject: [PATCH 40/88] tweak job names --- .github/workflows/test-application.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test-application.yaml b/.github/workflows/test-application.yaml index caa44f9..64e2ade 100644 --- a/.github/workflows/test-application.yaml +++ b/.github/workflows/test-application.yaml @@ -11,7 +11,7 @@ on: jobs: test: - name: 'PHP ${{ matrix.php-version }} ${{ matrix.dependencies}}' + name: "PHP ${{ matrix.php-version }} ${{ matrix.dependencies }} ${{ matrix.dev-dependencies && 'dev' }}" runs-on: ubuntu-20.04 strategy: From 210fd2593c18d93cc4356d44b71654d4465d94bf Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Fri, 19 Nov 2021 08:52:20 +0000 Subject: [PATCH 41/88] Apply fixes from StyleCI --- src/PHPCR/Util/UUIDHelper.php | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/PHPCR/Util/UUIDHelper.php b/src/PHPCR/Util/UUIDHelper.php index c684c1e..546a71d 100644 --- a/src/PHPCR/Util/UUIDHelper.php +++ b/src/PHPCR/Util/UUIDHelper.php @@ -46,25 +46,25 @@ public static function generateUUID() return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x', // 32 bits for "time_low" - mt_rand(0, 0xffff), - mt_rand(0, 0xffff), + mt_rand(0, 0xFFFF), + mt_rand(0, 0xFFFF), // 16 bits for "time_mid" - mt_rand(0, 0xffff), + mt_rand(0, 0xFFFF), // 16 bits for "time_hi_and_version", // four most significant bits holds version number 4 - mt_rand(0, 0x0fff) | 0x4000, + mt_rand(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, + mt_rand(0, 0x3FFF) | 0x8000, // 48 bits for "node" - mt_rand(0, 0xffff), - mt_rand(0, 0xffff), - mt_rand(0, 0xffff) + mt_rand(0, 0xFFFF), + mt_rand(0, 0xFFFF), + mt_rand(0, 0xFFFF) ); } } From f35c51e3a061189f9156344e9fbdae8140da4792 Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Fri, 19 Nov 2021 09:54:19 +0100 Subject: [PATCH 42/88] build with php 8.1 --- .github/workflows/test-application.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/test-application.yaml b/.github/workflows/test-application.yaml index 64e2ade..1f624c1 100644 --- a/.github/workflows/test-application.yaml +++ b/.github/workflows/test-application.yaml @@ -24,6 +24,7 @@ jobs: - php-version: '8.0' - php-version: '8.0' dev-dependencies: true + - php-version: '8.1' steps: - name: Checkout project From 9c2243d0783d84bc2e2c89b5899bb36aa7eb9db4 Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Fri, 19 Nov 2021 09:56:37 +0100 Subject: [PATCH 43/88] prepare release --- CHANGELOG.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1277cc6..82ac683 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,12 @@ Changelog ========= +1.5.3 +----- + +* Compatible with Symfony 6 +* Compatible with PHP 8.1 + 1.5.2 ----- From 689aef1c591d72422829bf86c09941e508f8ff2a Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Tue, 23 Nov 2021 07:52:17 +0100 Subject: [PATCH 44/88] build all minor php versions --- .github/workflows/test-application.yaml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/test-application.yaml b/.github/workflows/test-application.yaml index 1f624c1..e8dde85 100644 --- a/.github/workflows/test-application.yaml +++ b/.github/workflows/test-application.yaml @@ -20,6 +20,8 @@ jobs: include: - php-version: '7.1' dependencies: 'lowest' + - php-version: '7.2' + - php-version: '7.3' - php-version: '7.4' - php-version: '8.0' - php-version: '8.0' From b814637e1764a2a652d4bad46a264b22ea1b9e1f Mon Sep 17 00:00:00 2001 From: mamazu Date: Mon, 29 Nov 2021 15:47:40 +0100 Subject: [PATCH 45/88] Fixing the string tokenization (#199) * Fixing the string tokenization * Adding more test cases and fixed bug in the parser Now the parser can understand escaped characters in the string --- src/PHPCR/Util/QOM/Sql2Scanner.php | 114 +++++++-------- .../Util/QOM/Sql2ToQomQueryConverter.php | 45 ++---- .../PHPCR/Tests/Util/QOM/Sql2ScannerTest.php | 130 ++++++++++++++++-- 3 files changed, 184 insertions(+), 105 deletions(-) diff --git a/src/PHPCR/Util/QOM/Sql2Scanner.php b/src/PHPCR/Util/QOM/Sql2Scanner.php index fd5c563..8639f22 100644 --- a/src/PHPCR/Util/QOM/Sql2Scanner.php +++ b/src/PHPCR/Util/QOM/Sql2Scanner.php @@ -26,13 +26,6 @@ class Sql2Scanner */ protected $tokens; - /** - * Delimiters between tokens. - * - * @var array - */ - protected $delimiters; - /** * Parsing position in the SQL string. * @@ -68,16 +61,6 @@ public function lookupNextToken($offset = 0) return ''; } - /** - * Get the delimiter that separated the two previous tokens. - * - * @return string - */ - public function getPreviousDelimiter() - { - return isset($this->delimiters[$this->curpos - 1]) ? $this->delimiters[$this->curpos - 1] : ' '; - } - /** * Get the next token and remove it from the queue. * Return an empty string when there are no more tokens. @@ -116,12 +99,12 @@ 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. * - * @see expectToken - * * @param array $tokens * @param bool $case_insensitive * * @throws InvalidQueryException + * + * @see expectToken */ public function expectTokens($tokens, $case_insensitive = true) { @@ -151,7 +134,7 @@ public function tokenIs($token, $value, $case_insensitive = true) } /** - * Scan a SQL2 string a extract the tokens. + * Scan a SQL2 string and extract the tokens. * * @param string $sql2 * @@ -160,49 +143,72 @@ public function tokenIs($token, $value, $case_insensitive = true) protected function scan($sql2) { $tokens = []; - $token = strtok($sql2, " \n\t"); - while ($token !== false) { - $this->tokenize($tokens, $token); - $token = strtok(" \n\t"); + $currentToken = ''; + $tokenEndChars = ['.', ',', '(', ')', '=']; + + $stringStartCharacter = false; + $isEscaped = false; + $escapedQuotesCount = 0; + foreach (\str_split($sql2) as $index => $character) { + if (!$stringStartCharacter && in_array($character, [' ', "\t", "\n"], true)) { + if ($currentToken !== '') { + $tokens[] = $currentToken; + } + $currentToken = ''; + continue; + } + if (!$stringStartCharacter && in_array($character, $tokenEndChars, true)) { + if ($currentToken !== '') { + $tokens[] = $currentToken; + } + $tokens[] = $character; + $currentToken = ''; + continue; + } + $currentToken .= $character; + + if (!$isEscaped && in_array($character, ['"', "'"], true)) { + // 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 = $this->getCharacterAtIndex($sql2, $index + 1); + if ($character === "'" && $nextCharacter === "'") { + $isEscaped = true; + $escapedQuotesCount++; + continue; + } + // If the escaped quotes are not paired up. eg. "I'''m cool" would be a parsing error + if ($escapedQuotesCount % 2 == 1 && $stringStartCharacter !== "'") { + throw new InvalidQueryException("Syntax error: Number of single quotes to be even: $currentToken"); + } + if ($character === $stringStartCharacter) { + // reached the end of the string + $stringStartCharacter = false; + $tokens[] = $currentToken; + $currentToken = ''; + } elseif (!$stringStartCharacter) { + // If there is no start character already we have found the beginning of a new string + $stringStartCharacter = $character; + } + } + $isEscaped = $character === '\\'; } - - $regexpTokens = []; - foreach ($tokens as $token) { - $regexpTokens[] = preg_quote($token, '/'); + if ($currentToken !== '') { + $tokens[] = $currentToken; } - $regexp = '/^'.implode('([ \t\n]*)', $regexpTokens).'$/'; - preg_match($regexp, $sql2, $this->delimiters); - $this->delimiters[0] = ''; + if ($stringStartCharacter) { + throw new InvalidQueryException("Syntax error: unterminated quoted string $currentToken in '$sql2'"); + } return $tokens; } - /** - * Tokenize a string returned by strtok to split the string at '.', ',', '(', '=' - * and ')' characters. - * - * @param array $tokens - * @param string $token - */ - protected function tokenize(&$tokens, $token) + private function getCharacterAtIndex($string, $index) { - $buffer = ''; - for ($i = 0; $i < strlen($token); $i++) { - $char = trim(substr($token, $i, 1)); - if (in_array($char, ['.', ',', '(', ')', '='])) { - if ($buffer !== '') { - $tokens[] = $buffer; - $buffer = ''; - } - $tokens[] = $char; - } else { - $buffer .= $char; - } + if ($index < strlen($string)) { + return $string[$index]; } - if ($buffer !== '') { - $tokens[] = $buffer; - } + return ''; } } diff --git a/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php b/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php index d3a7a46..a859ebd 100644 --- a/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php +++ b/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php @@ -756,27 +756,13 @@ protected function parseCastLiteral($token) $this->scanner->expectToken('('); $token = $this->scanner->fetchNextToken(); - $quoteString = false; - if (substr($token, 0, 1) === '\'') { - $quoteString = "'"; - } elseif (substr($token, 0, 1) === '"') { - $quoteString = '"'; - } + $quoteString = in_array($token[0], ['\'', '"'], true); if ($quoteString) { - while (substr($token, -1) !== $quoteString) { - $nextToken = $this->scanner->fetchNextToken(); - if ('' === $nextToken) { - break; - } - $token .= $nextToken; - } - - if (substr($token, -1) !== $quoteString) { - throw new InvalidQueryException("Syntax error: unterminated quoted string '$token' in '{$this->sql2}'"); - } + $quotesUsed = $token[0]; $token = substr($token, 1, -1); - $token = str_replace('\\'.$quoteString, $quoteString, $token); + // Un-escaping quotes + $token = str_replace('\\'.$quotesUsed, $quotesUsed, $token); } $this->scanner->expectToken('AS'); @@ -813,28 +799,13 @@ protected function parseLiteralValue() return $this->parseCastLiteral($token); } - $quoteString = false; - if (substr($token, 0, 1) === '\'') { - $quoteString = "'"; - } elseif (substr($token, 0, 1) === '"') { - $quoteString = '"'; - } + $quoteString = in_array($token[0], ['"', "'"], true); if ($quoteString) { - while (substr($token, -1) !== $quoteString) { - $nextToken = $this->scanner->fetchNextToken(); - if ('' === $nextToken) { - break; - } - $token .= $this->scanner->getPreviousDelimiter(); - $token .= $nextToken; - } - - if (substr($token, -1) !== $quoteString) { - throw new InvalidQueryException("Syntax error: unterminated quoted string $token in '{$this->sql2}'"); - } + $quotesUsed = $token[0]; $token = substr($token, 1, -1); - $token = str_replace('\\'.$quoteString, $quoteString, $token); + // Unescape quotes + $token = str_replace('\\'.$quotesUsed, $quotesUsed, $token); $token = str_replace("''", "'", $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)) { diff --git a/tests/PHPCR/Tests/Util/QOM/Sql2ScannerTest.php b/tests/PHPCR/Tests/Util/QOM/Sql2ScannerTest.php index d3bda9c..07da5dd 100644 --- a/tests/PHPCR/Tests/Util/QOM/Sql2ScannerTest.php +++ b/tests/PHPCR/Tests/Util/QOM/Sql2ScannerTest.php @@ -2,6 +2,7 @@ namespace PHPCR\Tests\Util\QOM; +use PHPCR\Query\InvalidQueryException; use PHPCR\Util\QOM\Sql2Scanner; use PHPUnit\Framework\TestCase; @@ -21,27 +22,128 @@ public function testToken() 'page', ]; - while ($token = $scanner->fetchNextToken()) { - $this->assertEquals(array_shift($expected), $token); - } + $this->expectTokensFromScanner($scanner, $expected); } - public function testDelimiter() + /** + * @dataProvider dataTestStringTokenization + */ + public function testStringTokenization() { - $scanner = new Sql2Scanner('SELECT page.* FROM [nt:unstructured] AS page'); + $scanner = new Sql2Scanner('SELECT page.* FROM [nt:unstructured] AS page WHERE name ="Hello world"'); $expected = [ - '', - ' ', - '', - '', - ' ', - ' ', - ' ', - ' ', + 'SELECT', + 'page', + '.', + '*', + 'FROM', + '[nt:unstructured]', + 'AS', + 'page', + 'WHERE', + 'name', + '=', + '"Hello world"', ]; + $this->expectTokensFromScanner($scanner, $expected); + } + + public function dataTestStringTokenization() + { + $multilineQuery = <<<'SQL' +SELECT page.* +FROM [nt:unstructured] AS page +WHERE name ="Hello world" +SQL; + + return [ + 'single line query' => ['SELECT page.* FROM [nt:unstructured] AS page WHERE name ="Hello world"'], + 'multi line query' => [$multilineQuery], + ]; + } + + public function testEscapingStrings() + { + $sql = <<expectTokensFromScanner($scanner, $expected); + } + + public function testSQLEscapedStrings() + { + $sql = "WHERE page.name = 'Hello, it''s me.'"; + + $scanner = new Sql2Scanner($sql); + $expected = [ + 'WHERE', + 'page', + '.', + 'name', + '=', + "'Hello, it''s me.'", + ]; + + $this->expectTokensFromScanner($scanner, $expected); + } + + public function testSQLEscapedStrings2() + { + $sql = "WHERE page.name = 'Hello, it''' AND"; + + $scanner = new Sql2Scanner($sql); + $expected = [ + 'WHERE', + 'page', + '.', + 'name', + '=', + "'Hello, it'''", + 'AND', + ]; + + $this->expectTokensFromScanner($scanner, $expected); + } + + public function testThrowingErrorOnUnclosedString() + { + $this->expectException(InvalidQueryException::class); + new Sql2Scanner('SELECT page.* FROM [nt:unstructured] AS page WHERE name ="Hello '); + } + + /** + * 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) + { + $actualTokens = []; while ($token = $scanner->fetchNextToken()) { - $this->assertEquals(array_shift($expected), $scanner->getPreviousDelimiter()); + $actualTokens[] = $token; } + + $this->assertEquals($expected, $actualTokens); } } From 3ec11ff445d3bce703e8c83d1de1355c7b26c3b7 Mon Sep 17 00:00:00 2001 From: mamazu Date: Tue, 30 Nov 2021 01:12:25 +0100 Subject: [PATCH 46/88] Adding the a test for combined tokens --- src/PHPCR/Util/QOM/Sql2Scanner.php | 6 ++++ .../PHPCR/Tests/Util/QOM/Sql2ScannerTest.php | 35 +++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/src/PHPCR/Util/QOM/Sql2Scanner.php b/src/PHPCR/Util/QOM/Sql2Scanner.php index 8639f22..0905146 100644 --- a/src/PHPCR/Util/QOM/Sql2Scanner.php +++ b/src/PHPCR/Util/QOM/Sql2Scanner.php @@ -188,6 +188,12 @@ protected function scan($sql2) } elseif (!$stringStartCharacter) { // If there is no start character already we have found the beginning of a new string $stringStartCharacter = $character; + + // When tokenizing `AS"abc"` add the current token (AS) as token already + if (strlen($currentToken) > 1) { + $tokens[] = substr($currentToken, 0, strlen($currentToken) - 1); + $currentToken = $character; + } } } $isEscaped = $character === '\\'; diff --git a/tests/PHPCR/Tests/Util/QOM/Sql2ScannerTest.php b/tests/PHPCR/Tests/Util/QOM/Sql2ScannerTest.php index 07da5dd..c98e017 100644 --- a/tests/PHPCR/Tests/Util/QOM/Sql2ScannerTest.php +++ b/tests/PHPCR/Tests/Util/QOM/Sql2ScannerTest.php @@ -124,6 +124,41 @@ public function testSQLEscapedStrings2() $this->expectTokensFromScanner($scanner, $expected); } + public function testSquareBrakets() + { + $sql = 'WHERE ISSAMENODE(file, ["/home node"])'; + + $scanner = new Sql2Scanner($sql); + $expected = [ + 'WHERE', + 'ISSAMENODE', + '(', + 'file', + ',', + '[', + '"/home node"', + ']', + ')', + ]; + + $this->expectTokensFromScanner($scanner, $expected); + } + + public function testTokenizingWithMissingSpaces() + { + $sql = 'SELECT * AS"all"'; + + $scanner = new Sql2Scanner($sql); + $expected = [ + 'SELECT', + '*', + 'AS', + '"all"', + ]; + + $this->expectTokensFromScanner($scanner, $expected); + } + public function testThrowingErrorOnUnclosedString() { $this->expectException(InvalidQueryException::class); From c800b7c09e4c52906a66ef20aa10314f1dd0a449 Mon Sep 17 00:00:00 2001 From: mamazu Date: Tue, 30 Nov 2021 01:31:44 +0100 Subject: [PATCH 47/88] Adding the github action badge Instead of the broken travis badge --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6dcb525..609eb5c 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # PHPCR Utilities -[![Build Status](https://secure.travis-ci.org/phpcr/phpcr-utils.png)](http://travis-ci.org/phpcr/phpcr-utils) +[![Build Status](https://github.com/phpcr/phpcr-utils/actions/workflows/test-application.yaml/badge.svg)](https://github.com/phpcr/phpcr-utils/actions) [![Latest Stable Version](https://poser.pugx.org/phpcr/phpcr-utils/version.png)](https://packagist.org/packages/phpcr/phpcr-utils) [![Total Downloads](https://poser.pugx.org/phpcr/phpcr-utils/d/total.png)](https://packagist.org/packages/phpcr/phpcr-utils) From 33154072e41d33646ab43c0c323e0a0aa98bb66a Mon Sep 17 00:00:00 2001 From: mamazu Date: Tue, 7 Dec 2021 23:58:57 +0100 Subject: [PATCH 48/88] Adding tests for unquoted strings in square brackets --- .../PHPCR/Tests/Util/QOM/Sql2ScannerTest.php | 27 ++++++++++++++++--- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/tests/PHPCR/Tests/Util/QOM/Sql2ScannerTest.php b/tests/PHPCR/Tests/Util/QOM/Sql2ScannerTest.php index c98e017..e4b489b 100644 --- a/tests/PHPCR/Tests/Util/QOM/Sql2ScannerTest.php +++ b/tests/PHPCR/Tests/Util/QOM/Sql2ScannerTest.php @@ -28,9 +28,9 @@ public function testToken() /** * @dataProvider dataTestStringTokenization */ - public function testStringTokenization() + public function testStringTokenization(string $query) { - $scanner = new Sql2Scanner('SELECT page.* FROM [nt:unstructured] AS page WHERE name ="Hello world"'); + $scanner = new Sql2Scanner($query); $expected = [ 'SELECT', 'page', @@ -49,7 +49,7 @@ public function testStringTokenization() $this->expectTokensFromScanner($scanner, $expected); } - public function dataTestStringTokenization() + public function dataTestStringTokenization(): array { $multilineQuery = <<<'SQL' SELECT page.* @@ -124,7 +124,7 @@ public function testSQLEscapedStrings2() $this->expectTokensFromScanner($scanner, $expected); } - public function testSquareBrakets() + public function testSquareBrackets() { $sql = 'WHERE ISSAMENODE(file, ["/home node"])'; @@ -144,6 +144,25 @@ public function testSquareBrakets() $this->expectTokensFromScanner($scanner, $expected); } + public function testSquareBracketsWithoutQuotes() + { + $sql = 'WHERE ISSAMENODE(file, [/home node])'; + + $scanner = new Sql2Scanner($sql); + $expected = [ + 'WHERE', + 'ISSAMENODE', + '(', + 'file', + ',', + '[/home', + 'node]', + ')', + ]; + + $this->expectTokensFromScanner($scanner, $expected); + } + public function testTokenizingWithMissingSpaces() { $sql = 'SELECT * AS"all"'; From f8b891eecaf9c79c175adcd90f3abac76a154ebd Mon Sep 17 00:00:00 2001 From: mamazu Date: Sun, 12 Dec 2021 00:55:49 +0100 Subject: [PATCH 49/88] Fixing tests for brackets --- src/PHPCR/Util/QOM/Sql2Scanner.php | 24 ++++++++++++++++++- .../PHPCR/Tests/Util/QOM/Sql2ScannerTest.php | 7 ++---- 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/src/PHPCR/Util/QOM/Sql2Scanner.php b/src/PHPCR/Util/QOM/Sql2Scanner.php index 0905146..658c3d3 100644 --- a/src/PHPCR/Util/QOM/Sql2Scanner.php +++ b/src/PHPCR/Util/QOM/Sql2Scanner.php @@ -149,7 +149,9 @@ protected function scan($sql2) $stringStartCharacter = false; $isEscaped = false; $escapedQuotesCount = 0; - foreach (\str_split($sql2) as $index => $character) { + $splitString = \str_split($sql2); + for ($index = 0; $index < count($splitString); $index++) { + $character = $splitString[$index]; if (!$stringStartCharacter && in_array($character, [' ', "\t", "\n"], true)) { if ($currentToken !== '') { $tokens[] = $currentToken; @@ -165,6 +167,19 @@ protected function scan($sql2) $currentToken = ''; continue; } + + // Handling the squared brackets in queries + if (!$isEscaped && $character === '[') { + if ($currentToken !== '') { + $tokens[] = $currentToken; + } + $stringSize = $this->parseBrackets($sql2, $index); + $tokens[] = substr($sql2, $index, $stringSize); + // We need to subtract one here because the for loop will automatically increment the index + $index += $stringSize - 1; + continue; + } + $currentToken .= $character; if (!$isEscaped && in_array($character, ['"', "'"], true)) { @@ -217,4 +232,11 @@ private function getCharacterAtIndex($string, $index) return ''; } + + private function parseBrackets(string $query, int $index): int + { + $endPosition = strpos($query, ']', $index) + 1; + + return $endPosition - $index; + } } diff --git a/tests/PHPCR/Tests/Util/QOM/Sql2ScannerTest.php b/tests/PHPCR/Tests/Util/QOM/Sql2ScannerTest.php index e4b489b..85616ac 100644 --- a/tests/PHPCR/Tests/Util/QOM/Sql2ScannerTest.php +++ b/tests/PHPCR/Tests/Util/QOM/Sql2ScannerTest.php @@ -135,9 +135,7 @@ public function testSquareBrackets() '(', 'file', ',', - '[', - '"/home node"', - ']', + '["/home node"]', ')', ]; @@ -155,8 +153,7 @@ public function testSquareBracketsWithoutQuotes() '(', 'file', ',', - '[/home', - 'node]', + '[/home node]', ')', ]; From ae813add8ac64be7a675b1cea79d9b1967d701f3 Mon Sep 17 00:00:00 2001 From: mamazu <14860264+mamazu@users.noreply.github.com> Date: Wed, 15 Dec 2021 06:05:39 +0100 Subject: [PATCH 50/88] Handling strings inside brackets --- src/PHPCR/Util/QOM/Sql2Scanner.php | 4 +++- tests/PHPCR/Tests/Util/QOM/Sql2ScannerTest.php | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/PHPCR/Util/QOM/Sql2Scanner.php b/src/PHPCR/Util/QOM/Sql2Scanner.php index 658c3d3..f099480 100644 --- a/src/PHPCR/Util/QOM/Sql2Scanner.php +++ b/src/PHPCR/Util/QOM/Sql2Scanner.php @@ -174,7 +174,9 @@ protected function scan($sql2) $tokens[] = $currentToken; } $stringSize = $this->parseBrackets($sql2, $index); - $tokens[] = substr($sql2, $index, $stringSize); + $bracketContent = substr($sql2, $index + 1, $stringSize - 2); + $tokens[] = '[' . trim($bracketContent, '"') . ']'; + // We need to subtract one here because the for loop will automatically increment the index $index += $stringSize - 1; continue; diff --git a/tests/PHPCR/Tests/Util/QOM/Sql2ScannerTest.php b/tests/PHPCR/Tests/Util/QOM/Sql2ScannerTest.php index 85616ac..4fca591 100644 --- a/tests/PHPCR/Tests/Util/QOM/Sql2ScannerTest.php +++ b/tests/PHPCR/Tests/Util/QOM/Sql2ScannerTest.php @@ -135,7 +135,7 @@ public function testSquareBrackets() '(', 'file', ',', - '["/home node"]', + '[/home node]', ')', ]; From f5b28b6499c42a7b8ed317b27bb3be0cefa55aba Mon Sep 17 00:00:00 2001 From: mamazu <14860264+mamazu@users.noreply.github.com> Date: Wed, 15 Dec 2021 06:24:41 +0100 Subject: [PATCH 51/88] Simplifying the next character logic --- src/PHPCR/Util/QOM/Sql2Scanner.php | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/src/PHPCR/Util/QOM/Sql2Scanner.php b/src/PHPCR/Util/QOM/Sql2Scanner.php index f099480..1666311 100644 --- a/src/PHPCR/Util/QOM/Sql2Scanner.php +++ b/src/PHPCR/Util/QOM/Sql2Scanner.php @@ -175,7 +175,7 @@ protected function scan($sql2) } $stringSize = $this->parseBrackets($sql2, $index); $bracketContent = substr($sql2, $index + 1, $stringSize - 2); - $tokens[] = '[' . trim($bracketContent, '"') . ']'; + $tokens[] = '['.trim($bracketContent, '"').']'; // We need to subtract one here because the for loop will automatically increment the index $index += $stringSize - 1; @@ -187,7 +187,7 @@ protected function scan($sql2) if (!$isEscaped && in_array($character, ['"', "'"], true)) { // 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 = $this->getCharacterAtIndex($sql2, $index + 1); + $nextCharacter = $splitString[$index + 1] ?? ''; if ($character === "'" && $nextCharacter === "'") { $isEscaped = true; $escapedQuotesCount++; @@ -226,15 +226,6 @@ protected function scan($sql2) return $tokens; } - private function getCharacterAtIndex($string, $index) - { - if ($index < strlen($string)) { - return $string[$index]; - } - - return ''; - } - private function parseBrackets(string $query, int $index): int { $endPosition = strpos($query, ']', $index) + 1; From 0a802203b0fda20421c2b8fcfc0d2ec45e2152e6 Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Wed, 15 Dec 2021 07:43:08 +0100 Subject: [PATCH 52/88] prepare release --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 82ac683..cc5c055 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,11 @@ Changelog ========= +1.6.0 +----- + +* Refactored SQL2 parsing to be more efficient. + 1.5.3 ----- From 5d6525110d3213048b04fae28e55ad1778e78379 Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Wed, 15 Dec 2021 10:18:16 +0100 Subject: [PATCH 53/88] fix branch alias --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 3c26226..fda2633 100644 --- a/composer.json +++ b/composer.json @@ -49,7 +49,7 @@ "bin": ["bin/phpcr"], "extra": { "branch-alias": { - "dev-master": "1.4-dev" + "dev-master": "1.x-dev" } } } From 88629e2508bd8cf9e1409c50c344f0a9ce13bcb9 Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Wed, 15 Dec 2021 10:16:06 +0100 Subject: [PATCH 54/88] names and paths can contain spaces --- tests/PHPCR/Tests/Util/ValueConverterTest.php | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/tests/PHPCR/Tests/Util/ValueConverterTest.php b/tests/PHPCR/Tests/Util/ValueConverterTest.php index e57bc46..f14e55b 100644 --- a/tests/PHPCR/Tests/Util/ValueConverterTest.php +++ b/tests/PHPCR/Tests/Util/ValueConverterTest.php @@ -74,10 +74,10 @@ public function dataConversionMatrix() ['test string', PropertyType::STRING, true, PropertyType::BOOLEAN], ['false', PropertyType::STRING, true, PropertyType::BOOLEAN], ['', PropertyType::STRING, false, PropertyType::BOOLEAN], - // TODO: check NAME may not have spaces ['test string', PropertyType::STRING, null, PropertyType::NAME], ['test', PropertyType::STRING, 'test', PropertyType::NAME], - // TODO: check PATH may not have spaces ['test string', PropertyType::STRING, null, PropertyType::PATH], + ['test space', PropertyType::STRING, 'test space', PropertyType::NAME], ['../the/node', PropertyType::STRING, '../the/node', PropertyType::PATH], + ['../the space/node', PropertyType::STRING, '../the space/node', PropertyType::PATH], ['38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::STRING, '38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::REFERENCE], // TODO: should we move UUIDHelper to phpcr so we can check in PropertyType? ['test string', PropertyType::STRING, null, PropertyType::REFERENCE], ['', PropertyType::STRING, null, PropertyType::REFERENCE], @@ -93,9 +93,7 @@ public function dataConversionMatrix() [$stream, PropertyType::BINARY, null, PropertyType::DATE], [$dateStream, PropertyType::BINARY, new DateTime('17.12.2010 GMT'), PropertyType::DATE], [$stream, PropertyType::BINARY, true, PropertyType::BOOLEAN], - // TODO: check NAME may not have spaces [$stream, PropertyType::BINARY, null, PropertyType::NAME], [$nameStream, PropertyType::BINARY, 'test', PropertyType::NAME], - // TODO: check PATH may not have spaces [$stream, PropertyType::BINARY, null, PropertyType::PATH], // TODO: should we move UUIDHelper to phpcr so we can check in PropertyType? [$stream, PropertyType::STRING, null, PropertyType::REFERENCE], [$uuidStream, PropertyType::BINARY, '38b7cf18-c417-477a-af0b-c1e92a290c9a', PropertyType::REFERENCE], [$stream, PropertyType::BINARY, 'test string', PropertyType::DECIMAL], // up to the decimal functions to validate From edb1707e2041bda965ee215ea449b50b9c64874b Mon Sep 17 00:00:00 2001 From: Alexander Schranz Date: Wed, 15 Dec 2021 12:21:49 +0100 Subject: [PATCH 55/88] Add CI for windows tests --- .github/workflows/test-application.yaml | 34 +++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/.github/workflows/test-application.yaml b/.github/workflows/test-application.yaml index e8dde85..fb64166 100644 --- a/.github/workflows/test-application.yaml +++ b/.github/workflows/test-application.yaml @@ -50,3 +50,37 @@ jobs: - name: Execute test cases run: vendor/bin/phpunit + + + php-windows: + name: "PHP Windows ${{ matrix.php-version }} ${{ matrix.dependencies }} ${{ matrix.dev-dependencies && 'dev' }}" + runs-on: windows-latest + + strategy: + fail-fast: false + matrix: + include: + - php-version: '7.4' + + steps: + - name: Checkout project + uses: actions/checkout@v2 + + - name: Install and configure PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php-version }} + tools: 'composer:v2' + + - name: Allow unstable dependencies + if: matrix.dev-dependencies == true + run: composer config minimum-stability dev + + - name: Install dependencies with Composer + uses: ramsey/composer-install@v1 + with: + dependency-versions: ${{ matrix.dependencies }} + composer-options: --prefer-dist + + - name: Execute test cases + run: vendor/bin/phpunit From 67456bc73d37b9c0b0b934b44358b3ea52426aaf Mon Sep 17 00:00:00 2001 From: Alexander Schranz Date: Wed, 15 Dec 2021 13:20:08 +0100 Subject: [PATCH 56/88] Try to fix SqlScanner on windows for multiline select statements --- src/PHPCR/Util/QOM/Sql2Scanner.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/PHPCR/Util/QOM/Sql2Scanner.php b/src/PHPCR/Util/QOM/Sql2Scanner.php index 1666311..a4c4107 100644 --- a/src/PHPCR/Util/QOM/Sql2Scanner.php +++ b/src/PHPCR/Util/QOM/Sql2Scanner.php @@ -152,7 +152,7 @@ protected function scan($sql2) $splitString = \str_split($sql2); for ($index = 0; $index < count($splitString); $index++) { $character = $splitString[$index]; - if (!$stringStartCharacter && in_array($character, [' ', "\t", "\n"], true)) { + if (!$stringStartCharacter && in_array($character, [' ', "\t", "\n", "\r"], true)) { if ($currentToken !== '') { $tokens[] = $currentToken; } From 6ce7d0f850aa85efe801b90064da8db6341d6832 Mon Sep 17 00:00:00 2001 From: Alexander Schranz Date: Wed, 15 Dec 2021 13:20:25 +0100 Subject: [PATCH 57/88] Update test-application.yaml --- .github/workflows/test-application.yaml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/test-application.yaml b/.github/workflows/test-application.yaml index fb64166..abc922e 100644 --- a/.github/workflows/test-application.yaml +++ b/.github/workflows/test-application.yaml @@ -51,7 +51,6 @@ jobs: - name: Execute test cases run: vendor/bin/phpunit - php-windows: name: "PHP Windows ${{ matrix.php-version }} ${{ matrix.dependencies }} ${{ matrix.dev-dependencies && 'dev' }}" runs-on: windows-latest From b966bcb415849987dfe8fc129aeabe5340beab4d Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Thu, 16 Dec 2021 08:30:13 +0100 Subject: [PATCH 58/88] some minor cleanups in query converter --- src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php b/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php index a859ebd..40a336b 100644 --- a/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php +++ b/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php @@ -5,7 +5,6 @@ use DateTime; use Exception; use InvalidArgumentException; -use Jackalope\Query\QOM\Selector; use LogicException; use PHPCR\PropertyType; use PHPCR\Query\InvalidQueryException; @@ -21,7 +20,6 @@ use PHPCR\Query\QOM\JoinInterface; use PHPCR\Query\QOM\NotInterface; use PHPCR\Query\QOM\OrderingInterface; -use PHPCR\Query\QOM\PropertyExistenceInterface; use PHPCR\Query\QOM\PropertyValueInterface; use PHPCR\Query\QOM\QueryObjectModelConstantsInterface as Constants; use PHPCR\Query\QOM\QueryObjectModelFactoryInterface; @@ -133,9 +131,7 @@ public function parse($sql2) $columns = $this->buildColumns($columnData); - $query = $this->factory->createQuery($source, $constraint, $orderings, $columns); - - return $query; + return $this->factory->createQuery($source, $constraint, $orderings, $columns); } /** @@ -161,7 +157,7 @@ protected function parseSource() /** * 6.7.3. Selector - * Parse an SQL2 selector and return a QOM\Selector. + * Parse an SQL2 selector and return a QOM\SelectorInterface. * * @return SelectorInterface */ @@ -519,7 +515,7 @@ protected function parseOperator() /** * 6.7.18 PropertyExistence. * - * @return PropertyExistenceInterface + * @return ConstraintInterface */ protected function parsePropertyExistence() { From e69003631c7b8800eee607c644861c7eebe62880 Mon Sep 17 00:00:00 2001 From: Alexander Schranz Date: Fri, 17 Dec 2021 11:00:28 +0100 Subject: [PATCH 59/88] Update .github/workflows/test-application.yaml --- .github/workflows/test-application.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/test-application.yaml b/.github/workflows/test-application.yaml index abc922e..5c82c00 100644 --- a/.github/workflows/test-application.yaml +++ b/.github/workflows/test-application.yaml @@ -59,7 +59,7 @@ jobs: fail-fast: false matrix: include: - - php-version: '7.4' + - php-version: '8.1' steps: - name: Checkout project From 6b5db3321d6f9e7ceaf3880131a089e8e2505cfc Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Mon, 20 Dec 2021 08:52:52 +0100 Subject: [PATCH 60/88] prepare release --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index cc5c055..5f7ae32 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,11 @@ Changelog ========= +1.6.1 +----- + +* Fixed handling of windows style newlines in SQL2 parsing. + 1.6.0 ----- From 13ec1271f30b71fa0e186518ba604b759efd008a Mon Sep 17 00:00:00 2001 From: Alexander Schranz Date: Fri, 29 Apr 2022 14:20:09 +0200 Subject: [PATCH 61/88] Fix some php 8.1 issues --- src/PHPCR/Util/CND/Scanner/TokenQueue.php | 1 + src/PHPCR/Util/NodeHelper.php | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/PHPCR/Util/CND/Scanner/TokenQueue.php b/src/PHPCR/Util/CND/Scanner/TokenQueue.php index 188f72e..d1424d1 100644 --- a/src/PHPCR/Util/CND/Scanner/TokenQueue.php +++ b/src/PHPCR/Util/CND/Scanner/TokenQueue.php @@ -65,6 +65,7 @@ public function next() return next($this->tokens); } + #[\ReturnTypeWillChange] public function getIterator() { return new \ArrayIterator($this->tokens); diff --git a/src/PHPCR/Util/NodeHelper.php b/src/PHPCR/Util/NodeHelper.php index 95d7459..7997c25 100644 --- a/src/PHPCR/Util/NodeHelper.php +++ b/src/PHPCR/Util/NodeHelper.php @@ -53,7 +53,7 @@ public static function createPath(SessionInterface $session, $path) { $current = $session->getRootNode(); - $segments = preg_split('#/#', $path, null, PREG_SPLIT_NO_EMPTY); + $segments = preg_split('#/#', $path, -1, PREG_SPLIT_NO_EMPTY); foreach ($segments as $segment) { if ($current->hasNode($segment)) { $current = $current->getNode($segment); From f9b18c15a574f0582ce22eea0884839aa957cd46 Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Mon, 2 May 2022 14:11:50 +0200 Subject: [PATCH 62/88] prepare release --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f7ae32..2beaef0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,11 @@ Changelog ========= +1.6.2 +----- + +* Fix deprecations of PHP 8.1 + 1.6.1 ----- From f378a6a32cbd08613b389b24ba7e91a5f58b07af Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Sun, 20 Nov 2022 11:37:04 +0100 Subject: [PATCH 63/88] fix php 8.1 warnings --- src/PHPCR/Util/ValueConverter.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/PHPCR/Util/ValueConverter.php b/src/PHPCR/Util/ValueConverter.php index 904e6bf..343a93d 100644 --- a/src/PHPCR/Util/ValueConverter.php +++ b/src/PHPCR/Util/ValueConverter.php @@ -246,13 +246,13 @@ public function convertType($value, $type, $srcType = PropertyType::UNDEFINED) try { return new DateTime($value); } catch (Exception $e) { - throw new ValueFormatException("String '$value' is not a valid date", null, $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 = $datetime->setTimestamp($value); + $datetime = $datetime->setTimestamp(round($value)); return $datetime; } From 71d5083766b49bcb08c2d9d9fce790f36ac0935c Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Sun, 20 Nov 2022 11:40:46 +0100 Subject: [PATCH 64/88] prepare release --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2beaef0..ddf5ee6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,11 @@ Changelog ========= +1.6.3 +----- + +* Fix more deprecations with PHP 8.1. Round floats when using them as a timestamp, rather than the implicit conversion that floored them. + 1.6.2 ----- From 54fb032ff64b11e478096831bb5575d618f25ec5 Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Fri, 17 Feb 2023 02:02:42 +0100 Subject: [PATCH 65/88] validate with phpstan --- .gitattributes | 9 ++ .github/workflows/static.yml | 42 +++++++++ .github/workflows/test-application.yaml | 4 +- composer.json | 5 +- phpstan.neon.dist | 9 ++ phpstan.tests.neon.dist | 4 + src/PHPCR/Util/CND/Parser/CndParser.php | 5 - src/PHPCR/Util/CND/Reader/FileReader.php | 2 +- src/PHPCR/Util/CND/Writer/CndWriter.php | 16 ++-- .../Util/Console/Command/BaseCommand.php | 32 +++++-- .../Console/Command/NodeRemoveCommand.php | 2 +- .../Console/Command/NodesUpdateCommand.php | 4 +- src/PHPCR/Util/Console/Helper/PhpcrHelper.php | 2 +- .../TreeDumper/ConsoleDumperNodeVisitor.php | 2 +- .../ConsoleDumperPropertyVisitor.php | 5 + src/PHPCR/Util/NodeHelper.php | 4 +- .../Util/QOM/BaseQomToSqlQueryConverter.php | 2 - src/PHPCR/Util/QOM/BaseSqlGenerator.php | 91 +++++++++++++++++-- .../Util/QOM/QomToSql2QueryConverter.php | 74 +++++++++++---- src/PHPCR/Util/QOM/Sql1Generator.php | 8 +- src/PHPCR/Util/QOM/Sql2Generator.php | 23 ++--- .../Util/QOM/Sql2ToQomQueryConverter.php | 5 + src/PHPCR/Util/TraversingItemVisitor.php | 10 +- src/PHPCR/Util/TreeWalker.php | 14 ++- .../Tests/Util/CND/Reader/FileReaderTest.php | 5 + .../Util/CND/Scanner/GenericScannerTest.php | 6 +- .../Tests/Util/QOM/BaseSqlGeneratorTest.php | 6 ++ 27 files changed, 307 insertions(+), 84 deletions(-) create mode 100644 .gitattributes create mode 100644 .github/workflows/static.yml create mode 100644 phpstan.neon.dist create mode 100644 phpstan.tests.neon.dist diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..050d624 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,9 @@ +.gitattributes export-ignore +/.github/ export-ignore +.gitignore export-ignore +/.php_cs.dist export-ignore +/phpstan.neon.dist export-ignore +/phpstan.tests.neon.dist export-ignore +/phpunit.xml.dist export-ignore +/stubs/ export-ignore +/tests/ export-ignore diff --git a/.github/workflows/static.yml b/.github/workflows/static.yml new file mode 100644 index 0000000..b1403f2 --- /dev/null +++ b/.github/workflows/static.yml @@ -0,0 +1,42 @@ +name: Static analysis + +on: + push: + branches: + - '[0-9]+.x' + - '[0-9]+.[0-9]+' + - '[0-9]+.[0-9]+.x' + pull_request: + +jobs: + phpstan-src: + name: PHPStan src + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v2 + + - name: PHPStan + uses: docker://oskarstark/phpstan-ga + with: + args: analyze --no-progress + + phpstan-tests: + name: PHPStan tests + runs-on: ubuntu-latest + env: + REQUIRE_DEV: "true" + + steps: + - name: Checkout code + uses: actions/checkout@v2 + + - name: Install dependencies + run: | + composer update --no-progress + + - name: PHPStan + uses: docker://oskarstark/phpstan-ga + with: + args: analyze --no-progress -c phpstan.tests.neon.dist diff --git a/.github/workflows/test-application.yaml b/.github/workflows/test-application.yaml index 5c82c00..760386b 100644 --- a/.github/workflows/test-application.yaml +++ b/.github/workflows/test-application.yaml @@ -18,15 +18,15 @@ jobs: fail-fast: false matrix: include: - - php-version: '7.1' - dependencies: 'lowest' - php-version: '7.2' + dependencies: 'lowest' - 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' steps: - name: Checkout project diff --git a/composer.json b/composer.json index fda2633..3364e45 100644 --- a/composer.json +++ b/composer.json @@ -27,13 +27,14 @@ } ], "require": { - "php": "^7.1 || ^8.0", + "php": "^7.2 || ^8.0", "phpcr/phpcr": "~2.1.0", "symfony/console": "^2.3 || ^3.0 || ^4.0 || ^5.0 || ^6.0" }, "require-dev": { "ramsey/uuid": "^3.5", - "phpunit/phpunit": "^7.5 || ^8.0 || ^9.0" + "phpunit/phpunit": "^7.5 || ^8.0 || ^9.0", + "phpstan/phpstan": "^1.9" }, "suggest": { "ramsey/uuid": "A library for generating RFC 4122 version 1, 3, 4, and 5 universally unique identifiers (UUID)." diff --git a/phpstan.neon.dist b/phpstan.neon.dist new file mode 100644 index 0000000..bc5b3ef --- /dev/null +++ b/phpstan.neon.dist @@ -0,0 +1,9 @@ +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/phpstan.tests.neon.dist b/phpstan.tests.neon.dist new file mode 100644 index 0000000..0efe94d --- /dev/null +++ b/phpstan.tests.neon.dist @@ -0,0 +1,4 @@ +parameters: + level: 1 + paths: + - tests diff --git a/src/PHPCR/Util/CND/Parser/CndParser.php b/src/PHPCR/Util/CND/Parser/CndParser.php index 0a18429..dab5dc9 100644 --- a/src/PHPCR/Util/CND/Parser/CndParser.php +++ b/src/PHPCR/Util/CND/Parser/CndParser.php @@ -733,11 +733,6 @@ protected function parseQueryOpsAttribute() $ops[] = $op; } while ($op && $this->checkAndExpectToken(Token::TK_SYMBOL, ',')); - if (empty($ops)) { - // There must be at least an operator if this attribute is not variant - throw new ParserException($this->tokenQueue, 'Operator expected'); - } - return $ops; } diff --git a/src/PHPCR/Util/CND/Reader/FileReader.php b/src/PHPCR/Util/CND/Reader/FileReader.php index 2115b5f..353594d 100644 --- a/src/PHPCR/Util/CND/Reader/FileReader.php +++ b/src/PHPCR/Util/CND/Reader/FileReader.php @@ -13,7 +13,7 @@ class FileReader extends BufferReader /** * @var string */ - protected $filePath; + protected $path; /** * @param string $path diff --git a/src/PHPCR/Util/CND/Writer/CndWriter.php b/src/PHPCR/Util/CND/Writer/CndWriter.php index 4df28c7..2ab7538 100644 --- a/src/PHPCR/Util/CND/Writer/CndWriter.php +++ b/src/PHPCR/Util/CND/Writer/CndWriter.php @@ -5,7 +5,6 @@ use PHPCR\NamespaceRegistryInterface; use PHPCR\NodeType\NodeDefinitionInterface; use PHPCR\NodeType\NodeTypeDefinitionInterface; -use PHPCR\NodeType\NodeTypeManagerInterface; use PHPCR\NodeType\NodeTypeTemplateInterface; use PHPCR\NodeType\PropertyDefinitionInterface; use PHPCR\PropertyType; @@ -34,9 +33,6 @@ class CndWriter /** @var array hashmap of prefix => namespace uri */ private $namespaces = []; - /** - * @param NodeTypeManagerInterface $ntm - */ public function __construct(NamespaceRegistryInterface $ns) { $this->ns = $ns; @@ -135,6 +131,11 @@ protected function writeNodeType(NodeTypeDefinitionInterface $nodeType) return $s; } + /** + * @param PropertyDefinitionInterface[] $properties + * + * @return string + */ private function writeProperties($properties) { if (null === $properties) { @@ -145,7 +146,6 @@ private function writeProperties($properties) $s = ''; - /** @var $property PropertyDefinitionInterface */ foreach ($properties as $property) { $this->checkNamespace($property->getName()); $s .= '- '.$property->getName(); @@ -196,6 +196,11 @@ private function writeProperties($properties) return $s; } + /** + * @param NodeDefinitionInterface[] $children + * + * @return string + */ private function writeChildren($children) { if (null === $children) { @@ -206,7 +211,6 @@ private function writeChildren($children) $s = ''; - /** @var $child NodeDefinitionInterface */ foreach ($children as $child) { $this->checkNamespace($child->getName()); $s .= '+ '.$child->getName(); diff --git a/src/PHPCR/Util/Console/Command/BaseCommand.php b/src/PHPCR/Util/Console/Command/BaseCommand.php index eb6d82b..5fdd56e 100644 --- a/src/PHPCR/Util/Console/Command/BaseCommand.php +++ b/src/PHPCR/Util/Console/Command/BaseCommand.php @@ -6,6 +6,8 @@ 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; @@ -51,20 +53,20 @@ protected function getPhpcrConsoleDumperHelper() * * @param InputInterface $input * @param OutputInterface $output - * @param string $question + * @param string $questionText * @param string $default * * @return string */ - protected function ask(InputInterface $input, OutputInterface $output, $question, $default = null) + protected function ask(InputInterface $input, OutputInterface $output, $questionText, $default = null) { if ($this->getHelperSet()->has('question')) { - $question = new Question($question, $default); + $question = new Question($questionText, $default); - return $this->getHelper('question')->ask($input, $output, $question); + return $this->getQuestionHelper()->ask($input, $output, $question); } - return $this->getHelper('dialog')->ask($output, $question, $default); + return $this->getDialogHelper()->ask($output, $questionText, $default); } /** @@ -72,19 +74,29 @@ protected function ask(InputInterface $input, OutputInterface $output, $question * * @param InputInterface $input * @param OutputInterface $output - * @param string $question + * @param string $questionText * @param bool $default * * @return string */ - protected function askConfirmation(InputInterface $input, OutputInterface $output, $question, $default = true) + protected function askConfirmation(InputInterface $input, OutputInterface $output, $questionText, $default = true) { if ($this->getHelperSet()->has('question')) { - $question = new ConfirmationQuestion($question, $default); + $question = new ConfirmationQuestion($questionText, $default); - return $this->getHelper('question')->ask($input, $output, $question); + return $this->getQuestionHelper()->ask($input, $output, $question); } - return $this->getHelper('dialog')->askConfirmation($output, $question, $default); + return $this->getDialogHelper()->askConfirmation($output, $questionText, $default); + } + + private 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 f9a3127..280fb5a 100644 --- a/src/PHPCR/Util/Console/Command/NodeRemoveCommand.php +++ b/src/PHPCR/Util/Console/Command/NodeRemoveCommand.php @@ -107,7 +107,7 @@ protected function execute(InputInterface $input, OutputInterface $output) if ($onlyChildren) { $baseNode = $session->getNode($path, 0); - /** @var $childNode NodeInterface */ + /** @var NodeInterface $childNode */ foreach ($baseNode->getNodes() as $childNode) { $childNodePath = $childNode->getPath(); $childNode->remove(); diff --git a/src/PHPCR/Util/Console/Command/NodesUpdateCommand.php b/src/PHPCR/Util/Console/Command/NodesUpdateCommand.php index 6b13eb2..50aa22d 100644 --- a/src/PHPCR/Util/Console/Command/NodesUpdateCommand.php +++ b/src/PHPCR/Util/Console/Command/NodesUpdateCommand.php @@ -125,7 +125,7 @@ protected function execute(InputInterface $input, OutputInterface $output) $persistIn = $persistCounter; - /** @var $row RowInterface */ + /** @var RowInterface $row */ foreach ($result as $i => $row) { $output->writeln(sprintf( 'Updating node: [%d] %s.', @@ -169,7 +169,7 @@ private function shouldExecute(InputInterface $input, OutputInterface $output, Q ))); if ($response === 'L') { - /** @var $row RowInterface */ + /** @var RowInterface $row */ foreach ($result as $i => $row) { $output->writeln(sprintf(' - [%d] %s', $i, $row->getPath())); } diff --git a/src/PHPCR/Util/Console/Helper/PhpcrHelper.php b/src/PHPCR/Util/Console/Helper/PhpcrHelper.php index 8c0d7ce..edb6edc 100644 --- a/src/PHPCR/Util/Console/Helper/PhpcrHelper.php +++ b/src/PHPCR/Util/Console/Helper/PhpcrHelper.php @@ -129,7 +129,7 @@ public function processNode(OutputInterface $output, NodeInterface $node, array if ($operations['dump']) { $output->writeln('Node dump: '); - /** @var $property PropertyInterface */ + /** @var PropertyInterface $property */ foreach ($node->getProperties() as $property) { $value = $property->getValue(); if (!is_string($value)) { diff --git a/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperNodeVisitor.php b/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperNodeVisitor.php index f6f710d..c64438b 100644 --- a/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperNodeVisitor.php +++ b/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperNodeVisitor.php @@ -58,7 +58,7 @@ public function setShowFullPath($showFullPath) public function visit(ItemInterface $item) { if (!$item instanceof NodeInterface) { - throw new Exception("Internal error: did not expect to visit a non-node object: $item"); + throw new Exception('Internal error: did not expect to visit a non-node object: '.get_class($item)); } if ($item->getDepth() === 0) { diff --git a/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperPropertyVisitor.php b/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperPropertyVisitor.php index 3cc4466..63ccbc7 100644 --- a/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperPropertyVisitor.php +++ b/src/PHPCR/Util/Console/Helper/TreeDumper/ConsoleDumperPropertyVisitor.php @@ -27,6 +27,11 @@ class ConsoleDumperPropertyVisitor extends ConsoleDumperItemVisitor */ protected $expandReferences; + /** + * @var string + */ + private $refFormat; + /** * Instantiate property visitor. * diff --git a/src/PHPCR/Util/NodeHelper.php b/src/PHPCR/Util/NodeHelper.php index 7997c25..fada226 100644 --- a/src/PHPCR/Util/NodeHelper.php +++ b/src/PHPCR/Util/NodeHelper.php @@ -86,14 +86,14 @@ public static function purgeWorkspace(SessionInterface $session) { $root = $session->getRootNode(); - /** @var $property PropertyInterface */ + /** @var PropertyInterface $property */ foreach ($root->getProperties() as $property) { if (!self::isSystemItem($property)) { $property->remove(); } } - /** @var $node NodeInterface */ + /** @var NodeInterface $node */ foreach ($root->getNodes() as $node) { if (!self::isSystemItem($node)) { $node->remove(); diff --git a/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php b/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php index c2a1ac2..9cab6b0 100644 --- a/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php +++ b/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php @@ -248,7 +248,6 @@ protected function convertPropertyValue(QOM\PropertyValueInterface $value) protected function convertOrderings(array $orderings) { $list = []; - /** @var $ordering QOM\OrderingInterface */ foreach ($orderings as $ordering) { $order = $this->generator->evalOrder($ordering->getOrder()); $operand = $this->convertDynamicOperand($ordering->getOperand()); @@ -314,7 +313,6 @@ protected function convertColumns(array $columns) { $list = []; - /** @var $column QOM\ColumnInterface */ foreach ($columns as $column) { $selector = $column->getSelectorName(); $property = $column->getPropertyName(); diff --git a/src/PHPCR/Util/QOM/BaseSqlGenerator.php b/src/PHPCR/Util/QOM/BaseSqlGenerator.php index 027318e..e023fbd 100644 --- a/src/PHPCR/Util/QOM/BaseSqlGenerator.php +++ b/src/PHPCR/Util/QOM/BaseSqlGenerator.php @@ -40,17 +40,17 @@ public function __construct(ValueConverter $valueConverter) */ public function evalQuery($source, $columns, $constraint = '', $orderings = '') { - $sql1 = "SELECT $columns FROM $source"; + $sql = "SELECT $columns FROM $source"; if ($constraint) { - $sql1 .= " WHERE $constraint"; + $sql .= " WHERE $constraint"; } if ($orderings) { - $sql1 .= " ORDER BY $orderings"; + $sql .= " ORDER BY $orderings"; } - return $sql1; + return $sql; } /** @@ -169,17 +169,17 @@ public function evalUpper($operand) */ public function evalOrderings($orderings) { - $sql2 = ''; + $sql = ''; foreach ($orderings as $ordering) { - if ($sql2 !== '') { - $sql2 .= ', '; + if ($sql !== '') { + $sql .= ', '; } - $sql2 .= $ordering; + $sql .= $ordering; } - return $sql2; + return $sql; } /** @@ -292,12 +292,83 @@ public function evalLiteral($literal) */ abstract public function evalCastLiteral($literal, $type); + /** + * @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); + /** * Evaluate a path. This is different between SQL1 and SQL2. * * @param string $path * - * @return string + * @return string|null */ abstract public function evalPath($path); + + /** + * columns ::= (Column ',' {Column}) | '*'. + * + * With empty columns, SQL1 is different from SQL2 + * + * @param $columns + * + * @return string + */ + abstract public function evalColumns($columns); + + /** + * @param string $selectorName + * @param string $propertyName + * @param string $colname + * + * @return string + */ + abstract public function evalColumn($selectorName, $propertyName = null, $colname = null); + + /** + * @param $selectorName + * @param $propertyName + * + * @return string + */ + abstract public function evalPropertyExistence($selectorName, $propertyName); + + /** + * @param string $propertyName + * @param string $selectorName + * + * @return string + */ + abstract public function evalPropertyValue($propertyName, $selectorName = null); + + /** + * @param string $path + * @param string $selectorName + * + * @return string + */ + abstract public function evalChildNode($path, $selectorName = null); + + /** + * @param string $path + * @param string $selectorName + * + * @return string + */ + abstract public function evalDescendantNode($path, $selectorName = null); + + /** + * @param string $selectorName + * @param string $searchExpression + * @param string $propertyName + * + * @return string + */ + abstract public function evalFullTextSearch($selectorName, $searchExpression, $propertyName = null); } diff --git a/src/PHPCR/Util/QOM/QomToSql2QueryConverter.php b/src/PHPCR/Util/QOM/QomToSql2QueryConverter.php index 7c92ed6..fdef9c0 100644 --- a/src/PHPCR/Util/QOM/QomToSql2QueryConverter.php +++ b/src/PHPCR/Util/QOM/QomToSql2QueryConverter.php @@ -51,6 +51,10 @@ protected function convertSource(QOM\SourceInterface $source) */ protected function convertJoin(QOM\JoinInterface $join) { + if (!$this->generator instanceof Sql2Generator) { + throw new NotSupportedOperandException('Only SQL2 supports join'); + } + $left = $this->convertSource($join->getLeft()); $right = $this->convertSource($join->getRight()); $condition = $this->convertJoinCondition($join->getJoinCondition()); @@ -73,19 +77,20 @@ protected function convertJoin(QOM\JoinInterface $join) protected function convertJoinCondition(QOM\JoinConditionInterface $condition) { if ($condition instanceof QOM\EquiJoinConditionInterface) { - $sql2 = $this->convertEquiJoinCondition($condition); - } elseif ($condition instanceof QOM\SameNodeJoinConditionInterface) { - $sql2 = $this->convertSameNodeJoinCondition($condition); - } elseif ($condition instanceof QOM\ChildNodeJoinConditionInterface) { - $sql2 = $this->convertChildNodeJoinCondition($condition); - } elseif ($condition instanceof QOM\DescendantNodeJoinConditionInterface) { - $sql2 = $this->convertDescendantNodeJoinCondition($condition); - } else { - // This should not happen, but who knows... - throw new InvalidArgumentException('Invalid operand'); + return $this->convertEquiJoinCondition($condition); + } + if ($condition instanceof QOM\SameNodeJoinConditionInterface) { + return $this->convertSameNodeJoinCondition($condition); + } + if ($condition instanceof QOM\ChildNodeJoinConditionInterface) { + return $this->convertChildNodeJoinCondition($condition); + } + if ($condition instanceof QOM\DescendantNodeJoinConditionInterface) { + return $this->convertDescendantNodeJoinCondition($condition); } - return $sql2; + // This should not happen, but who knows... + throw new InvalidArgumentException('Invalid operand'); } /** @@ -102,6 +107,10 @@ protected function convertJoinCondition(QOM\JoinConditionInterface $condition) */ protected function convertEquiJoinCondition(QOM\EquiJoinConditionInterface $condition) { + if (!$this->generator instanceof Sql2Generator) { + throw new NotSupportedOperandException('Only SQL2 supports equi join condition'); + } + return $this->generator->evalEquiJoinCondition( $condition->getSelector1Name(), $condition->getProperty1Name(), @@ -123,6 +132,10 @@ protected function convertEquiJoinCondition(QOM\EquiJoinConditionInterface $cond */ protected function convertSameNodeJoinCondition(QOM\SameNodeJoinConditionInterface $condition) { + if (!$this->generator instanceof Sql2Generator) { + throw new NotSupportedOperandException('Only SQL2 supports same node join condition'); + } + return $this->generator->evalSameNodeJoinCondition( $condition->getSelector1Name(), $condition->getSelector2Name(), @@ -143,6 +156,10 @@ protected function convertSameNodeJoinCondition(QOM\SameNodeJoinConditionInterfa */ protected function convertChildNodeJoinCondition(QOM\ChildNodeJoinConditionInterface $condition) { + if (!$this->generator instanceof Sql2Generator) { + throw new NotSupportedOperandException('Only SQL2 supports child node join condition'); + } + return $this->generator->evalChildNodeJoinCondition( $condition->getChildSelectorName(), $condition->getParentSelectorName() @@ -162,6 +179,10 @@ protected function convertChildNodeJoinCondition(QOM\ChildNodeJoinConditionInter */ protected function convertDescendantNodeJoinCondition(QOM\DescendantNodeJoinConditionInterface $condition) { + if (!$this->generator instanceof Sql2Generator) { + throw new NotSupportedOperandException('Only SQL2 supports descendant node join condition'); + } + return $this->generator->evalDescendantNodeJoinCondition( $condition->getDescendantSelectorName(), $condition->getAncestorSelectorName() @@ -221,11 +242,16 @@ 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) { + if (!$this->generator instanceof Sql2Generator) { + throw new NotSupportedConstraintException('Only SQL2 supports same node constraint'); + } + return $this->generator->evalSameNode( $this->convertPath($constraint->getPath()), $constraint->getSelectorName() @@ -275,31 +301,47 @@ protected function convertDynamicOperand(QOM\DynamicOperandInterface $operand) } if ($operand instanceof QOM\LengthInterface) { + if (!$this->generator instanceof Sql2Generator) { + throw new NotSupportedOperandException('Only SQL2 supports length operand'); + } + return $this->generator->evalLength($this->convertPropertyValue($operand->getPropertyValue())); } if ($operand instanceof QOM\NodeNameInterface) { + if (!$this->generator instanceof Sql2Generator) { + throw new NotSupportedOperandException('Only SQL2 supports node operand'); + } + return $this->generator->evalNodeName($operand->getSelectorName()); } if ($operand instanceof QOM\NodeLocalNameInterface) { + if (!$this->generator instanceof Sql2Generator) { + throw new NotSupportedOperandException('Only SQL2 supports local node name operand'); + } + return $this->generator->evalNodeLocalName($operand->getSelectorName()); } if ($operand instanceof QOM\FullTextSearchScoreInterface) { + if (!$this->generator instanceof Sql2Generator) { + throw new NotSupportedOperandException('Only SQL2 supports fulltext search score operand'); + } + return $this->generator->evalFullTextSearchScore($operand->getSelectorName()); } if ($operand instanceof QOM\LowerCaseInterface) { - $operand = $this->convertDynamicOperand($operand->getOperand()); + $operandName = $this->convertDynamicOperand($operand->getOperand()); - return $this->generator->evalLower($operand); + return $this->generator->evalLower($operandName); } if ($operand instanceof QOM\UpperCaseInterface) { - $operand = $this->convertDynamicOperand($operand->getOperand()); + $operandName = $this->convertDynamicOperand($operand->getOperand()); - return $this->generator->evalUpper($operand); + return $this->generator->evalUpper($operandName); } // This should not happen, but who knows... diff --git a/src/PHPCR/Util/QOM/Sql1Generator.php b/src/PHPCR/Util/QOM/Sql1Generator.php index c06a061..6c9927a 100644 --- a/src/PHPCR/Util/QOM/Sql1Generator.php +++ b/src/PHPCR/Util/QOM/Sql1Generator.php @@ -64,11 +64,12 @@ public function evalChildNode($path, $selectorName = null) /** * Emulate descendant query with LIKE query. * - * @param string $path + * @param string $path + * @param string|null $selectorName Unused * * @return string */ - public function evalDescendantNode($path) + public function evalDescendantNode($path, $selectorName = null) { $path = $this->getPathForDescendantQuery($path); @@ -161,10 +162,11 @@ public function evalPropertyValue($propertyName, $selectorName = null) * * @param string $selectorName unused in SQL1 * @param string $propertyName + * @param string $colname unused in SQL1 * * @return string */ - public function evalColumn($selectorName = null, $propertyName = null) + public function evalColumn($selectorName = null, $propertyName = null, $colname = null) { return $propertyName; } diff --git a/src/PHPCR/Util/QOM/Sql2Generator.php b/src/PHPCR/Util/QOM/Sql2Generator.php index a938911..45fd775 100644 --- a/src/PHPCR/Util/QOM/Sql2Generator.php +++ b/src/PHPCR/Util/QOM/Sql2Generator.php @@ -237,7 +237,7 @@ public function evalPropertyExistence($selectorName, $propertyName) * FullTextSearchExpression ')' * FullTextSearchExpression ::= BindVariable | ''' FullTextSearchLiteral '''. * - * @param string $selectorName unusued + * @param string $selectorName * @param string $searchExpression * @param string $propertyName * @@ -389,18 +389,19 @@ public function evalColumn($selectorName, $propertyName = null, $colname = null) */ public function evalPath($path) { - if ($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 (substr($path, 0, 1) !== '[' && substr($path, -1) !== ']') { - if (false !== strpos($sql2, ' ') || false !== strpos($sql2, '.')) { - $sql2 = '"'.$sql2.'"'; - } - $sql2 = '['.$sql2.']'; + 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 (strpos($path, '[') !== 0 && substr($path, -1) !== ']') { + if (false !== strpos($sql2, ' ') || false !== strpos($sql2, '.')) { + $sql2 = '"'.$sql2.'"'; } - - return $sql2; + $sql2 = '['.$sql2.']'; } + + return $sql2; } /** diff --git a/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php b/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php index 40a336b..76aca66 100644 --- a/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php +++ b/src/PHPCR/Util/QOM/Sql2ToQomQueryConverter.php @@ -69,6 +69,11 @@ class Sql2ToQomQueryConverter */ protected $implicitSelectorName = null; + /** + * @var ValueConverter + */ + private $valueConverter; + /** * Instantiate a converter. * diff --git a/src/PHPCR/Util/TraversingItemVisitor.php b/src/PHPCR/Util/TraversingItemVisitor.php index 447b35d..713df4c 100644 --- a/src/PHPCR/Util/TraversingItemVisitor.php +++ b/src/PHPCR/Util/TraversingItemVisitor.php @@ -159,7 +159,15 @@ public function visit(ItemInterface $item) $this->entering($item, $this->currentDepth); $this->leaving($item, $this->currentDepth); } else { - /* @var $item NodeInterface */ + if (!$item instanceof NodeInterface) { + throw new RepositoryException(sprintf( + 'Internal error in TraversingItemVisitor: item %s at %s is not a node but %s', + $item->getName(), + $item->getPath(), + get_class($item) + )); + } + try { if ($this->breadthFirst === false) { $this->entering($item, $this->currentDepth); diff --git a/src/PHPCR/Util/TreeWalker.php b/src/PHPCR/Util/TreeWalker.php index 670c413..94b460f 100644 --- a/src/PHPCR/Util/TreeWalker.php +++ b/src/PHPCR/Util/TreeWalker.php @@ -122,20 +122,26 @@ 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) + public function traverse(NodeInterface $node, $recurse = -1, $level = 0): void { if ($this->mustVisitNode($node)) { // Visit node - $this->nodeVisitor->setLevel($level); - $this->nodeVisitor->setShowFullPath(0 === $level); + if (method_exists($this->nodeVisitor, 'setLevel')) { + $this->nodeVisitor->setLevel($level); + } + if (method_exists($this->nodeVisitor, 'setShowFullPath')) { + $this->nodeVisitor->setShowFullPath(0 === $level); + } $node->accept($this->nodeVisitor); // Visit properties if ($this->propertyVisitor !== null) { foreach ($node->getProperties() as $prop) { if ($this->mustVisitProperty($prop)) { - $this->propertyVisitor->setLevel($level); + if (method_exists($this->propertyVisitor, 'setLevel')) { + $this->propertyVisitor->setLevel($level); + } $prop->accept($this->propertyVisitor); } } diff --git a/tests/PHPCR/Tests/Util/CND/Reader/FileReaderTest.php b/tests/PHPCR/Tests/Util/CND/Reader/FileReaderTest.php index 23329e4..5d3d1a2 100644 --- a/tests/PHPCR/Tests/Util/CND/Reader/FileReaderTest.php +++ b/tests/PHPCR/Tests/Util/CND/Reader/FileReaderTest.php @@ -23,6 +23,11 @@ class FileReaderTest extends TestCase */ private $lines; + /** + * @var string[] + */ + private $chars; + public function setUp(): void { $this->filepath = __DIR__.'/../Fixtures/files/TestFile.txt'; diff --git a/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php b/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php index dab5d01..59f9377 100644 --- a/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php +++ b/tests/PHPCR/Tests/Util/CND/Scanner/GenericScannerTest.php @@ -10,8 +10,6 @@ use PHPCR\Util\CND\Scanner\TokenFilter; use PHPCR\Util\CND\Scanner\TokenQueue; use PHPUnit\Framework\TestCase; -use Test; -use TestClass; class GenericScannerTest extends TestCase { @@ -27,7 +25,7 @@ class GenericScannerTest extends TestCase // namespace Test\Foobar; [Token::TK_IDENTIFIER, 'namespace'], [Token::TK_WHITESPACE, ''], - [Token::TK_IDENTIFIER, Test::class], + [Token::TK_IDENTIFIER, 'Test'], [Token::TK_SYMBOL, '\\'], [Token::TK_IDENTIFIER, 'Foobar'], [Token::TK_SYMBOL, ';'], @@ -37,7 +35,7 @@ class GenericScannerTest extends TestCase // class TestClass { [Token::TK_IDENTIFIER, 'class'], [Token::TK_WHITESPACE, ''], - [Token::TK_IDENTIFIER, TestClass::class], + [Token::TK_IDENTIFIER, 'TestClass'], [Token::TK_NEWLINE, ''], [Token::TK_SYMBOL, '{'], [Token::TK_NEWLINE, ''], diff --git a/tests/PHPCR/Tests/Util/QOM/BaseSqlGeneratorTest.php b/tests/PHPCR/Tests/Util/QOM/BaseSqlGeneratorTest.php index e5ed115..0f11e57 100644 --- a/tests/PHPCR/Tests/Util/QOM/BaseSqlGeneratorTest.php +++ b/tests/PHPCR/Tests/Util/QOM/BaseSqlGeneratorTest.php @@ -2,10 +2,16 @@ namespace PHPCR\Tests\Util\QOM; +use PHPCR\Util\QOM\BaseSqlGenerator; use PHPUnit\Framework\TestCase; abstract class BaseSqlGeneratorTest extends TestCase { + /** + * @var BaseSqlGenerator + */ + protected $generator; + public function testNot() { $string = $this->generator->evalNot('foo = bar'); From 3edec926fa608af32b863ba6cb97d3b208e7b765 Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Fri, 17 Feb 2023 02:14:03 +0100 Subject: [PATCH 66/88] prepare release --- CHANGELOG.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index ddf5ee6..9f7b4f4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,13 @@ Changelog ========= +1.7.0 +----- + +* Introduced phpstan and fixed a couple of undeclared properties and other findings. +* Test with PHP 8.2 +* Drop support for PHP 7.1 + 1.6.3 ----- From cf2ceadee32a974d46f62c94bb1726e5b90806d2 Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Sat, 18 Feb 2023 14:33:01 +0100 Subject: [PATCH 67/88] fix fulltext search --- .github/workflows/test-application.yaml | 1 - CHANGELOG.md | 5 +++++ composer.json | 7 +------ src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php | 14 ++++++++++++-- 4 files changed, 18 insertions(+), 9 deletions(-) diff --git a/.github/workflows/test-application.yaml b/.github/workflows/test-application.yaml index 760386b..a484683 100644 --- a/.github/workflows/test-application.yaml +++ b/.github/workflows/test-application.yaml @@ -4,7 +4,6 @@ on: pull_request: push: branches: - - 'master' - '[0-9]+.x' - '[0-9]+.[0-9]+' - '[0-9]+.[0-9]+.x' diff --git a/CHANGELOG.md b/CHANGELOG.md index 9f7b4f4..8082c2a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,11 @@ Changelog ========= +1.8.0 +----- + +* Fixed handling of QOM fulltext search expression which should never be string but a `QOM\StaticOperandInterface`. + 1.7.0 ----- diff --git a/composer.json b/composer.json index 3364e45..655bd18 100644 --- a/composer.json +++ b/composer.json @@ -47,10 +47,5 @@ "PHPCR\\Util": "src" } }, - "bin": ["bin/phpcr"], - "extra": { - "branch-alias": { - "dev-master": "1.x-dev" - } - } + "bin": ["bin/phpcr"] } diff --git a/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php b/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php index 9cab6b0..7161a1b 100644 --- a/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php +++ b/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php @@ -4,6 +4,7 @@ use InvalidArgumentException; use PHPCR\Query\QOM; +use PHPCR\Query\QOM\StaticOperandInterface; /** * Common base class for the SQL(1) and SQL2 converters. @@ -170,14 +171,23 @@ protected function convertFullTextSearch(QOM\FullTextSearchInterface $constraint /** * FullTextSearchExpression ::= BindVariable | ''' FullTextSearchLiteral '''. * - * @param string $expr + * @param string|QOM\StaticOperandInterface $expr * * @return string */ protected function convertFullTextSearchExpression($expr) { if ($expr instanceof QOM\BindVariableValueInterface) { - return $this->convertBindVariable($expr); + return $this->convertBindVariable($expr->getBindVariableName()); + } + if ($expr instanceof QOM\LiteralInterface) { + $literal = $expr->getLiteralValue(); + } elseif (is_string($expr)) { + // this should not happen, the interface for full text search declares the return type to be StaticOperandInterface + // 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)); } $expr = $this->generator->evalFullText($expr); From e7229ac9adbf4d1cbdca944671a2a227be0d235b Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Sat, 18 Feb 2023 14:47:42 +0100 Subject: [PATCH 68/88] fix mistake in handling full text constraint --- src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php b/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php index 7161a1b..b9f2801 100644 --- a/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php +++ b/src/PHPCR/Util/QOM/BaseQomToSqlQueryConverter.php @@ -190,9 +190,9 @@ protected function convertFullTextSearchExpression($expr) throw new InvalidArgumentException('Unknown full text search expression type '.get_class($expr)); } - $expr = $this->generator->evalFullText($expr); + $literal = $this->generator->evalFullText($literal); - return "'$expr'"; + return "'$literal'"; } /** From 83f383999944e5c0630a6787084f8e0a9192843c Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Sat, 18 Feb 2023 14:47:42 +0100 Subject: [PATCH 69/88] use newest github action versions in build --- .github/workflows/test-application.yaml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/test-application.yaml b/.github/workflows/test-application.yaml index a484683..9e15c89 100644 --- a/.github/workflows/test-application.yaml +++ b/.github/workflows/test-application.yaml @@ -29,7 +29,7 @@ jobs: steps: - name: Checkout project - uses: actions/checkout@v2 + uses: actions/checkout@v3 - name: Install and configure PHP uses: shivammathur/setup-php@v2 @@ -42,7 +42,7 @@ jobs: run: composer config minimum-stability dev - name: Install dependencies with Composer - uses: ramsey/composer-install@v1 + uses: ramsey/composer-install@v2 with: dependency-versions: ${{ matrix.dependencies }} composer-options: --prefer-dist @@ -62,7 +62,7 @@ jobs: steps: - name: Checkout project - uses: actions/checkout@v2 + uses: actions/checkout@v3 - name: Install and configure PHP uses: shivammathur/setup-php@v2 @@ -75,7 +75,7 @@ jobs: run: composer config minimum-stability dev - name: Install dependencies with Composer - uses: ramsey/composer-install@v1 + uses: ramsey/composer-install@v2 with: dependency-versions: ${{ matrix.dependencies }} composer-options: --prefer-dist From c650d574011af4d5b1a8241554f72d0f771dbd90 Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Mon, 20 Feb 2023 17:10:06 +0100 Subject: [PATCH 70/88] fix eof detection for PHP 7+. fix #168 --- src/PHPCR/Util/CND/Reader/BufferReader.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/PHPCR/Util/CND/Reader/BufferReader.php b/src/PHPCR/Util/CND/Reader/BufferReader.php index e9b8d0b..e38c00d 100644 --- a/src/PHPCR/Util/CND/Reader/BufferReader.php +++ b/src/PHPCR/Util/CND/Reader/BufferReader.php @@ -114,8 +114,9 @@ public function currentChar() */ public function isEof() { - return $this->currentChar() === $this->getEofMarker() - || $this->currentChar() === false + $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) || $this->forwardPos > strlen($this->buffer); } From 50e99c9f38d61f3c348797469653b696e4feca5f Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Mon, 20 Feb 2023 17:30:23 +0100 Subject: [PATCH 71/88] prepare release --- CHANGELOG.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8082c2a..bcf780b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,8 @@ Changelog 1.8.0 ----- -* Fixed handling of QOM fulltext search expression which should never be string but a `QOM\StaticOperandInterface`. +* Fixed handling of QOM fulltext search expression which should never be string but a `QOM\StaticOperandInterface`. +* Fixed EOF detection while parsing CND with PHP 7+. 1.7.0 ----- From 7d05a34323124e406337c6981472b72c0f3e249e Mon Sep 17 00:00:00 2001 From: StyleCI Bot Date: Tue, 19 Sep 2023 17:02:28 +0000 Subject: [PATCH 72/88] Apply fixes from StyleCI --- src/PHPCR/Util/CND/Scanner/GenericScanner.php | 3 --- src/PHPCR/Util/PathHelper.php | 3 +-- src/PHPCR/Util/TreeWalker.php | 1 - src/PHPCR/Util/ValueConverter.php | 2 +- tests/PHPCR/Tests/Util/NodeHelperTest.php | 3 +-- tests/PHPCR/Tests/Util/ValueConverterTest.php | 6 +++--- 6 files changed, 6 insertions(+), 12 deletions(-) diff --git a/src/PHPCR/Util/CND/Scanner/GenericScanner.php b/src/PHPCR/Util/CND/Scanner/GenericScanner.php index edc1d00..76ccecd 100644 --- a/src/PHPCR/Util/CND/Scanner/GenericScanner.php +++ b/src/PHPCR/Util/CND/Scanner/GenericScanner.php @@ -165,13 +165,11 @@ protected function consumeBlockComments(ReaderInterface $reader) $nextChar = $reader->currentChar(); foreach ($this->context->getBlockCommentDelimiters() as $beginDelim => $endDelim) { if ($nextChar === $beginDelim[0]) { - // Lookup the start delimiter for ($i = 1; $i <= strlen($beginDelim); $i++) { $reader->forward(); } if ($reader->current() === $beginDelim) { - // Start delimiter found, let's try to find the end delimiter $nextChar = $reader->forwardChar(); @@ -223,7 +221,6 @@ protected function consumeLineComments(ReaderInterface $reader) } if ($reader->current() === $delimiter) { - // consume to end of line $char = $reader->currentChar(); while (!$reader->isEof() && $char !== "\n") { diff --git a/src/PHPCR/Util/PathHelper.php b/src/PHPCR/Util/PathHelper.php index 0394163..8fba416 100644 --- a/src/PHPCR/Util/PathHelper.php +++ b/src/PHPCR/Util/PathHelper.php @@ -165,8 +165,7 @@ public static function normalizePath($path, $destination = false, $throw = true) } $normalizedPath = count($finalParts) > 1 ? implode('/', $finalParts) : - '/' // first element is always the empty-name root element. this might have been a path like /x/.. -; + '/'; // first element is always the empty-name root element. this might have been a path like /x/.. if (!self::assertValidAbsolutePath($normalizedPath, $destination, $throw)) { return false; diff --git a/src/PHPCR/Util/TreeWalker.php b/src/PHPCR/Util/TreeWalker.php index 94b460f..2eaf6e3 100644 --- a/src/PHPCR/Util/TreeWalker.php +++ b/src/PHPCR/Util/TreeWalker.php @@ -125,7 +125,6 @@ protected function mustVisitProperty(PropertyInterface $property) public function traverse(NodeInterface $node, $recurse = -1, $level = 0): void { if ($this->mustVisitNode($node)) { - // Visit node if (method_exists($this->nodeVisitor, 'setLevel')) { $this->nodeVisitor->setLevel($level); diff --git a/src/PHPCR/Util/ValueConverter.php b/src/PHPCR/Util/ValueConverter.php index 343a93d..859cdfe 100644 --- a/src/PHPCR/Util/ValueConverter.php +++ b/src/PHPCR/Util/ValueConverter.php @@ -167,7 +167,7 @@ public function convertType($value, $type, $srcType = PropertyType::UNDEFINED) case PropertyType::NAME: case PropertyType::PATH: // TODO: The name/path is converted to qualified form according to the current local namespace mapping (see §3.2.5.2 Qualified Form). - return $value; + return $value; default: if (is_object($value)) { throw new ValueFormatException('Cannot convert object of class "'.get_class($value).'" to STRING'); diff --git a/tests/PHPCR/Tests/Util/NodeHelperTest.php b/tests/PHPCR/Tests/Util/NodeHelperTest.php index 5a1f392..bebad5e 100644 --- a/tests/PHPCR/Tests/Util/NodeHelperTest.php +++ b/tests/PHPCR/Tests/Util/NodeHelperTest.php @@ -117,8 +117,7 @@ public function testIsSystemItem() $top->expects($this->once()) ->method('getName') - ->willReturn('jcrname') // this is NOT in the jcr namespace -; + ->willReturn('jcrname'); // this is NOT in the jcr namespace $this->assertFalse(NodeHelper::isSystemItem($top)); diff --git a/tests/PHPCR/Tests/Util/ValueConverterTest.php b/tests/PHPCR/Tests/Util/ValueConverterTest.php index f14e55b..65002a7 100644 --- a/tests/PHPCR/Tests/Util/ValueConverterTest.php +++ b/tests/PHPCR/Tests/Util/ValueConverterTest.php @@ -269,9 +269,9 @@ 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 + * @param $expected + * @param $targetType * * @dataProvider dataConversionMatrix */ From 806a28ca598546383e3495a5c0a9d5d4f61978b3 Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Mon, 27 Nov 2023 14:59:39 +0100 Subject: [PATCH 73/88] prepare release --- CHANGELOG.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index bcf780b..b85a588 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,13 @@ Changelog ========= +1.x +--- + +1.8.1 +----- +* Codestyle fixes. + 1.8.0 ----- From 3df491e6918b15d6c5ff869ef6c6d92bc1c5061f Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Mon, 27 Nov 2023 15:04:51 +0100 Subject: [PATCH 74/88] downgrade phpstan --- .github/workflows/static.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/static.yml b/.github/workflows/static.yml index b1403f2..98bf641 100644 --- a/.github/workflows/static.yml +++ b/.github/workflows/static.yml @@ -15,10 +15,10 @@ jobs: steps: - name: Checkout code - uses: actions/checkout@v2 + uses: actions/checkout@v3 - name: PHPStan - uses: docker://oskarstark/phpstan-ga + uses: docker://oskarstark/phpstan-ga:1.8.0 with: args: analyze --no-progress @@ -30,13 +30,13 @@ jobs: steps: - name: Checkout code - uses: actions/checkout@v2 + uses: actions/checkout@v3 - name: Install dependencies run: | composer update --no-progress - name: PHPStan - uses: docker://oskarstark/phpstan-ga + uses: docker://oskarstark/phpstan-ga:1.8.0 with: args: analyze --no-progress -c phpstan.tests.neon.dist From 3921d659837ee6172894f7f85e486be69eb721af Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Tue, 19 Sep 2023 18:51:55 +0200 Subject: [PATCH 75/88] 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 9e15c89..a4226ab 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 b85a588..53f113a 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 655bd18..e4e125d 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 10cdf18..dcfbd68 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 d0f3fd4..2eef8c1 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 280fb5a..0ee7431 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 7ca3f0e..e3cd0f4 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 2f95fa5..557e6fa 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 9cf78ed..0534b2c 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 50aa22d..6e29b1d 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 c0ac8a6..b9c1401 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 9200fe6..fd63d40 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 5708e79..c8e0f7b 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 4b6578d..1641d7f 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 3165f8b..4210891 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 c8c8f81..c33baa9 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 f4d7fc1..d7015ff 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 d7d3cdb..04c3522 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 edb6edc..8e044dd 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 76/88] 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 98bf641..0f89ba6 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 bb6966f..35e5af6 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 0000000..92bc748 --- /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 5e45ebb..0000000 --- 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 e4e125d..d76537d 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 a08d67e..5652ee1 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 e01aae6..a7f3aba 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 dab5dc9..59249d7 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 e38c00d..20db884 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 f61f0dd..35eb208 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 a9ea48a..f9855dd 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 76ccecd..1860854 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 735de8c..6d7e7e5 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 f24fdb6..0402059 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 6acf162..d61a7a2 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 9268388..1bb953f 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 d1424d1..0904e24 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 2ab7538..154d8bd 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 5fdd56e..d1ff179 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 dcfbd68..0f6f434 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 0ee7431..a6083a1 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 e3cd0f4..e4dca65 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 0534b2c..3e8485f 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 6e29b1d..dd8ca70 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 c8e0f7b..1487b4a 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 1641d7f..109f3f9 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 04c3522..f22c51b 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 8e044dd..68608c9 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 ddd1623..fe334e1 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 c64438b..3656b18 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 63ccbc7..6202b49 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 51c1cf6..9c6e86c 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 fada226..84e8090 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 8fba416..649ef73 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 b9f2801..b74f1af 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 e023fbd..5226cd4 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 223e850..39a543d 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 bc7f317..af6457e 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 ae591b5..4c75be4 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 fdef9c0..b5dd984 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 23c6c12..eb6211b 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 6c9927a..bea5d88 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 45fd775..a819c6c 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 a4c4107..2bc91f7 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 76aca66..7e58eb0 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 713df4c..2890c55 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 2eaf6e3..d1539e8 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 41272d7..1e32605 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 546a71d..476c136 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 859cdfe..ab11663 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 e024939..ea93721 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 7cd4660..97f696f 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 4507722..298e2be 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 86fd747..7741efe 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 5d3d1a2..e7fed57 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 59f9377..53c5212 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 8f81190..272ce1e 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 f935b7d..26c13f6 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 993d486..c9aee70 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 c103ee4..7edbd10 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 0bbb59a..30cc7fa 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 542fe10..a05ea5a 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 7df686b..34f8608 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 9808db4..ebd841f 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 d2b5ebd..5d2958c 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 057b3a6..6c4b97d 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 bebad5e..a365929 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 14d0911..cc7ec87 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 a96ef09..7b50c42 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 aa0a7aa..b3f3719 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 f28dff4..1dac252 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 4fca591..b4627bb 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 65002a7..e69ed96 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 cabe086..ac7baf3 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 77/88] 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 a4226ab..cc3ec50 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 53f113a..8fde359 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 d76537d..843324f 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 bc5b3ef..093e815 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 d1ff179..71822c6 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 a6083a1..bbf0071 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 dd8ca70..fd49f99 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 fd63d40..8a6bee1 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 c33baa9..c9112bb 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 78/88] 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 5652ee1..8be90b3 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 8f20151..f68f409 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 a7f3aba..8954f1d 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 59249d7..0aa4354 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 20db884..2e38031 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 353594d..30daeb3 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 0f8b73e..614b43c 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 35eb208..3d1ae4c 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 f9855dd..3befd7c 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 1860854..3f324c4 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 6d7e7e5..b278555 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 80aebe6..4ae91e4 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 0402059..0d5a8ba 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 d61a7a2..24fa082 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 1bb953f..c38d3d3 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 0904e24..a25db19 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 154d8bd..c1f21a5 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 9633e45..bb995e9 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 e4dca65..f397e4b 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 3e8485f..3fc5c9d 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 b9c1401..90ce44a 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 f22c51b..32b640e 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 68608c9..5bb5a1b 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 fe334e1..a28551e 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 3656b18..925cdc8 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 6202b49..55ddc74 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 9c6e86c..cffc9b8 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 84e8090..6f2e121 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 649ef73..43c289b 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 b74f1af..6750699 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 5226cd4..f1b43f1 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 39a543d..3d14c25 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 af6457e..e982488 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 4c75be4..cb89b15 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 b5dd984..09d63eb 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 eb6211b..9205152 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 bea5d88..94edccf 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 a819c6c..ca656fe 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 2bc91f7..9fd6472 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 7e58eb0..d849cda 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 2890c55..911e2ba 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 d1539e8..52fb753 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 1e32605..9265bcc 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 476c136..0e59fa7 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 ab11663..c3ff595 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 cc7ec87..0e0dd06 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 7b50c42..c5466d0 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 b3f3719..4bc2184 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 1dac252..5517fb3 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 e69ed96..ce74b05 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 79/88] 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 8be90b3..3cb73bd 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 2eef8c1..e6b6730 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 bbf0071..ec98705 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 f397e4b..3ff77f0 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 557e6fa..88c6dbb 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 3fc5c9d..7950ee4 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 fd49f99..eeb4d94 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 90ce44a..07f6c55 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 8a6bee1..2366276 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 1487b4a..2500918 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 109f3f9..b9b0047 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 4210891..3a5d631 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 c9112bb..ac2dc07 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 d7015ff..2b9944e 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 a28551e..d9b1d86 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 55ddc74..97f696d 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 cffc9b8..64a7e79 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 f1b43f1..2215ec7 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 94edccf..3f637a9 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 911e2ba..1ee1ced 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 52fb753..0ebe6f0 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 ea93721..68603a0 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 e7fed57..00e8fc8 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 53c5212..84982b5 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 7af6afb..8b653c5 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 272ce1e..08b7673 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 26c13f6..84d430e 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 132aafb..52d5776 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 7edbd10..6381ba5 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 30cc7fa..41febd1 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 f74f6fd..3359f87 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 b39fe38..76fc4e7 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 a05ea5a..251655a 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 34f8608..f3352a3 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 ebd841f..30df140 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 a16e265..1868ed0 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 5d2958c..13e16cf 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 86ef8fc..1044200 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 5938ac8..f37ecfe 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 9ab438b..184f9cb 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 6c4b97d..575fc28 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 a365929..68e514a 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 0e0dd06..8e03eea 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 0f11e57..c89b55e 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 c5466d0..40aff3c 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 4bc2184..8798c67 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 5517fb3..f7d8c76 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 b4627bb..9b6ea95 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 393e3e6..d52beee 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 e233026..abc3be6 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 3e20505..f6efc33 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 ce74b05..4b87194 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 80/88] 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 d2edb48..1dfa587 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 bf789ee..58a76d8 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 1396b4d..d03bb90 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 9c52e98..9f88af8 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 112e59e..1081328 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 33c0a89..20f8d5e 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 ec98705..362df92 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 3ff77f0..7d554af 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 3af5473..f447df5 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 d9b1d86..ecdd293 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 b788646..e1f8153 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 97f696d..cd07faa 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 28abbd4..9792487 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 e8fcbfc..ffa1464 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 f4d8c38..f9444b7 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 f7fa228..f29faa9 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 3f637a9..bcd7b93 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 1f83f7d..0ec2a83 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 bde4417..880a0f9 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 1ee1ced..4707e96 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 0ebe6f0..723b54b 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 6b5f5ec..f9a7695 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 84982b5..7936038 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 08b7673..79cf660 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 8c5590fee72927cea80de76fee32a0216594da5b Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Wed, 29 Nov 2023 13:06:36 +0100 Subject: [PATCH 81/88] bug is fixed, use latest phpstan action --- .github/workflows/static.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/static.yml b/.github/workflows/static.yml index 98bf641..31130e5 100644 --- a/.github/workflows/static.yml +++ b/.github/workflows/static.yml @@ -18,7 +18,7 @@ jobs: uses: actions/checkout@v3 - name: PHPStan - uses: docker://oskarstark/phpstan-ga:1.8.0 + uses: docker://oskarstark/phpstan-ga with: args: analyze --no-progress @@ -37,6 +37,6 @@ jobs: composer update --no-progress - name: PHPStan - uses: docker://oskarstark/phpstan-ga:1.8.0 + uses: docker://oskarstark/phpstan-ga with: args: analyze --no-progress -c phpstan.tests.neon.dist From 78040a92af1a91a6a163a8eb62f1fdbc6c2caac6 Mon Sep 17 00:00:00 2001 From: David Buchmann Date: Fri, 1 Dec 2023 15:34:59 +0100 Subject: [PATCH 82/88] 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 093e815..6fc9436 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 0efe94d..b4deb82 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 1dfa587..ace8eb2 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 58a76d8..33dd38d 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 d03bb90..8161eb3 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 20f8d5e..796f399 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 b5d86e1..756dab9 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 cd07faa..4a4f41c 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 880a0f9..bb1e88b 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 68603a0..5d27eac 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 b085ecf..468fe9d 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 27bc04e..9511237 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 00e8fc8..1e49cbb 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 7936038..7021b05 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 84d430e..a0300ce 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 d5228ea..5e5da9a 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 52d5776..4dee112 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 41febd1..afc746d 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 3359f87..fb25baf 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 76fc4e7..712b4a1 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 251655a..6806109 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 184f9cb..d751012 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 575fc28..748fb87 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 68e514a..1878745 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 8e03eea..5bafb69 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 40aff3c..b89f7e2 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 9b6ea95..9918d94 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 4b87194..28f0b87 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 83/88] prepare release --- CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8fde359..1c4803f 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 84/88] 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 b4deb82..d7889e1 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 468fe9d..f3fe1df 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 85/88] 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 1c4803f..12aba85 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 2215ec7..98851fc 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 86/88] 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 ace8eb2..638013f 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 38c7fad..08bf602 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 9792487..cccbc05 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 f9444b7..928ac90 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 98851fc..365d625 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 f29faa9..1018e7e 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 bcd7b93..452a164 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 e327848..7c042f1 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 bb1e88b..e0bd27b 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 723b54b..0588c94 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 87/88] 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 1018e7e..046bc87 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 88/88] prepare release --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 12aba85..c560bbc 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 -----