Skip to content

Support using Stringable implementations in BSON - #70

Merged
thekid merged 2 commits into
masterfrom
feature/stringable
Aug 29, 2026
Merged

thekid merged 2 commits into
masterfrom
feature/stringable

Conversation

@thekid

@thekid thekid commented Aug 29, 2026 •

Copy link
Copy Markdown
Member

This pull request makes Stringable implementations usable in the MongoDB API.

Example:

use com\mongodb\MongoConnection;
use lang\IllegalArgumentException;

// This class implicitely implements the `Stringable` interface
class Code {

  public function __construct(private string $string) {
    preg_match('/^[0-9_A-Z-]{14}$/', $string) || throw new IllegalArgumentException('Invalid code');
  }
  
  public function __toString() { return $this->string; }
}

// We can now directly use it in queries, criteria, pipelines etc.
$conn= new MongoConnection('...');
$assessment= $conn->collection('scorm.assessments')->first(new Code('...'));

This is consistent with marshalling in this library.

@thekid thekid added the enhancement New feature or request label Aug 29, 2026
} else if ($value instanceof Traversable || $value instanceof StdClass) {
return "\x03".$name."\x00".$this->sections($value);
} else if (is_string($value)) {
} else if (is_string($value) || (PHP_VERSION_ID <= 80000 ? method_exists($value, '__toString') : $value instanceof Stringable)) {

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This can be dropped with the next major version requiring PHP8+

@thekid
thekid merged commit 15ad75e into master Aug 29, 2026
16 checks passed
@thekid
thekid deleted the feature/stringable branch August 29, 2026 10:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant