diff --git a/.gitignore b/.gitignore index 3b39edc1..45aca26b 100644 --- a/.gitignore +++ b/.gitignore @@ -13,3 +13,5 @@ test #PHP-CS-FIXER .php-cs-fixer.php .php-cs-fixer.cache + + diff --git a/composer.json b/composer.json index aea16885..f148d564 100644 --- a/composer.json +++ b/composer.json @@ -12,6 +12,7 @@ "require-dev": { "phpunit/phpunit": "^11.0", "friendsofphp/php-cs-fixer": "^3.68" + }, "autoload": { "psr-4": { diff --git a/composer.lock b/composer.lock index 09363afc..471d7d01 100644 --- a/composer.lock +++ b/composer.lock @@ -1082,16 +1082,16 @@ }, { "name": "friendsofphp/php-cs-fixer", - "version": "v3.68.0", + "version": "v3.68.5", "source": { "type": "git", "url": "https://github.com/PHP-CS-Fixer/PHP-CS-Fixer.git", - "reference": "73f78d8b2b34a0dd65fedb434a602ee4c2c8ad4c" + "reference": "7bedb718b633355272428c60736dc97fb96daf27" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/PHP-CS-Fixer/PHP-CS-Fixer/zipball/73f78d8b2b34a0dd65fedb434a602ee4c2c8ad4c", - "reference": "73f78d8b2b34a0dd65fedb434a602ee4c2c8ad4c", + "url": "https://api.github.com/repos/PHP-CS-Fixer/PHP-CS-Fixer/zipball/7bedb718b633355272428c60736dc97fb96daf27", + "reference": "7bedb718b633355272428c60736dc97fb96daf27", "shasum": "" }, "require": { @@ -1173,7 +1173,7 @@ ], "support": { "issues": "https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/issues", - "source": "https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/tree/v3.68.0" + "source": "https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/tree/v3.68.5" }, "funding": [ { @@ -1181,7 +1181,7 @@ "type": "github" } ], - "time": "2025-01-13T17:01:01+00:00" + "time": "2025-01-30T17:00:50+00:00" }, { "name": "myclabs/deep-copy", @@ -1744,16 +1744,16 @@ }, { "name": "phpunit/phpunit", - "version": "11.5.3", + "version": "11.5.7", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/phpunit.git", - "reference": "30e319e578a7b5da3543073e30002bf82042f701" + "reference": "e1cb706f019e2547039ca2c839898cd5f557ee5d" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/30e319e578a7b5da3543073e30002bf82042f701", - "reference": "30e319e578a7b5da3543073e30002bf82042f701", + "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/e1cb706f019e2547039ca2c839898cd5f557ee5d", + "reference": "e1cb706f019e2547039ca2c839898cd5f557ee5d", "shasum": "" }, "require": { @@ -1825,7 +1825,7 @@ "support": { "issues": "https://github.com/sebastianbergmann/phpunit/issues", "security": "https://github.com/sebastianbergmann/phpunit/security/policy", - "source": "https://github.com/sebastianbergmann/phpunit/tree/11.5.3" + "source": "https://github.com/sebastianbergmann/phpunit/tree/11.5.7" }, "funding": [ { @@ -1841,7 +1841,7 @@ "type": "tidelift" } ], - "time": "2025-01-13T09:36:00+00:00" + "time": "2025-02-06T16:10:05+00:00" }, { "name": "psr/container", diff --git a/src/BasicAuthentication.php b/src/BasicAuthentication.php index d8b0430c..bb46e365 100644 --- a/src/BasicAuthentication.php +++ b/src/BasicAuthentication.php @@ -11,7 +11,6 @@ class BasicAuthentication implements AuthenticateInterface public function __construct(?string $username = null, ?string $password = null) { - // Use provided values or fallback to environment variables $this->username = $username ?? getenv("NEO4J_USERNAME") ?: ''; $this->password = $password ?? getenv("NEO4J_PASSWORD") ?: ''; } diff --git a/src/Neo4jPhp.php b/src/Neo4jPhp.php deleted file mode 100644 index 6a1892d3..00000000 --- a/src/Neo4jPhp.php +++ /dev/null @@ -1,108 +0,0 @@ - 'Basic ' . $credentials, - 'Content-Type' => 'application/json', - ]; - - // Initialize the client with the authorization header - $client = new \GuzzleHttp\Client([ - 'base_uri' => rtrim($neo4jAddress, '/'), - 'timeout' => 10.0, - 'headers' => $headers, - ]); - - // Step 2: Create the Cypher query - $cypherQuery = 'MATCH (n) RETURN n LIMIT 10'; - $parameters = []; // No parameters in this query - $database = 'neo4j'; // Default Neo4j database - - echo "Running Cypher Query: $cypherQuery\n"; - - // Prepare the payload for the Cypher query - $payload = [ - 'statement' => $cypherQuery, - 'parameters' => new stdClass(), // No parameters - 'includeCounters' => true, - ]; - - // Step 3: Send the request to Neo4j - $response = $client->post("/db/{$database}/query/v2", [ - 'json' => $payload, - ]); - - // Parse the response body as JSON - $responseData = json_decode($response->getBody()->getContents(), true); - - // Check for errors in the response - if (isset($responseData['errors']) && count($responseData['errors']) > 0) { - echo "Error: " . $responseData['errors'][0]['message'] . "\n"; - } else { - // Step 4: Output the result of the query - echo "Query Results:\n"; - foreach ($responseData['data'] as $row) { - print_r($row); // Print each row's data - } - } - - // Step 5: Begin a new transaction - $transactionResponse = $client->post("/db/neo4j/query/v2/tx"); - $transactionData = json_decode($transactionResponse->getBody()->getContents(), true); - $transactionId = $transactionData['transaction']['id']; // Retrieve the transaction ID - - echo "Transaction started successfully.\n"; - echo "Transaction ID: $transactionId\n"; - - // You can also fetch additional transaction details if available in the response - // Example: transaction metadata or counters - if (isset($transactionData['transaction']['metadata'])) { - echo "Transaction Metadata: \n"; - print_r($transactionData['transaction']['metadata']); - } - - // Step 6: Execute a query within the transaction - $cypherTransactionQuery = 'MATCH (n) SET n.modified = true RETURN n LIMIT 5'; - $transactionPayload = [ - 'statement' => $cypherTransactionQuery, - 'parameters' => new stdClass(), // No parameters - ]; - - // Execute the transaction query - $transactionQueryResponse = $client->post("/db/neo4j/query/v2/tx/{$transactionId}/commit", [ - 'json' => $transactionPayload, - ]); - - $transactionQueryData = json_decode($transactionQueryResponse->getBody()->getContents(), true); - - // Check for any errors in the transaction query - if (isset($transactionQueryData['errors']) && count($transactionQueryData['errors']) > 0) { - echo "Transaction Error: " . $transactionQueryData['errors'][0]['message'] . "\n"; - } else { - echo "Transaction Query Results:\n"; - print_r($transactionQueryData['data']); // Print transaction results - } - -} catch (RequestException $e) { - echo "Request Error: " . $e->getMessage() . "\n"; -} catch (Exception $e) { - echo "Error: " . $e->getMessage() . "\n"; -} diff --git a/src/NoAuth.php b/src/NoAuth.php index 0444ef49..aa1565c6 100644 --- a/src/NoAuth.php +++ b/src/NoAuth.php @@ -11,16 +11,3 @@ public function authenticate(RequestInterface $request): RequestInterface return $request; } } - -/* -namespace Neo4j\QueryAPI; - -use Psr\Http\Message\RequestInterface; - -class NoAuth implements AuthenticateInterface -{ - public function authenticate(RequestInterface $request): RequestInterface - { - return $request; - } -}*/ diff --git a/src/OGM.php b/src/OGM.php index 0e2afc7c..4275ce3e 100644 --- a/src/OGM.php +++ b/src/OGM.php @@ -10,7 +10,7 @@ class OGM { /** - * @param array{'$type': string, '_value': mixed} $object + * @param array{'$type': string, ' $object _value': mixed} $object * @return mixed */ public function map(array $object): mixed @@ -21,8 +21,8 @@ public function map(array $object): mixed 'String' => $object['_value'], 'Boolean' => $object['_value'], 'Null' => $object['_value'], - 'Array' => $object['_value'], // Handle generic arrays - 'List' => array_map([$this, 'map'], $object['_value']), // Recursively map lists + 'Array' => $object['_value'], + 'List' => array_map([$this, 'map'], $object['_value']), 'Duration' => $object['_value'], 'OffsetDateTime' => $object['_value'], 'Node' => $this->mapNode($object['_value']), @@ -40,7 +40,7 @@ public static function parseWKT(string $wkt): Point $srid = (int)str_replace('SRID=', '', $sridPart); $pointPart = substr($wkt, strpos($wkt, 'POINT') + 6); - if (strpos($pointPart, 'Z') !== false) { + if (str_contains($pointPart, 'Z')) { $pointPart = str_replace('Z', '', $pointPart); } $pointPart = trim($pointPart, ' ()'); @@ -64,8 +64,8 @@ public static function parseWKT(string $wkt): Point private function mapNode(array $nodeData): Node { return new Node( - $nodeData['_labels'], // Labels of the node - $this->mapProperties($nodeData['_properties']) // Mapped properties + $nodeData['_labels'], + $this->mapProperties($nodeData['_properties']) ); } diff --git a/src/Objects/Authentication.php b/src/Objects/Authentication.php index e62d885c..ae8680e4 100644 --- a/src/Objects/Authentication.php +++ b/src/Objects/Authentication.php @@ -17,7 +17,7 @@ public static function basic(string $username, string $password): AuthenticateIn public static function fromEnvironment(): AuthenticateInterface { - // Fetch credentials from environment variables + $username = getenv("NEO4J_USERNAME") ?: ''; $password = getenv("NEO4J_PASSWORD") ?: ''; diff --git a/src/Objects/Person.php b/src/Objects/Person.php index 3776e646..6b8b1020 100644 --- a/src/Objects/Person.php +++ b/src/Objects/Person.php @@ -15,7 +15,7 @@ class Person extends Node */ public function __construct(array $properties) { - // Pass the label 'Person' along with the properties to the parent Node constructor. + parent::__construct(['Person'], $properties); } } diff --git a/src/Objects/ProfiledQueryPlan.php b/src/Objects/ProfiledQueryPlan.php index a32d314f..a1ab424e 100644 --- a/src/Objects/ProfiledQueryPlan.php +++ b/src/Objects/ProfiledQueryPlan.php @@ -35,7 +35,7 @@ public function __construct( ?string $operatorType, ProfiledQueryPlanArguments $arguments, ?array $children = [], - array $identifiers = [] // Default to an empty array + array $identifiers = [] ) { $this->dbHits = $dbHits ?? 0; $this->records = $records ?? 0; diff --git a/src/Objects/ResultSet.php b/src/Objects/ResultSet.php index a511dd74..e32b0b44 100644 --- a/src/Objects/ResultSet.php +++ b/src/Objects/ResultSet.php @@ -8,8 +8,6 @@ use Neo4j\QueryAPI\Results\ResultRow; use Traversable; -// Make sure to include the Bookmarks class - class ResultSet implements IteratorAggregate, Countable { /** diff --git a/src/Transaction.php b/src/Transaction.php index 46af85be..537d8bfd 100644 --- a/src/Transaction.php +++ b/src/Transaction.php @@ -2,6 +2,7 @@ namespace Neo4j\QueryAPI; +use GuzzleHttp\Exception\GuzzleException; use Neo4j\QueryAPI\Exception\Neo4jException; use Neo4j\QueryAPI\Objects\Authentication; use Neo4j\QueryAPI\Objects\Bookmarks; @@ -22,11 +23,11 @@ public function __construct( /** * Execute a Cypher query within the transaction. - * @api * @param string $query The Cypher query to be executed. * @param array $parameters Parameters for the query. * @return ResultSet The result rows in ResultSet format. - * @throws Neo4jException If the response structure is invalid. + * @throws Neo4jException|GuzzleException If the response structure is invalid. + *@api */ public function run(string $query, array $parameters): ResultSet { diff --git a/src/requestFactory.php b/src/requestFactory.php deleted file mode 100644 index 60d51d43..00000000 --- a/src/requestFactory.php +++ /dev/null @@ -1,67 +0,0 @@ -buildBeginTransactionRequest($database); - $beginTxResponse = $client->sendRequest($beginTxRequest); - $beginTxData = json_decode($beginTxResponse->getBody()->getContents(), true); - - // Extract the transaction ID - $transactionId = $beginTxData['transaction']['id'] ?? null; - if (!$transactionId) { - throw new RuntimeException("Transaction ID not found in response."); - } - - echo "Transaction ID: {$transactionId}" . PHP_EOL; - - $runQueryRequest = $requestFactory->buildRunQueryRequest($database, $cypher, $parameters); - $runQueryResponse = $client->sendRequest($runQueryRequest); - - $queryResults = json_decode($runQueryResponse->getBody()->getContents(), true); - echo "Query Results: " . json_encode($queryResults, JSON_PRETTY_PRINT) . PHP_EOL; - - // Step 3: Commit the transaction - $commitRequest = $requestFactory->buildCommitRequest($database, $transactionId); - $commitResponse = $client->sendRequest($commitRequest); - - echo "Transaction committed successfully!" . PHP_EOL; - - // Optional: Output commit response - echo "Commit Response: " . $commitResponse->getBody()->getContents() . PHP_EOL; - -} catch (Exception $e) { - echo "Error: " . $e->getMessage() . PHP_EOL; - - // Rollback the transaction in case of failure - if (isset($transactionId)) { - $rollbackRequest = $requestFactory->buildRollbackRequest($database, $transactionId); - $rollbackResponse = $client->sendRequest($rollbackRequest); - - echo "Transaction rolled back." . PHP_EOL; - echo "Rollback Response: " . $rollbackResponse->getBody()->getContents() . PHP_EOL; - } -} diff --git a/src/transaction_Script.php b/src/transaction_Script.php deleted file mode 100644 index b6b6b422..00000000 --- a/src/transaction_Script.php +++ /dev/null @@ -1,96 +0,0 @@ -post("{$neo4jAddress}/db/neo4j/tx", [ - 'headers' => [ - 'Authorization' => 'Basic ' . $credentials, - 'Content-Type' => 'application/json', - ] - ]); - - // Extract the transaction ID and cluster affinity from the response - $data = json_decode($response->getBody()->getContents(), true); - - // Check if the transaction was created and extract necessary values - if (isset($data['tx'])) { - $transactionId = $data['tx']['id']; - $clusterAffinity = $data['neo4j-cluster-affinity']; // Usually returned as part of response headers - - return [$transactionId, $clusterAffinity]; - } - - throw new Exception("Failed to start transaction or missing transaction ID in the response."); -} - -// Start the transaction and extract transactionId and clusterAffinity -list($transactionId, $clusterAffinity) = startTransaction($client, $neo4jAddress, $username, $password); - -// Create a new Transaction instance with the extracted values -$transaction = new Transaction($client, $clusterAffinity, $transactionId); - -// Function to run a Cypher query -function runQuery($transaction, $query, $parameters = []) -{ - try { - $results = $transaction->run($query, $parameters); - echo "Query Results:\n"; - foreach ($results->getRows() as $row) { - print_r($row->getData()); - } - } catch (Exception $e) { - echo "Error running query: " . $e->getMessage() . "\n"; - } -} - -// Function to commit the transaction -function commitTransaction($transaction) -{ - try { - $transaction->commit(); - echo "Transaction committed successfully.\n"; - } catch (Exception $e) { - echo "Error committing transaction: " . $e->getMessage() . "\n"; - } -} - -// Function to rollback the transaction -function rollbackTransaction($transaction) -{ - try { - $transaction->rollback(); - echo "Transaction rolled back successfully.\n"; - } catch (Exception $e) { - echo "Error rolling back transaction: " . $e->getMessage() . "\n"; - } -} - -// Example usage: running a query within the transaction -$query = "CREATE (n:Person {name: 'John Doe'}) RETURN n"; -runQuery($transaction, $query); - -// Now, let's commit the transaction -commitTransaction($transaction); - -// Running another query after commit to verify changes -$query = "MATCH (n:Person {name: 'John Doe'}) RETURN n"; -runQuery($transaction, $query); diff --git a/tests/Integration/Neo4jOGMTest.php b/tests/Integration/Neo4jOGMTest.php index b8500a61..7b2edee2 100644 --- a/tests/Integration/Neo4jOGMTest.php +++ b/tests/Integration/Neo4jOGMTest.php @@ -385,10 +385,6 @@ public function testWithPath() $this->assertEquals($expectedResult, $actual); } - - - - #[DataProvider('nullDataProvider')] public function testWithNull(string $query, array $parameters, ?string $expectedResult): void { diff --git a/tests/Integration/Neo4jQueryAPIIntegrationTest.php b/tests/Integration/Neo4jQueryAPIIntegrationTest.php index 88f49466..cf5210aa 100644 --- a/tests/Integration/Neo4jQueryAPIIntegrationTest.php +++ b/tests/Integration/Neo4jQueryAPIIntegrationTest.php @@ -32,8 +32,6 @@ class Neo4jQueryAPIIntegrationTest extends TestCase public function setUp(): void { $this->api = $this->initializeApi(); - - // Clear database and populate test data $this->clearDatabase(); $this->populateTestData(); } @@ -82,7 +80,7 @@ public function testProfileExistence(): void public function testProfileCreateQueryExistence(): void { - // Define the CREATE query + $query = " PROFILE UNWIND range(1, 100) AS i CREATE (:Person { @@ -184,23 +182,17 @@ public function testProfileCreateKnowsBidirectionalRelationshipsMock(): void $handler = HandlerStack::create($mockSack); $client = new Client(['handler' => $handler]); + $auth = Authentication::fromEnvironment(); - // Use environment variables for authentication - $auth = Authentication::basic(getenv("NEO4J_USERNAME"), getenv("NEO4J_PASSWORD")); - - // Pass both client and authentication to Neo4jQueryAPI $api = new Neo4jQueryAPI($client, $auth); - // Execute the query $result = $api->run($query); $plan = $result->getProfiledQueryPlan(); $this->assertNotNull($plan, "The result of the query should not be null."); - // Load expected data $expected = require __DIR__ . '/../resources/expected/complex-query-profile.php'; - // Assert the profiled query plan matches the expected result $this->assertEquals($expected->getProfiledQueryPlan(), $plan, "Profiled query plan does not match the expected value."); } @@ -232,9 +224,6 @@ public function testChildQueryPlanExistence(): void } - - - /** * @throws GuzzleException */ diff --git a/tests/Integration/Neo4jTransactionIntegrationTest.php b/tests/Integration/Neo4jTransactionIntegrationTest.php index bc1f338f..77868d7e 100644 --- a/tests/Integration/Neo4jTransactionIntegrationTest.php +++ b/tests/Integration/Neo4jTransactionIntegrationTest.php @@ -53,27 +53,19 @@ private function populateTestData(): void } public function testTransactionCommit(): void { - // Begin a new transaction + $tsx = $this->api->beginTransaction(); - // Generate a random name for the node $name = (string)mt_rand(1, 100000); - - // Create a node within the transaction $tsx->run("CREATE (x:Human {name: \$name})", ['name' => $name]); - // Validate that the node does not exist in the database before the transaction is committed $results = $this->api->run("MATCH (x:Human {name: \$name}) RETURN x", ['name' => $name]); $this->assertCount(0, $results); - // Validate that the node exists within the transaction $results = $tsx->run("MATCH (x:Human {name: \$name}) RETURN x", ['name' => $name]); $this->assertCount(1, $results); - // Commit the transaction $tsx->commit(); - - // Validate that the node now exists in the database $results = $this->api->run("MATCH (x:Human {name: \$name}) RETURN x", ['name' => $name]); $this->assertCount(1, $results); // Updated to expect 1 result } diff --git a/tests/Unit/AuthenticationTest.php b/tests/Unit/AuthenticationTest.php index acfa46bc..cae794cd 100644 --- a/tests/Unit/AuthenticationTest.php +++ b/tests/Unit/AuthenticationTest.php @@ -9,13 +9,10 @@ class AuthenticationTest extends TestCase { public function testBearerToken(): void { - // Mock Bearer token - $mockToken = 'mocked_bearer_token'; - // Use the Authentication::bearer method to get the Bearer authentication instance + $mockToken = 'mocked_bearer_token'; $auth = Authentication::bearer($mockToken); - // Assert: Ensure correct header and type for Bearer token $this->assertEquals("Bearer $mockToken", $auth->getHeader(), 'Bearer token mismatch.'); $this->assertEquals('Bearer', $auth->getType(), 'Type should be Bearer.'); } diff --git a/tests/Unit/Neo4jExceptionUnitTest.php b/tests/Unit/Neo4jExceptionUnitTest.php index 62d729ec..8e2ed9ff 100644 --- a/tests/Unit/Neo4jExceptionUnitTest.php +++ b/tests/Unit/Neo4jExceptionUnitTest.php @@ -26,7 +26,7 @@ public function testConstructor(): void $this->assertSame('Statement', $exception->getSubType()); $this->assertSame('SyntaxError', $exception->getName()); $this->assertSame('Invalid syntax near ...', $exception->getMessage()); - $this->assertSame(0, $exception->getCode()); // Default statusCode to 0 + $this->assertSame(0, $exception->getCode()); } /** diff --git a/tests/Unit/Neo4jRequestFactoryTest.php b/tests/Unit/Neo4jRequestFactoryTest.php index f5a11e55..708e2ec3 100644 --- a/tests/Unit/Neo4jRequestFactoryTest.php +++ b/tests/Unit/Neo4jRequestFactoryTest.php @@ -10,13 +10,14 @@ use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Utils; use Neo4j\QueryAPI\Neo4jRequestFactory; +use Neo4j\QueryAPI\Objects\Authentication; class Neo4jRequestFactoryTest extends TestCase { private $psr17Factory; private $streamFactory; - private string $baseUri = 'https://6f72daa1.databases.neo4j.io'; - private string $authHeader = 'Basic dXNlcjpwYXNzd29yZA=='; + private string $address; + private string $authHeader; /** * @throws Exception @@ -25,6 +26,11 @@ protected function setUp(): void { $this->psr17Factory = $this->createMock(RequestFactoryInterface::class); $this->streamFactory = $this->createMock(StreamFactoryInterface::class); + + $this->address = getenv('NEO4J_ADDRESS'); + + $auth = Authentication::fromEnvironment(); + $this->authHeader = $auth->getHeader(); } /** @@ -36,21 +42,16 @@ public function testBuildRunQueryRequest() $parameters = ['param1' => 'value1']; $database = 'neo4j'; - $payload = json_encode([ 'statement' => $cypher, 'parameters' => $parameters, 'includeCounters' => true, ]); - $uri = "{$this->baseUri}/db/{$database}/query/v2"; - + $uri = "{$this->address}/db/{$database}/query/v2"; $mockRequest = new Request('POST', $uri); - - $mockStream = Utils::streamFor($payload); - $this->streamFactory->method('createStream') ->willReturn($mockStream); @@ -60,7 +61,7 @@ public function testBuildRunQueryRequest() $factory = new Neo4jRequestFactory( $this->psr17Factory, $this->streamFactory, - $this->baseUri, + $this->address, $this->authHeader ); $request = $factory->buildRunQueryRequest($database, $cypher, $parameters); @@ -76,7 +77,7 @@ public function testBuildRunQueryRequest() public function testBuildBeginTransactionRequest() { $database = 'neo4j'; - $uri = "{$this->baseUri}/db/{$database}/query/v2/tx"; + $uri = "{$this->address}/db/{$database}/query/v2/tx"; $mockRequest = new Request('POST', $uri); $mockStream = Utils::streamFor(''); @@ -90,11 +91,10 @@ public function testBuildBeginTransactionRequest() $factory = new Neo4jRequestFactory( $this->psr17Factory, $this->streamFactory, - $this->baseUri + $this->address ); $request = $factory->buildBeginTransactionRequest($database); - // Assertions $this->assertEquals('POST', $request->getMethod()); $this->assertEquals($uri, (string) $request->getUri()); } @@ -106,7 +106,7 @@ public function testBuildCommitRequest() { $database = 'neo4j'; $transactionId = '12345'; - $uri = "{$this->baseUri}/db/{$database}/query/v2/tx/{$transactionId}/commit"; + $uri = "{$this->address}/db/{$database}/query/v2/tx/{$transactionId}/commit"; $mockRequest = new Request('POST', $uri); $mockStream = Utils::streamFor(''); @@ -120,7 +120,7 @@ public function testBuildCommitRequest() $factory = new Neo4jRequestFactory( $this->psr17Factory, $this->streamFactory, - $this->baseUri + $this->address ); $request = $factory->buildCommitRequest($database, $transactionId); @@ -135,7 +135,7 @@ public function testBuildRollbackRequest() { $database = 'neo4j'; $transactionId = '12345'; - $uri = "{$this->baseUri}/db/{$database}/query/v2/tx/{$transactionId}/rollback"; + $uri = "{$this->address}/db/{$database}/query/v2/tx/{$transactionId}/rollback"; $mockRequest = new Request('POST', $uri); $mockStream = Utils::streamFor(''); @@ -149,7 +149,7 @@ public function testBuildRollbackRequest() $factory = new Neo4jRequestFactory( $this->psr17Factory, $this->streamFactory, - $this->baseUri + $this->address ); $request = $factory->buildRollbackRequest($database, $transactionId); @@ -158,14 +158,15 @@ public function testBuildRollbackRequest() } /** - * Test for the createRequest method (Private method should be tested indirectly through other public methods) + * Test for createRequest method with headers and body */ public function testCreateRequestWithHeadersAndBody() { $cypher = 'MATCH (n) RETURN n'; $parameters = ['param1' => 'value1']; $database = 'neo4j'; - $uri = "{$this->baseUri}/db/{$database}/query/v2"; + $uri = "{$this->address}/db/{$database}/query/v2"; + $payload = json_encode([ 'statement' => $cypher, 'parameters' => $parameters, @@ -183,7 +184,7 @@ public function testCreateRequestWithHeadersAndBody() $factory = new Neo4jRequestFactory( $this->psr17Factory, $this->streamFactory, - $this->baseUri, + $this->address, $this->authHeader ); @@ -192,18 +193,19 @@ public function testCreateRequestWithHeadersAndBody() $this->assertEquals('application/json', $request->getHeaderLine('Content-Type')); $this->assertEquals('application/json', $request->getHeaderLine('Accept')); $this->assertEquals($this->authHeader, $request->getHeaderLine('Authorization')); - - // Assertions for body $this->assertJsonStringEqualsJsonString($payload, (string) $request->getBody()); } - + /** + * Test createRequest without Authorization header + */ public function testCreateRequestWithoutAuthorizationHeader() { $cypher = 'MATCH (n) RETURN n'; $parameters = ['param1' => 'value1']; $database = 'neo4j'; - $uri = "{$this->baseUri}/db/{$database}/query/v2"; + $uri = "{$this->address}/db/{$database}/query/v2"; + $payload = json_encode([ 'statement' => $cypher, 'parameters' => $parameters, @@ -221,15 +223,14 @@ public function testCreateRequestWithoutAuthorizationHeader() $factory = new Neo4jRequestFactory( $this->psr17Factory, $this->streamFactory, - $this->baseUri + $this->address ); $request = $factory->buildRunQueryRequest($database, $cypher, $parameters); $this->assertEquals('application/json', $request->getHeaderLine('Content-Type')); $this->assertEquals('application/json', $request->getHeaderLine('Accept')); - $this->assertEmpty($request->getHeaderLine('Authorization')); // No Authorization header - + $this->assertEmpty($request->getHeaderLine('Authorization')); $this->assertJsonStringEqualsJsonString($payload, (string) $request->getBody()); } }