BSONArray.php 2.57 KB
Newer Older
1
<?php
2
/*
3
 * Copyright 2016-present MongoDB, Inc.
4 5 6 7 8 9 10 11 12 13 14 15 16
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
17 18 19 20

namespace MongoDB\Model;

use ArrayObject;
21
use JsonSerializable;
22 23 24 25
use MongoDB\BSON\Serializable;
use MongoDB\BSON\Unserializable;
use function array_values;
use function MongoDB\recursive_copy;
26 27 28 29 30 31 32 33 34

/**
 * Model class for a BSON array.
 *
 * The internal data will be filtered through array_values() during BSON
 * serialization to ensure that it becomes a BSON array.
 *
 * @api
 */
35
class BSONArray extends ArrayObject implements JsonSerializable, Serializable, Unserializable
36
{
37 38 39 40 41 42
    /**
     * Clone this BSONArray.
     */
    public function __clone()
    {
        foreach ($this as $key => $value) {
43
            $this[$key] = recursive_copy($value);
44 45 46
        }
    }

47 48 49 50 51 52 53 54 55 56
    /**
     * Factory method for var_export().
     *
     * @see http://php.net/oop5.magic#object.set-state
     * @see http://php.net/var-export
     * @param array $properties
     * @return self
     */
    public static function __set_state(array $properties)
    {
57
        $array = new static();
58 59 60 61 62
        $array->exchangeArray($properties);

        return $array;
    }

63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
    /**
     * Serialize the array to BSON.
     *
     * The array data will be numerically reindexed to ensure that it is stored
     * as a BSON array.
     *
     * @see http://php.net/mongodb-bson-serializable.bsonserialize
     * @return array
     */
    public function bsonSerialize()
    {
        return array_values($this->getArrayCopy());
    }

    /**
     * Unserialize the document to BSON.
     *
     * @see http://php.net/mongodb-bson-unserializable.bsonunserialize
     * @param array $data Array data
     */
    public function bsonUnserialize(array $data)
    {
        self::__construct($data);
    }
87 88 89 90 91 92 93 94 95 96 97 98 99 100

    /**
     * Serialize the array to JSON.
     *
     * The array data will be numerically reindexed to ensure that it is stored
     * as a JSON array.
     *
     * @see http://php.net/jsonserializable.jsonserialize
     * @return array
     */
    public function jsonSerialize()
    {
        return array_values($this->getArrayCopy());
    }
101
}