Uploaded image for project: 'PHP Driver: Extension'
  1. PHP Driver: Extension
  2. PHPC-640

Implement interfaces for userland BSON type classes

    • Type: Icon: Task Task
    • Resolution: Done
    • Priority: Icon: Major - P3 Major - P3
    • 1.3.0-beta1, 1.3.0
    • Affects Version/s: 1.1.5
    • Component/s: None
    • None

      Interfaces for our BSON types will allow users to wrap them in objects, which can then be used interchangeably (provided they typehint against the interface). For example, this could allow for custom wrappers around the UTCDateTime, as demonstrated in this gist:

      <?php
      /* Custom document class that stores a UTCDateTime and timezone and also
       * implements the UTCDateTime interface for portability. */
      class LocalDateTime implements \MongoDB\BSON\Persistable, \MongoDB\BSON\UTCDateTimeInterface
      {
          private $utc;
          private $tz;
          public function __construct($milliseconds = null, \DateTimeZone $timezone = null)
          {
              $this->utc = new \MongoDB\BSON\UTCDateTime($milliseconds);
              if ($timezone === null) {
                  $timezone = new \DateTimeZone(date_default_timezone_get());
              }
              $this->tz = $timezone;
          }
          public function bsonSerialize()
          {
              return [
                  'utc' => $this->utc,
                  'tz' => $this->tz->getName(),
              ];
          }
          public function bsonUnserialize(array $data)
          {
              if ( ! isset($data['utc']) || ! $data['utc'] instanceof \MongoDB\BSON\UTCDateTime) {
                  throw new Exception('Expected "utc" field to be a UTCDateTime');
              }
              if ( ! isset($data['tz']) || ! is_string($data['tz'])) {
                  throw new Exception('Expected "tz" field to be a string');
              }
              $this->utc = $data['utc'];
              $this->tz = new \DateTimeZone($data['tz']);
          }
          public function toDateTime()
          {
              return $this->utc->toDateTime()->setTimezone($this->tz);
          }
          public function __toString()
          {
              return (string) $this->utc;
          }
      }
      $bson = MongoDB\BSON\fromPHP(['date' => new LocalDateTime]);
      $document = MongoDB\BSON\toPHP($bson);
      var_dump($document);
      var_dump($document->date->toDateTime());
      

            Assignee:
            jmikola@mongodb.com Jeremy Mikola
            Reporter:
            jmikola@mongodb.com Jeremy Mikola
            Votes:
            1 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: