Uploaded image for project: 'PHP Driver: Library'
  1. PHP Driver: Library
  2. PHPLIB-185

BSONDocument and BSONArray should implement JsonSerializable

    • Type: Icon: New Feature New Feature
    • Resolution: Done
    • Priority: Icon: Minor - P4 Minor - P4
    • 1.1.0-alpha1, 1.1.0
    • Affects Version/s: 1.0.1
    • Component/s: None
    • Labels:
      None

      Both MongoDB\Model\BSONDocument and MongoDB\Model\BSONArray extends the ArrayObject class. When one uses getArrayCopy on a document with nested documents / arrays these are not converted to arrays. Is this intended behavior?

      This caused some issues for me when I wanted to encode a BSONDocument with nested documents/arrays as JSON:

      <?php
      use MongoDB\Model\BSONDocument,
          MongoDB\Model\BSONArray;
      
      $document = new BSONDocument([
          'list' => new BSONArray([1, 2]),
      ]);
      $arrayCopy = $document->getArrayCopy();
      
      var_dump(
          $arrayCopy,
          json_encode($arrayCopy)
      );
      /*
      array(1) {
        'list' =>
        class MongoDB\Model\BSONArray#23 (1) {
          private $storage =>
          array(2) {
            [0] =>
            int(1)
            [1] =>
            int(2)
          }
        }
      }
      string(22) "{"list":{"0":1,"1":2}}"
      */
      

      As you can see the inner BSONArray is encoded as an object. I have worked around this with a function that recursively does getArrayCopy on all nested objects. I just thought I'd see if this behavior was intentional or not.

            Assignee:
            jmikola@mongodb.com Jeremy Mikola
            Reporter:
            cogo Christer Edvartsen
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: