Skip to content

refactor: Add cache invalidation method and tests for NestedSetsBehavior. #50

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

Merged
merged 5 commits into from
Jul 3, 2025

Conversation

terabytesoftw
Copy link
Member

@terabytesoftw terabytesoftw commented Jul 3, 2025

Q A
Is bugfix? ✔️
New feature?
Breaks BC?

Summary by CodeRabbit

  • New Features

    • Added a method to manually invalidate cached values in the nested sets behavior, ensuring data consistency after tree modifications.
  • Bug Fixes

    • Improved cache management to automatically clear outdated values after insert, update, or delete operations in the tree structure.
  • Tests

    • Introduced comprehensive tests to verify proper cache invalidation after various tree operations and manual invalidation.
    • Added tracking to confirm cache invalidation method calls during lifecycle events.
  • Chores

    • Added a new development dependency for enhanced support in development workflows.

@terabytesoftw terabytesoftw added the bug Something isn't working label Jul 3, 2025
Copy link

coderabbitai bot commented Jul 3, 2025

"""

Walkthrough

A new development dependency was added to the Composer configuration. The NestedSetsBehavior class was refactored to centralize cache and state invalidation logic into a new invalidateCache() method, which is now called after tree modification operations. Comprehensive tests were added to verify cache invalidation after various operations and manual cache clearing. Additionally, a test stub class was extended to track calls to invalidateCache() for testing purposes.

Changes

File(s) Change Summary
composer.json Added "php-forge/support": "^0.1" to require-dev.
src/NestedSetsBehavior.php Introduced invalidateCache() to centralize cache/state reset; changed visibility of cached properties to protected; refactored lifecycle event handlers to call invalidateCache().
tests/NestedSetsBehaviorTest.php Added multiple tests verifying cache invalidation after tree operations and manual invalidation; added helper methods for cache state assertions.
tests/support/stub/ExtendableNestedSetsBehavior.php Added property and override of invalidateCache() to track invocation; added methods to set internal state properties for testing.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant NestedSetsBehavior
    participant Database

    User->>NestedSetsBehavior: Perform tree operation (insert/update/delete)
    NestedSetsBehavior->>Database: Modify tree structure
    NestedSetsBehavior->>NestedSetsBehavior: invalidateCache()
    NestedSetsBehavior->>NestedSetsBehavior: Clear cached values (depth, left, right, node, operation)
Loading

Poem

In the garden of code, where the data trees grow,
A bunny hopped in, making caches let go.
With invalidateCache(), the clutter is cleared,
Each branch and each leaf, now perfectly steered.
Tests bloom like carrots, orange and bright—
Hooray for fresh roots and cache done right! 🥕
"""

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 PHPStan (2.1.15)

Note: Using configuration file /phpstan.neon.
Invalid configuration:
Unexpected item 'parameters › yii2'.


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 73b3059 and b6daebc.

