Skip to content

Conversation

@ItzNotABug
Copy link
Member

@ItzNotABug ItzNotABug commented Jul 19, 2025

  1. Checks the first 5 rows for ,, ;, \t, | and decides the best delimiter for further CSV process.
  2. Added tests to verify the logic, didn't copy the method to avoid duplicacy. Reflection should be fine for tests!

Summary by CodeRabbit

  • New Features

    • Improved CSV import to automatically detect and handle various delimiters (comma, semicolon, tab, pipe) for more flexible CSV file support.
  • Tests

    • Added tests to verify accurate detection of CSV delimiters across multiple file formats and edge cases.

@ItzNotABug ItzNotABug self-assigned this Jul 19, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 19, 2025

Walkthrough

Delimiter detection for CSV files is introduced in the CSV source class. The withCsvStream method now detects and passes the CSV delimiter to its callback, which is used in all fgetcsv operations. A new private method implements the delimiter detection logic. Comprehensive unit tests are added to verify delimiter detection across various CSV formats.

Changes

File(s) Change Summary
src/Migration/Sources/CSV.php Added delimiter detection logic; updated withCsvStream to provide delimiter to callback; adjusted exportRows to use detected delimiter; updated PHPDoc.
tests/Migration/Unit/General/CSVTest.php Added new PHPUnit test class for delimiter detection, with tests for multiple delimiter scenarios and edge cases.

Sequence Diagram(s)

sequenceDiagram
    participant Test as CSVTest
    participant CSV as CSV
    participant File as CSV File Stream

    Test->>File: Open test CSV file
    Test->>CSV: detectDelimiter(File stream)
    CSV->>File: Read sample lines
    CSV->>CSV: Analyze lines for delimiter
    CSV-->>Test: Return detected delimiter
    Test->>Test: Assert detected delimiter matches expected
    Test->>File: Close file
Loading
sequenceDiagram
    participant App as Application
    participant CSV as CSV
    participant File as CSV File Stream

    App->>CSV: withCsvStream(callback)
    CSV->>File: Open CSV file
    CSV->>File: Sample lines for delimiter
    CSV->>CSV: Detect delimiter
    CSV->>App: Invoke callback(File stream, detected delimiter)
    App->>File: Parse rows using detected delimiter
Loading

Poem

In the warren where data flows free,
A clever new trick for CSV!
No more guessing what splits the line—
Comma, tab, or pipe, all work fine.
With tests to ensure it’s all just right,
The rabbit hops on, parsing with delight!
🐇📄✨

✨ 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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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
Contributor

@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: 0

🧹 Nitpick comments (1)
src/Migration/Sources/CSV.php (1)

412-518: Algorithm is well-designed but could benefit from refactoring.

The delimiter detection algorithm is mathematically sound and handles edge cases well. The scoring system combining consistency and quality metrics is effective. However, the method is quite complex and could be improved.

Consider breaking down this method into smaller, focused functions:

+    private function sampleLines($stream, int $maxLines = 5): array
+    {
+        $sampleLines = [];
+        for ($i = 0; $i < $maxLines && !feof($stream); $i++) {
+            $line = fgets($stream);
+            if ($line === false) break;
+            
+            $line = trim($line);
+            if (empty($line)) {
+                $i--;
+                continue;
+            }
+            $sampleLines[] = $line;
+        }
+        return $sampleLines;
+    }
+
+    private function calculateDelimiterScore(string $delimiter, array $sampleLines): float
+    {
+        // Extract the scoring logic here
+    }

This would improve readability and testability of individual components.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 973a4da and 00a4c58.

⛔ Files ignored due to path filters (7)
  • tests/Migration/resources/csv/comma.csv is excluded by !**/*.csv
  • tests/Migration/resources/csv/empty.csv is excluded by !**/*.csv
  • tests/Migration/resources/csv/pipe.csv is excluded by !**/*.csv
  • tests/Migration/resources/csv/quoted_fields.csv is excluded by !**/*.csv
  • tests/Migration/resources/csv/semicolon.csv is excluded by !**/*.csv
  • tests/Migration/resources/csv/single_column.csv is excluded by !**/*.csv
  • tests/Migration/resources/csv/tab.csv is excluded by !**/*.csv
📒 Files selected for processing (2)
  • src/Migration/Sources/CSV.php (5 hunks)
  • tests/Migration/Unit/General/CSVTest.php (1 hunks)
🔇 Additional comments (4)
src/Migration/Sources/CSV.php (2)

183-183: LGTM: Callback signature and fgetcsv usage correctly updated.

The callback signature properly accepts the delimiter parameter, and the fgetcsv call correctly uses the detected delimiter with the separator parameter. This ensures consistent parsing behavior across different CSV formats.

Also applies to: 193-193


317-317: LGTM: Method signature and delimiter detection integration.

The PHPDoc correctly documents the new callback signature, and the delimiter detection is properly integrated before invoking the callback. The stream handling remains consistent.

Also applies to: 339-342

tests/Migration/Unit/General/CSVTest.php (2)

15-26: LGTM: Appropriate use of reflection for testing private method.

Using reflection to test the private delimiter method is the right approach here. It avoids code duplication while ensuring the actual implementation is tested. The newInstanceWithoutConstructor() method properly bypasses constructor dependencies.


28-48: All CSV test resources validated
All required .csv files are present under tests/resources/csv/ and their contents match the expected delimiters (comma, semicolon, tab, pipe) with correct fallback behavior for single-column and empty files. No further action needed.

@abnegate abnegate merged commit f463292 into main Jul 21, 2025
4 checks passed
@abnegate abnegate deleted the csv-delimeter branch July 21, 2025 07:06
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.

3 participants