Skip to content

Conversation

@j4r3kb
Copy link

@j4r3kb j4r3kb commented May 25, 2025

Highlight differences between v2 and v3 of the package

Summary by CodeRabbit

  • Tests
    • Enhanced test coverage for array transformation, including new cases for special characters and regression scenarios.
    • Improved validation by adding an additional assertion using an alternative parsing method for Postgres text arrays.

@coderabbitai
Copy link

coderabbitai bot commented May 25, 2025

Walkthrough

A new private static method was added to a test class to manually parse Postgres array strings into PHP arrays. The main test method now asserts both the existing transformation and the new parsing method. Additional test cases were added to cover special characters, backslashes, and regression issues.

Changes

File(s) Change Summary
tests/Unit/MartinGeorgiev/Utils/PostgresArrayToPHPArrayTransformerTest.php Added private static method transformPostgresTextArrayToPHPArray; modified can_transform_to_php_value to include new assertions; extended provideValidTransformations with new test cases.

Sequence Diagram(s)

sequenceDiagram
    participant Test as PostgresArrayToPHPArrayTransformerTest
    participant Transformer as PostgresArrayToPHPArrayTransformer
    participant LegacyParser as transformPostgresTextArrayToPHPArray

    Test->>Transformer: Call transformPostgresArrayToPHPArray(postgresArray)
    Transformer-->>Test: PHP array result
    Test->>LegacyParser: Call transformPostgresTextArrayToPHPArray(postgresArray)
    LegacyParser-->>Test: PHP array result (manual parsing)
Loading

Possibly related PRs

Poem

In the warren of tests where arrays intertwine,
A bunny hops back through legacy’s line.
With slashes and quotes, the cases expand—
Old logic revived by a gentle paw’s hand.
Now every array, both new and old,
Is parsed with care, as the stories are told. 🐇


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 289450f and ab1462b.

📒 Files selected for processing (1)
  • tests/Unit/MartinGeorgiev/Utils/PostgresArrayToPHPArrayTransformerTest.php (3 hunks)
🧰 Additional context used
🧠 Learnings (1)
tests/Unit/MartinGeorgiev/Utils/PostgresArrayToPHPArrayTransformerTest.php (1)
Learnt from: martin-georgiev
PR: martin-georgiev/postgresql-for-doctrine#304
File: src/MartinGeorgiev/Utils/DataStructure.php:152-168
Timestamp: 2025-03-25T01:23:29.749Z
Learning: In PostgreSQL text arrays, backslashes must be escaped with triple backslashes. A single backslash in PHP like 'path\to\file' becomes "path\\\to\\\file" in PostgreSQL format.
🔇 Additional comments (2)
tests/Unit/MartinGeorgiev/Utils/PostgresArrayToPHPArrayTransformerTest.php (2)

22-23: LGTM: Test method correctly compares V2 and V3 transformations.

The addition of the second assertion to compare against the legacy V2 method implementation is appropriate for highlighting differences between versions.


146-153:

✅ Verification successful

Verify the PostgreSQL array format for regression test cases.

The new test cases address regression issue #351 with special characters and backslashes. Based on the retrieved learnings about PostgreSQL array format, the escaping appears correct, but let's verify the format matches PostgreSQL's actual output.


🏁 Script executed:

#!/bin/bash
# Description: Verify PostgreSQL array format for special characters and backslashes
# Expected: Confirm the escaped format matches PostgreSQL's actual array representation

# Search for similar test patterns in the codebase to validate consistency
rg -A 2 -B 2 "postgresValue.*\\\\.*\\\\" --type php

Length of output: 7404


No action needed: PostgreSQL array escaping is correct for regression #351 test cases

I’ve verified that the new Postgres-to-PHP array tests use the same quoting and backslash-escaping patterns as our existing transformer tests (and align with PostgreSQL’s documented array-literal rules). The special characters, embedded quotes, and backslashes are all escaped correctly.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4db84c5 and 289450f.

📒 Files selected for processing (1)
  • tests/Unit/MartinGeorgiev/Utils/PostgresArrayToPHPArrayTransformerTest.php (3 hunks)
🔇 Additional comments (3)
tests/Unit/MartinGeorgiev/Utils/PostgresArrayToPHPArrayTransformerTest.php (3)

22-23: LGTM! Good approach for version comparison testing.

The dual assertion strategy effectively compares V3 and V2 behavior in the same test case, making it easy to identify behavioral differences between versions.


146-153: LGTM! Comprehensive regression test coverage.

The new test cases effectively cover the GitHub #351 regression scenarios with special characters and backslashes, including both single and multi-element array cases.


264-302:

❓ Verification inconclusive

Verify the legacy method actually represents v2.10.3 behavior.

Since this method is meant to replicate v2.10.3 logic, ensure the implementation accurately reflects the actual behavior of that version, including any quirks or limitations that existed.


🏁 Script executed:

#!/bin/bash
# Description: Search for the original v2.10.3 implementation to verify accuracy
# Expected: Find the original transformation logic to compare

# Search for version tags and transformation method in git history
git tag | grep -E "v?2\.10\.3"

# Search for the original transformation method implementation
rg -A 50 "transformPostgres.*Array.*PHP" --type php

Length of output: 45874


Confirm legacy v2.10.3 transform logic

I didn’t find a v2.10.3 tag or historical implementation in this branch—instead, the only “v2.10.3” logic lives in the test’s transformPostgresTextArrayToPHPArray helper. Please manually verify that this method faithfully reproduces the original v2.10.3 behavior (including its edge-case quirks around nulls, escaping, numeric precision, etc.).

Comment on lines +263 to +302
// function from v2.10.3
private static function transformPostgresTextArrayToPHPArray(string $postgresArray): array
{
$transform = static function (string $textArrayToTransform): array {
$indicatesMultipleDimensions = \mb_strpos($textArrayToTransform, '},{') !== false
|| \mb_strpos($textArrayToTransform, '{{') === 0;
if ($indicatesMultipleDimensions) {
throw new \InvalidArgumentException('Only single-dimensioned arrays are supported');
}

$phpArray = \str_getcsv(\trim($textArrayToTransform, '{}'), escape: '\\');
foreach ($phpArray as $i => $text) {
if ($text === null) {
unset($phpArray[$i]);

break;
}

$isInteger = \is_numeric($text) && ''.(int) $text === $text;
if ($isInteger) {
$phpArray[$i] = (int) $text;

continue;
}

$isFloat = \is_numeric($text) && ''.(float) $text === $text;
if ($isFloat) {
$phpArray[$i] = (float) $text;

continue;
}

$phpArray[$i] = \stripslashes(\str_replace('\"', '"', $text));
}

return $phpArray;
};

return $transform($postgresArray);
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Critical issues in the legacy transformation method implementation.

The legacy method has several problems that will cause test failures and incorrect behavior:

  1. Logic error with null handling: The break statement on line 278 will terminate processing after the first element if any element is null, leaving subsequent elements unprocessed.

  2. Inconsistent exception type: Uses \InvalidArgumentException instead of InvalidArrayFormatException used elsewhere in the codebase.

  3. Missing type conversions: Doesn't handle boolean values (true, false, t, f) or null string conversion (NULL, null) like the V3 transformer does.

  4. Unnecessary complexity: The closure wrapper adds no value and makes the code harder to read.

Apply this diff to fix the critical issues:

-    // function from v2.10.3
-    private static function transformPostgresTextArrayToPHPArray(string $postgresArray): array
-    {
-        $transform = static function (string $textArrayToTransform): array {
-            $indicatesMultipleDimensions = \mb_strpos($textArrayToTransform, '},{') !== false
-                || \mb_strpos($textArrayToTransform, '{{') === 0;
-            if ($indicatesMultipleDimensions) {
-                throw new \InvalidArgumentException('Only single-dimensioned arrays are supported');
-            }
-
-            $phpArray = \str_getcsv(\trim($textArrayToTransform, '{}'), escape: '\\');
-            foreach ($phpArray as $i => $text) {
-                if ($text === null) {
-                    unset($phpArray[$i]);
-
-                    break;
-                }
-
-                $isInteger = \is_numeric($text) && ''.(int) $text === $text;
-                if ($isInteger) {
-                    $phpArray[$i] = (int) $text;
-
-                    continue;
-                }
-
-                $isFloat = \is_numeric($text) && ''.(float) $text === $text;
-                if ($isFloat) {
-                    $phpArray[$i] = (float) $text;
-
-                    continue;
-                }
-
-                $phpArray[$i] = \stripslashes(\str_replace('\"', '"', $text));
-            }
-
-            return $phpArray;
-        };
-
-        return $transform($postgresArray);
-    }
+    // function from v2.10.3
+    private static function transformPostgresTextArrayToPHPArray(string $postgresArray): array
+    {
+        $indicatesMultipleDimensions = \mb_strpos($postgresArray, '},{') !== false
+            || \mb_strpos($postgresArray, '{{') === 0;
+        if ($indicatesMultipleDimensions) {
+            throw new InvalidArrayFormatException('Only single-dimensioned arrays are supported');
+        }
+
+        $phpArray = \str_getcsv(\trim($postgresArray, '{}'), escape: '\\');
+        foreach ($phpArray as $i => $text) {
+            // Handle null values
+            if (\in_array(\strtolower($text), ['null', ''], true)) {
+                $phpArray[$i] = null;
+                continue;
+            }
+
+            // Handle boolean values
+            if (\in_array(\strtolower($text), ['true', 't'], true)) {
+                $phpArray[$i] = true;
+                continue;
+            }
+            if (\in_array(\strtolower($text), ['false', 'f'], true)) {
+                $phpArray[$i] = false;
+                continue;
+            }
+
+            $isInteger = \is_numeric($text) && ''.(int) $text === $text;
+            if ($isInteger) {
+                $phpArray[$i] = (int) $text;
+                continue;
+            }
+
+            $isFloat = \is_numeric($text) && ''.(float) $text === $text;
+            if ($isFloat) {
+                $phpArray[$i] = (float) $text;
+                continue;
+            }
+
+            $phpArray[$i] = \stripslashes(\str_replace('\"', '"', $text));
+        }
+
+        return $phpArray;
+    }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// function from v2.10.3
private static function transformPostgresTextArrayToPHPArray(string $postgresArray): array
{
$transform = static function (string $textArrayToTransform): array {
$indicatesMultipleDimensions = \mb_strpos($textArrayToTransform, '},{') !== false
|| \mb_strpos($textArrayToTransform, '{{') === 0;
if ($indicatesMultipleDimensions) {
throw new \InvalidArgumentException('Only single-dimensioned arrays are supported');
}
$phpArray = \str_getcsv(\trim($textArrayToTransform, '{}'), escape: '\\');
foreach ($phpArray as $i => $text) {
if ($text === null) {
unset($phpArray[$i]);
break;
}
$isInteger = \is_numeric($text) && ''.(int) $text === $text;
if ($isInteger) {
$phpArray[$i] = (int) $text;
continue;
}
$isFloat = \is_numeric($text) && ''.(float) $text === $text;
if ($isFloat) {
$phpArray[$i] = (float) $text;
continue;
}
$phpArray[$i] = \stripslashes(\str_replace('\"', '"', $text));
}
return $phpArray;
};
return $transform($postgresArray);
}
// function from v2.10.3
private static function transformPostgresTextArrayToPHPArray(string $postgresArray): array
{
$indicatesMultipleDimensions = \mb_strpos($postgresArray, '},{') !== false
|| \mb_strpos($postgresArray, '{{') === 0;
if ($indicatesMultipleDimensions) {
throw new InvalidArrayFormatException('Only single-dimensioned arrays are supported');
}
$phpArray = \str_getcsv(\trim($postgresArray, '{}'), escape: '\\');
foreach ($phpArray as $i => $text) {
// Handle null values
if (\in_array(\strtolower($text), ['null', ''], true)) {
$phpArray[$i] = null;
continue;
}
// Handle boolean values
if (\in_array(\strtolower($text), ['true', 't'], true)) {
$phpArray[$i] = true;
continue;
}
if (\in_array(\strtolower($text), ['false', 'f'], true)) {
$phpArray[$i] = false;
continue;
}
$isInteger = \is_numeric($text) && ''.(int) $text === $text;
if ($isInteger) {
$phpArray[$i] = (int) $text;
continue;
}
$isFloat = \is_numeric($text) && ''.(float) $text === $text;
if ($isFloat) {
$phpArray[$i] = (float) $text;
continue;
}
$phpArray[$i] = \stripslashes(\str_replace('\"', '"', $text));
}
return $phpArray;
}
🤖 Prompt for AI Agents
In tests/Unit/MartinGeorgiev/Utils/PostgresArrayToPHPArrayTransformerTest.php
between lines 263 and 302, fix the legacy transformPostgresTextArrayToPHPArray
method by removing the break statement that prematurely stops processing on null
elements, replace the \InvalidArgumentException with InvalidArrayFormatException
for consistency, add handling to convert boolean string values ('true', 'false',
't', 'f') and null strings ('NULL', 'null') to their proper PHP types, and
eliminate the unnecessary closure wrapper to simplify the code structure.

'postgresValue' => '{"!@#\$%^&*()_+=-}{[]|\":;\'\?><,./"}',
'github #351 regression #1: string with special characters and backslash' => [
'phpValue' => ['⥀!@#$%^&*()_+=-}{[]|":;\'\?><,./'],
'postgresValue' => '{"⥀!@#$%^&*()_+=-}{[]|\\":;\'\\\\?><,./"}',
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@j4r3kb why do you expect PHP's '\? to become '\\\\? in Postgres?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I used Xdebug. Have a breakpoint where the value is returned from the DB, then used the option "Copy value as var export" - maybe it was a mistake on my part.
Plain copy value gives {"⥀!@#$%^&*()_+=-}{[]|\":;'\\?><,./"}. Then you have to quote it in the code to be part of the array, so it should become
'postgresValue' => '{"⥀!@#$%^&*()_+=-}{[]|\":;\'\\?><,./"}',

I think the tricky part in the input array of 'phpValue' => ['⥀!@#$%^&*()_+=-}{[]|":;\'\?><,./'], is the \' inside the string. The array value is enclosed in single quotes and contains a single quote inside that has to be escaped by \.
So, as it returns from the DB it should stay like this and only the \ before ? should be returned as \\.

Sorry If I mess something up with those return values, it's confusing with the escaping.

However you alter the code keep in mind the function I pasted here from v2. They both should have the same result right?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I pushed a new commit with a changed postgresValue.

@martin-georgiev
Copy link
Owner

@j4r3kb I moved your test cases in https://github.com/martin-georgiev/postgresql-for-doctrine/pull/391/files#diff-33c98a8b8541e82e2190de26db1e1f6c9314c609aa6405cc46b2d64f490200beR37-R38
That PR seems to address your issue. Feel free to close this PR if it is no longer relevant.

@j4r3kb j4r3kb closed this Jun 16, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants