Skip to content

Conversation

@Henridv
Copy link
Contributor

@Henridv Henridv commented Jun 29, 2025

When an Eloquent model gets serialized, it clears the class cast cache, see here. This causes issues with how casting currently works in this library.

Here, a Geometry type attribute is cast from the model representation to the WKT representation, when set. But when fetching from the DB, it casts from WKB to the model representation.

When the class cast cache is populated, this is not a problem. After being set, the cached model representation will be fetched. However, without the cache, when fetching the attribute, it needs to be cast, which it can't because it expects WKB, but gets WKT, resulting in:

Bad endian byte value 83.

  at src/IO/Parser/WKB/WKBParser.php:125
    121▕
    122▕         $byteOrder = match ($endianValue) {
    123▕             0 => ByteOrder::bigEndian,
    124▕             1 => ByteOrder::littleEndian,
  ➜ 125▕             default => throw new RuntimeException(sprintf('Bad endian byte value %s.', json_encode($endianValue))),
    126▕         };
    127▕
    128▕         $this->scanner->setByteOrder($byteOrder);
    129▕     }

  1   src/IO/Parser/WKB/WKBParser.php:125
  2   src/IO/Parser/WKB/WKBParser.php:38

This situation presents itself when using queueable anonymous event listeners on the model.

This change fixes this issue.

In the meantime, it could be solved by doing $model->refresh() to fetch the WKB representation from the database.

Summary by CodeRabbit

  • New Features

    • Added support for parsing geometry data from both WKB (Well-Known Binary) and WKT (Well-Known Text) formats.
  • Tests

    • Added a test to verify that geometry data remains accessible and accurate after model serialization and reload.
  • Bug Fixes

    • Fixed issues with geometry data casts after serialization, improving compatibility with queued event listeners.

@coderabbitai
Copy link

coderabbitai bot commented Jun 29, 2025

Caution

Review failed

The pull request is closed.

📝 Walkthrough

Walkthrough

The GeometryCast class was updated to support parsing geometry data from both WKB and WKT formats by conditionally selecting the parser based on input format. Additionally, a new test was introduced to ensure that a model's geometry property remains accessible and correct after serialization and retrieval. The changelog was updated to document a fix related to casts after serialization affecting queueable anonymous event listeners.

Changes

File(s) Change Summary
src/Cast/GeometryCast.php Added WKT parsing support, introduced WKTParser property, updated constructor and parsing logic to select parser based on input format.
tests/Models/LocationTest.php Added test to verify geometry property accessibility after model serialization and reload.
CHANGELOG.md Added "Fixed" section documenting a fix for cast usage after serialization related to queueable anonymous event listeners.

Poem

In fields of WKT and WKB,
Geometry now parses with glee.
A rabbit hops through code anew,
Ensuring points stay tried and true.
Serialization? No fright!
The model’s shape remains just right. 🐇✨


📜 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 4305097 and 62bf51a.

📒 Files selected for processing (2)
  • CHANGELOG.md (1 hunks)
  • src/Cast/GeometryCast.php (3 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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 auto-generate unit tests to generate unit tests for 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

@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 (2)
src/Cast/GeometryCast.php (1)

52-57: Excellent solution for distinguishing WKB from WKT formats.

The ctype_xdigit() approach is clever and should reliably distinguish between:

  • WKB data (hexadecimal strings from database)
  • WKT data (text format like "POINT(1 2)" after serialization)

This directly addresses the core issue where serialization clears the cast cache and WKT gets interpreted as WKB.

Consider adding a comment to document this detection logic:

+        // Detect format: WKB data is hex-encoded, WKT is human-readable text
         if (ctype_xdigit($value)) {
             $geometry = $this->wkbParser->parse($value);
         } else {
             $geometry = $this->wktParser->parse($value);
         }
tests/Models/LocationTest.php (1)

68-86: Excellent test coverage for the serialization bug fix.

This test directly validates the core issue described in the PR:

  1. Model serialization clears the cast cache
  2. Geometry attribute access should still work correctly
  3. Both in-memory and fresh retrieval scenarios are tested

The test effectively ensures that the conditional WKB/WKT parsing logic in GeometryCast handles the cache clearing scenario properly.

Consider a minor optimization by combining model creation and saving:

-    $location = Location::make([
+    $location = Location::create([
         'name' => 'Test Location',
         'location' => Point::makeGeodetic(51.087, 8.76),
     ]);
-    $location->save();
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6353ce8 and 4305097.

📒 Files selected for processing (2)
  • src/Cast/GeometryCast.php (3 hunks)
  • tests/Models/LocationTest.php (1 hunks)
🧰 Additional context used
🪛 PHPMD (2.15.0)
src/Cast/GeometryCast.php

33-33: Avoid using static access to class '\Illuminate\Support\Facades\App' in method '__construct'. (Clean Code Rules)

(StaticAccess)


34-34: Avoid using static access to class '\Illuminate\Support\Facades\App' in method '__construct'. (Clean Code Rules)

(StaticAccess)


55-57: The method get uses an else expression. Else clauses are basically not necessary and you can simplify the code by not using them. (Clean Code Rules)

(ElseExpression)

🔇 Additional comments (3)
src/Cast/GeometryCast.php (3)

9-9: LGTM: WKTParser import added correctly.

The import is properly placed and follows the existing pattern.


25-25: LGTM: WKTParser property declaration.

Property is correctly typed and follows the existing pattern.


34-34: LGTM: WKTParser instantiation.

Using App::make() is the standard Laravel pattern for dependency injection in this context.

@saibotk
Copy link
Member

saibotk commented Jul 3, 2025

Will review this on the weekend :) thanks for your effort!

@saibotk saibotk self-assigned this Jul 3, 2025
Copy link
Member

@saibotk saibotk left a comment

Choose a reason for hiding this comment

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

Thanks!

Amazing contribution and sorry for the delay!

@saibotk saibotk enabled auto-merge July 14, 2025 19:42
@saibotk saibotk merged commit e50ed42 into clickbar:main Jul 14, 2025
15 of 16 checks passed
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