📒 Files selected for processing (2)
  • tests/NestedSetsBehaviorTest.php (2 hunks)
  • tests/support/stub/ExtendableNestedSetsBehavior.php (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/support/stub/ExtendableNestedSetsBehavior.php
🧰 Additional context used
🧠 Learnings (1)
📓 Common learnings
Learnt from: terabytesoftw
PR: yii2-extensions/nested-sets-behavior#13
File: src/NestedSetsBehavior.php:145-145
Timestamp: 2025-06-29T11:22:41.889Z
Learning: The user terabytesoftw prefers to keep PRs focused and small, implementing enhancements in separate dedicated PRs rather than bundling multiple changes together.
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: phpunit-compatibility / PHP 8.2-windows-latest
  • GitHub Check: mutation / PHP 8.4-ubuntu-latest
  • GitHub Check: mutation / PHP 8.4-ubuntu-latest
🔇 Additional comments (10)
tests/NestedSetsBehaviorTest.php (10)

2287-2341: Well-structured cache invalidation test.

The test properly verifies that cache values are invalidated after makeRoot() operation and correctly repopulated with new values. Good use of helper methods and proper test structure.


2343-2371: Effective test for cache invalidation during node movement.

The test correctly verifies cache state before and after the appendTo() operation, ensuring proper cache management during node operations.


2373-2400: Comprehensive test for cache invalidation during deletion.

The test properly validates that cache is cleared when nodes are deleted, ensuring no stale cache data remains after tree modifications.


2402-2438: Good coverage of manual cache invalidation functionality.

The test verifies that the public invalidateCache() method properly clears cached values and allows them to be repopulated correctly on subsequent access.


2495-2531: Clean test for cache invalidation without tree attribute.

The test properly validates cache behavior for nodes that don't use tree attributes, providing good coverage of different configuration scenarios.


2568-2638: Excellent integration test for cache invalidation.

The test comprehensively validates cache behavior across multiple operations, ensuring proper state management throughout the lifecycle of tree modifications.


2640-2666: Targeted test for afterUpdate cache invalidation.

The test properly validates cache invalidation behavior during the afterUpdate() lifecycle event, ensuring cache consistency during update operations.


2668-2694: Good coverage of edge case with null node.

The test validates cache invalidation behavior when the cached node is null, providing important edge case coverage for robust cache management.


2696-2717: Well-designed helper method for cache verification.

The helper method provides a clean abstraction for cache state verification, reducing code duplication and improving test maintainability.


2719-2744: Effective helper method for invalidation verification.

The helper method provides consistent verification of cache invalidation across all tests, ensuring that cached values are properly cleared when expected.

✨ 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

codecov bot commented Jul 3, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 100.00%. Comparing base (dd737cd) to head (b6daebc).
Report is 1 commits behind head on main.

Additional details and impacted files
@@             Coverage Diff             @@
##                main       #50   +/-   ##
===========================================
  Coverage     100.00%   100.00%           
- Complexity       129       130    +1     
===========================================
  Files              4         4           
  Lines            518       525    +7     
===========================================
+ Hits             518       525    +7     

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

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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

🧹 Nitpick comments (1)
tests/NestedSetsBehaviorTest.php (1)

2287-2468: Consider extracting common test patterns to improve maintainability.

While the current tests are comprehensive and correct, they contain significant code duplication. Consider extracting common patterns into helper methods to improve maintainability and reduce repetition.

For example, you could create helper methods like:

private function populateAndVerifyCache($behavior): void
{
    // Common cache population and verification logic
    Assert::invokeMethod($behavior, 'getDepthValue');
    Assert::invokeMethod($behavior, 'getLeftValue');
    Assert::invokeMethod($behavior, 'getRightValue');
    
    $depthValueProperty = Assert::inaccessibleProperty($behavior, 'depthValue');
    $leftValueProperty = Assert::inaccessibleProperty($behavior, 'leftValue');
    $rightValueProperty = Assert::inaccessibleProperty($behavior, 'rightValue');
    
    self::assertNotNull($depthValueProperty, 'Depth value cache should be populated.');
    self::assertNotNull($leftValueProperty, 'Left value cache should be populated.');
    self::assertNotNull($rightValueProperty, 'Right value cache should be populated.');
}

private function verifyCacheInvalidation($behavior): void
{
    // Common cache invalidation verification logic
    $depthValueProperty = Assert::inaccessibleProperty($behavior, 'depthValue');
    $leftValueProperty = Assert::inaccessibleProperty($behavior, 'leftValue');
    $rightValueProperty = Assert::inaccessibleProperty($behavior, 'rightValue');
    
    self::assertNull($depthValueProperty, 'Depth value cache should be invalidated.');
    self::assertNull($leftValueProperty, 'Left value cache should be invalidated.');
    self::assertNull($rightValueProperty, 'Right value cache should be invalidated.');
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between dd737cd and bc14cec.

📒 Files selected for processing (3)
  • composer.json (1 hunks)
  • src/NestedSetsBehavior.php (3 hunks)
  • tests/NestedSetsBehaviorTest.php (2 hunks)
🧰 Additional context used
🧠 Learnings (1)
📓 Common learnings
Learnt from: terabytesoftw
PR: yii2-extensions/nested-sets-behavior#13
File: src/NestedSetsBehavior.php:145-145
Timestamp: 2025-06-29T11:22:41.889Z
Learning: The user terabytesoftw prefers to keep PRs focused and small, implementing enhancements in separate dedicated PRs rather than bundling multiple changes together.
🧬 Code Graph Analysis (1)
tests/NestedSetsBehaviorTest.php (3)
tests/TestCase.php (1)
  • createDatabase (93-127)
tests/support/model/MultipleTree.php (1)
  • MultipleTree (18-59)
src/NestedSetsBehavior.php (4)
  • makeRoot (860-871)
  • appendTo (339-351)
  • deleteWithChildren (561-566)
  • invalidateCache (299-306)
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: phpunit / PHP 8.4-windows-latest
  • GitHub Check: phpunit-compatibility / PHP 8.3-windows-latest
  • GitHub Check: phpunit-compatibility / PHP 8.1-windows-latest
  • GitHub Check: phpunit-compatibility / PHP 8.4-windows-latest
  • GitHub Check: phpunit-compatibility / PHP 8.2-windows-latest
  • GitHub Check: phpunit / PHP 8.3-windows-latest
  • GitHub Check: phpunit / PHP 8.1-ubuntu-latest
  • GitHub Check: mutation / PHP 8.4-ubuntu-latest
  • GitHub Check: mutation / PHP 8.4-ubuntu-latest
🔇 Additional comments (10)
composer.json (1)

20-20: LGTM - Appropriate development dependency addition.

The addition of php-forge/support as a development dependency is well-placed and uses an appropriate version constraint for supporting the new test functionality.

src/NestedSetsBehavior.php (4)

284-306: Excellent centralized cache invalidation implementation.

The invalidateCache() method effectively centralizes the logic for clearing cached attribute values and resetting internal state. The implementation correctly clears all relevant cached properties (depthValue, leftValue, rightValue, node, operation) and provides comprehensive documentation with usage examples.


196-196: Proper cache invalidation after deletion.

Calling invalidateCache() after deletion operations ensures cached values remain consistent with the modified tree structure.


236-236: Appropriate cache invalidation after insertion.

The cache invalidation after insert operations maintains consistency when new nodes are added to the tree.


268-268: Comprehensive cache invalidation in update scenarios.

The strategic placement of invalidateCache() calls in different update operation branches ensures cached values are properly cleared regardless of the operation type (make root, null node, or node movement).

Also applies to: 274-274, 281-281

tests/NestedSetsBehaviorTest.php (5)

8-8: LGTM: Appropriate testing utility import.

The PHPForge\Support\Assert import is correctly added to access protected/private properties and methods during testing, which is a standard practice for thorough unit testing.


2287-2336: Comprehensive cache invalidation test for makeRoot operation.

The test thoroughly validates that:

  1. Cache values are initially populated and match expected attributes
  2. Cache is properly invalidated (set to null) after makeRoot() operation
  3. New cache values are correctly retrieved after invalidation and reflect root node state

The test methodology using Assert to access private properties is appropriate for validating internal cache state.


2338-2379: Well-structured test for appendTo cache invalidation.

This test effectively verifies that cache invalidation occurs during node movement operations. The pattern of populating cache, performing the operation, and then verifying cache is cleared is consistent with the other cache invalidation tests.


2381-2421: Thorough validation of cache invalidation during deletion.

The test properly verifies that deleteWithChildren() operation invalidates cached values. The setup with grandchild relationships provides good coverage for deletion scenarios involving multiple nodes.


2423-2468: Excellent test for manual cache invalidation.

This test validates the direct usage of the invalidateCache() method and confirms that:

  1. Cache can be manually cleared
  2. All expected properties are set to null
  3. Subsequent value retrieval works correctly after manual invalidation

The test provides good coverage for the public API of the cache invalidation functionality.

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e62e75b and 229b75a.

📒 Files selected for processing (1)
  • tests/NestedSetsBehaviorTest.php (2 hunks)
🧰 Additional context used
🧠 Learnings (1)
📓 Common learnings
Learnt from: terabytesoftw
PR: yii2-extensions/nested-sets-behavior#13
File: src/NestedSetsBehavior.php:145-145
Timestamp: 2025-06-29T11:22:41.889Z
Learning: The user terabytesoftw prefers to keep PRs focused and small, implementing enhancements in separate dedicated PRs rather than bundling multiple changes together.
🧬 Code Graph Analysis (1)
tests/NestedSetsBehaviorTest.php (6)
tests/TestCase.php (1)
  • createDatabase (93-127)
tests/support/model/MultipleTree.php (1)
  • MultipleTree (18-59)
src/NestedSetsBehavior.php (4)
  • makeRoot (860-871)
  • appendTo (339-351)
  • deleteWithChildren (561-566)
  • invalidateCache (299-306)
tests/support/stub/ExtendableNestedSetsBehavior.php (2)
  • invalidateCache (89-94)
  • ExtendableNestedSetsBehavior (15-95)
tests/support/model/Tree.php (1)
  • Tree (17-64)
tests/support/model/ExtendableMultipleTree.php (1)
  • ExtendableMultipleTree (18-59)
⏰ Context from checks skipped due to timeout of 90000ms (11)
  • GitHub Check: phpunit-compatibility / PHP 8.2-windows-latest
  • GitHub Check: phpunit-compatibility / PHP 8.1-windows-latest
  • GitHub Check: phpunit / PHP 8.1-windows-latest
  • GitHub Check: phpunit-compatibility / PHP 8.3-windows-latest
  • GitHub Check: phpunit-compatibility / PHP 8.4-windows-latest
  • GitHub Check: phpunit-compatibility / PHP 8.2-ubuntu-latest
  • GitHub Check: phpunit-compatibility / PHP 8.1-ubuntu-latest
  • GitHub Check: mutation / PHP 8.4-ubuntu-latest
  • GitHub Check: phpunit / PHP 8.4-windows-latest
  • GitHub Check: phpunit / PHP 8.2-windows-latest
  • GitHub Check: mutation / PHP 8.4-ubuntu-latest
🔇 Additional comments (8)
tests/NestedSetsBehaviorTest.php (8)

8-8: LGTM! Appropriate imports for testing cache invalidation.

The imports are correctly added to support the new test functionality - Assert for accessing private/protected members and Behavior for type hinting.

Also applies to: 10-10


2287-2341: LGTM! Comprehensive test for cache invalidation after makeRoot operation.

The test properly verifies that:

  1. Cache values are initially populated and match the node attributes
  2. Cache is invalidated after makeRoot() operation
  3. New cache values reflect the updated root node state

2343-2371: LGTM! Well-structured test for cache invalidation during node movement.

The test effectively verifies that cache is populated after initial placement and properly invalidated when the node is moved to a different parent.


2373-2400: LGTM! Properly tests cache invalidation after delete operations.

The test ensures that cached values are cleared when a node and its children are deleted, preventing stale cache data.


2402-2438: LGTM! Validates the manual cache invalidation API.

The test properly verifies that:

  1. Manual invalidateCache() clears all cached values
  2. Values can be correctly retrieved after cache invalidation

2495-2531: LGTM! Properly tests cache invalidation for single tree tables.

The test correctly verifies cache invalidation behavior for models without a tree attribute.


2568-2638: LGTM! Comprehensive integration test for cache invalidation.

The test effectively validates the complete flow of cache invalidation when a child node is promoted to root, ensuring all cached values are properly updated.


2640-2688: LGTM! Well-structured helper methods with proper type hints.

The helper methods effectively encapsulate cache verification logic and reduce code duplication across tests. The PHPStan type hints ensure type safety.

…ull and implement `setNode` method in `ExtendableNestedSetsBehavior`.
@terabytesoftw terabytesoftw requested a review from Copilot July 3, 2025 10:47
Copy link

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

Adds a centralized cache invalidation mechanism to NestedSetsBehavior and verifies its use across tree operations through new tests and a stub behavior tracker.

  • Introduces invalidateCache() in the behavior and wires it into afterInsert, afterDelete, and afterUpdate.
  • Provides a test stub (ExtendableNestedSetsBehavior) to detect when cache invalidation is called.
  • Adds extensive PHPUnit tests to confirm cache clearing after various node operations and manual invocations.
  • Adds a new dependency for assertion helpers used in tests.

Reviewed Changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 1 comment.

File Description
tests/support/stub/ExtendableNestedSetsBehavior.php Extends behavior to flag when invalidateCache() is invoked and adds setters for internal state.
tests/NestedSetsBehaviorTest.php Covers automatic and manual cache invalidation after all key nested-set operations.
src/NestedSetsBehavior.php Implements invalidateCache() and replaces manual state resets in lifecycle hooks.
composer.json Adds php-forge/support dependency for Assert utilities in tests.
Comments suppressed due to low confidence (1)

tests/NestedSetsBehaviorTest.php:8

  • The namespace PHPForge\Support\Assert may not match the package's actual namespace (often PhpForge\Support). Verify the correct casing and namespace so the class can be autoloaded.
use PHPForge\Support\Assert;

@terabytesoftw terabytesoftw merged commit bf7793a into main Jul 3, 2025
45 checks passed
@terabytesoftw terabytesoftw deleted the fix-mini-41 branch July 3, 2025 10:51
@terabytesoftw terabytesoftw changed the title feat: Add cache invalidation method and tests for NestedSetsBehavior. rafactor: Add cache invalidation method and tests for NestedSetsBehavior. Jul 3, 2025
@terabytesoftw terabytesoftw changed the title rafactor: Add cache invalidation method and tests for NestedSetsBehavior. refactor: Add cache invalidation method and tests for NestedSetsBehavior. Jul 3, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy