Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add dependencyIndex to the message of the Unbound exception #113

Merged
merged 3 commits into from
Oct 21, 2024

Conversation

jingu
Copy link
Contributor

@jingu jingu commented Oct 18, 2024

  • Unbound例外のメッセージからDependencyIndexの記述がなくなっており dc06f16 、BEAR.ResourceでリソースファイルのNot Foundが検知できない問題が発生しています。
  • 例外のメッセージにDependencyIndexを加えるようにしました。

Summary by CodeRabbit

  • Bug Fixes

    • Improved error handling for missing compiled script files by including the dependency index in the error message.
    • Corrected a typo in the method signature from setQaulifier to setQualifier, ensuring consistent naming.
  • Tests

    • Enhanced test assertions to check for expected content in generated code, allowing for variations in format.

@koriym
Copy link
Member

koriym commented Oct 18, 2024

この変更によるエラー失敗ではないですが、エラーでCIが落ちてますね。元々のテストの書き方の問題でもあるようですが...

@jingu
Copy link
Contributor Author

jingu commented Oct 18, 2024

そうなんです。php-parserのphp>=7.1対応の4系と、php>=7.4対応の5系で出力されるコードが異なってしまっているようで、どうするのが良さそうでしょうか?

@koriym
Copy link
Member

koriym commented Oct 19, 2024

arrayや鉤括弧を確認する必要もないのでその確認の詳細度合いが過ぎてるところはもう削除してしまっていいと思います。

Copy link

codecov bot commented Oct 21, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 100.00%. Comparing base (50e063e) to head (67bcd8e).
Report is 7 commits behind head on 1.x.

Additional details and impacted files
@@              Coverage Diff              @@
##                1.x      #113      +/-   ##
=============================================
+ Coverage     99.86%   100.00%   +0.13%     
  Complexity      215       215              
=============================================
  Files            28        28              
  Lines           740       739       -1     
=============================================
  Hits            739       739              
+ Misses            1         0       -1     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@jingu
Copy link
Contributor Author

jingu commented Oct 21, 2024

@koriym
修正しました!

lowerstとhighestで、バックスラッシュを \\ とエスケープするパターン(lowest)、 \ そのまま扱うパターン(highest) という違いもありましたので、文字列を置換して対応するように変更しました。

@jingu jingu marked this pull request as ready for review October 21, 2024 02:06
Copy link

coderabbitai bot commented Oct 21, 2024

Walkthrough

The changes in this pull request involve modifications to three files: CompileInjector.php, DependencyCode.php, and DependencyCompilerTest.php. In CompileInjector.php, the error handling in the getInstanceFile method has been updated to include the $dependencyIndex in exception messages. The DependencyCode.php file sees the addition of a @psalm-suppress annotation and a correction in the method signature and parameter naming for setQualifier. Lastly, DependencyCompilerTest.php has updated assertions in multiple test methods to check for substring containment rather than exact matches, improving test flexibility.

Changes

File Change Summary
src/CompileInjector.php Modified getInstanceFile method to include $dependencyIndex in the exception message when a compiled script file does not exist.
src/DependencyCode.php Added @psalm-suppress InvalidArgument annotation in getProviderCode method. Corrected method signature and parameter name from setQaulifier and $qualifer to setQualifier and $qualifier.
tests/DependencyCompilerTest.php Updated assertions in testInstanceCompileArray, testDependencyCompile, and testDependencyObjectInstanceCompile methods from exact string checks to checks for substring containment, enhancing test robustness.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CompileInjector
    participant DependencyCode
    participant DependencyCompilerTest

    User->>CompileInjector: Request to compile file
    CompileInjector->>CompileInjector: Check if file exists
    alt File does not exist
        CompileInjector-->>User: Throw Unbound exception with $dependencyIndex
    else File exists
        CompileInjector-->>User: Return compiled file
    end

    User->>DependencyCode: Request provider code
    DependencyCode->>DependencyCode: Suppress InvalidArgument warnings
    DependencyCode-->>User: Return provider code

    User->>DependencyCompilerTest: Run tests
    DependencyCompilerTest->>DependencyCompilerTest: Execute assertions
    DependencyCompilerTest-->>User: Return test results
Loading

🐇 In the code we hop and play,
Errors caught in a clearer way.
Qualifiers set with names so bright,
Tests now check for content right.
With each change, we leap and cheer,
For clarity and code so dear! 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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

@koriym koriym merged commit 69ad4bf into ray-di:1.x Oct 21, 2024
22 checks passed
@koriym
Copy link
Member

koriym commented Oct 21, 2024

@jingu GJ!

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

🧹 Outside diff range and nitpick comments (4)
tests/DependencyCompilerTest.php (2)

83-90: Improved test flexibility with complex string handling.

The change from assertSame to assertContains with multiple possible outcomes is appropriate. It addresses the discrepancies in code representation between different PHP versions, aligning with the PR objectives. The complex string replacement handles both array syntax differences and backslash escaping issues effectively.

However, the readability of this section could be improved. Consider extracting the string replacement logic into a separate helper method to enhance clarity.

Here's a suggested refactoring to improve readability:

private function getExpectedStrings(string $expected): array
{
    $modernSyntax = str_replace(
        'array(\'Ray\\Compiler\\FakeCar\', \'setHandle\', \'handle\')',
        '[\'Ray\\Compiler\\FakeCar\', \'setHandle\', \'handle\']',
        str_replace('\\\\', '\\', $expected)
    );
    return [$modernSyntax, $expected];
}

// In the test method
$this->assertContains((string) $code, $this->getExpectedStrings($expected));

Line range hint 1-168: Overall assessment: Effective improvements in test flexibility

The changes in this file consistently improve test flexibility to accommodate differences between PHP versions, particularly in array syntax and serialized object representation. This aligns well with the PR objectives and addresses the issues discussed in the PR comments.

To further enhance the maintainability of these tests, consider:

  1. Extracting the string replacement logic into helper methods, as suggested earlier.
  2. Adding comments explaining why these flexible assertions are necessary, referencing the PHP version discrepancies.
  3. If this pattern is used in multiple test files, consider creating a trait with these helper methods to promote code reuse.

These suggestions will improve code organization, readability, and make it easier for future contributors to understand and maintain these tests.

src/DependencyCode.php (1)

Remaining occurrences of 'setQaulifier' found.

Please update the following locations to correct the typo:

  • src/DependencyCode.php
  • src/FunctionCode.php
🔗 Analysis chain

Line range hint 79-82: Approve typo correction and suggest verification.

The typo correction in the method name and parameter improves code consistency and readability. Good catch!

To ensure this change doesn't break existing code, please verify all calls to this method have been updated. Run the following script to check for any remaining occurrences of the old method name:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining occurrences of 'setQaulifier'
rg 'setQaulifier' --type php

Length of output: 219

src/CompileInjector.php (1)

171-171: Improved error message with dependency context.

The change enhances the error message by including the $dependencyIndex and referencing the compile log. This aligns with the PR objective and improves error reporting.

Consider using a constant for the log file name ('_compile.log') to improve maintainability:

- throw new Unbound(sprintf('[%s] See compile log %s', $dependencyIndex, $this->scriptDir . '/_compile.log'));
+ const COMPILE_LOG = '_compile.log';
+ throw new Unbound(sprintf('[%s] See compile log %s', $dependencyIndex, $this->scriptDir . '/' . self::COMPILE_LOG));

This change would make it easier to update the log file name in the future if needed.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between b4ad323 and 67bcd8e.

⛔ Files ignored due to path filters (1)
  • vendor-bin/tools/composer.lock is excluded by !**/*.lock
📒 Files selected for processing (3)
  • src/CompileInjector.php (1 hunks)
  • src/DependencyCode.php (1 hunks)
  • tests/DependencyCompilerTest.php (3 hunks)
🧰 Additional context used
🔇 Additional comments (4)
tests/DependencyCompilerTest.php (2)

56-59: Improved test flexibility for array representation.

The change from assertSame to assertContains with multiple possible outcomes is a good approach. It addresses the discrepancies in array representation between different PHP versions (7.1 vs 7.4) mentioned in the PR discussion. This modification enhances the test's robustness and aligns with the PR objectives.


133-136: Improved test flexibility for serialized object representation.

The change from assertSame to assertContains with multiple possible outcomes is a good approach. It addresses potential discrepancies in serialized object representation between different PHP versions. This modification enhances the test's robustness and aligns with the PR objectives.

src/DependencyCode.php (1)

153-153: Clarify the need for @psalm-suppress InvalidArgument.

The addition of this suppression annotation suggests that Psalm is detecting a potential type mismatch. While suppressing the warning allows the code to pass static analysis, it might hide an underlying issue.

Could you please provide more context on why this suppression is necessary? Are there alternatives we could explore to address the underlying issue instead of suppressing the warning?

To help understand the context, please run the following command to see Psalm's output for this file:

This will help us understand the specific warning that Psalm is raising and potentially find a way to resolve it without suppression.

src/CompileInjector.php (1)

Line range hint 1-214: Overall impact: Improved error reporting without side effects.

The change to the error message in getInstanceFile method enhances the debugging experience by providing more context about the unbound dependency. This modification:

  1. Aligns with the PR objectives.
  2. Doesn't alter the method's logic or return value.
  3. Improves error reporting without introducing new dependencies or failure modes.
  4. Is consistent with the class's responsibility of managing compiled scripts.

No additional changes are required in other parts of the class or file.

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