Completed
Pull Request — master (#17)
by Andreas
15:20 queued 06:48
created

TypeConverter::convertLegacyArrayToObject()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 11
ccs 6
cts 6
cp 1
rs 9.4286
cc 3
eloc 5
nc 3
nop 1
crap 3
1
<?php
2
/*
3
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14
 */
15
16
namespace Alcaeus\MongoDbAdapter;
17
18
/**
19
 * @internal
20
 */
21
class TypeConverter
22
{
23
    /**
24
     * Converts a legacy type to the new BSON type
25
     *
26
     * This method handles type conversion from ext-mongo to ext-mongodb:
27
     *  - For all types (MongoId, MongoDate, etc.) it returns the correct BSON
28
     *    object instance
29
     *  - For arrays and objects it iterates over properties and converts each
30
     *    item individually
31
     *  - For other types it returns the value unconverted
32
     *
33
     * @param mixed $value
34
     * @return mixed
35
     */
36 44
    public static function fromLegacy($value)
37
    {
38
        switch (true) {
39 44
            case $value instanceof TypeInterface:
40 9
                return $value->toBSONType();
41 44
            case is_array($value):
42 44
            case is_object($value);
1 ignored issue
show
Coding Style introduced by
case statements should not use curly braces.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
43 44
                $result = [];
44
45 44
                foreach ($value as $key => $item) {
46 44
                    $result[$key] = self::fromLegacy($item);
47
                }
48
49 44
                return self::ensureCorrectType($result);
50
            default:
51 44
                return $value;
52
        }
53
    }
54
55
    /**
56
     * Converts a BSON type to the legacy types
57
     *
58
     * This method handles type conversion from ext-mongodb to ext-mongo:
59
     *  - For all instances of \MongoDB\BSON\Type it returns an object of the
60
     *    corresponding legacy type (MongoId, MongoDate, etc.)
61
     *  - For arrays and objects it iterates over properties and converts each
62
     *    item individually
63
     *  - For other types it returns the value unconverted
64
     *
65
     * @param mixed $value
66
     * @return mixed
67
     */
68 26
    public static function toLegacy($value)
69
    {
70
        switch (true) {
71 26
            case $value instanceof \MongoDB\BSON\Type:
1 ignored issue
show
Bug introduced by
The class MongoDB\BSON\Type does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
72 8
                return self::convertBSONObjectToLegacy($value);
73 26
            case is_array($value):
74 26
            case is_object($value):
75 24
                $result = [];
76
77 24
                foreach ($value as $key => $item) {
78 24
                    $result[$key] = self::toLegacy($item);
79
                }
80
81 24
                return $result;
82
            default:
83 26
                return $value;
84
        }
85
    }
86
87
    /**
88
     * Helper method to find out if an array has numerical indexes
89
     *
90
     * For performance reason, this method checks the first array index only.
91
     * More thorough inspection of the array might be needed.
92
     * Note: Returns true for empty arrays to preserve compatibility with empty
93
     * lists.
94
     *
95
     * @param array $array
96
     * @return bool
97
     */
98 44
    public static function isNumericArray(array $array)
99
    {
100 44
        return $array === [] || is_numeric(array_keys($array)[0]);
101
    }
102
103
    /**
104
     * Converter method to convert a BSON object to its legacy type
105
     *
106
     * @param \MongoDB\BSON\Type $value
107
     * @return mixed
108
     */
109 8
    private static function convertBSONObjectToLegacy(\MongoDB\BSON\Type $value)
110
    {
111
        switch (true) {
112 8
            case $value instanceof \MongoDB\BSON\ObjectID:
1 ignored issue
show
Bug introduced by
The class MongoDB\BSON\ObjectID does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
113 8
                return new \MongoId($value);
114
            case $value instanceof \MongoDB\BSON\Binary:
1 ignored issue
show
Bug introduced by
The class MongoDB\BSON\Binary does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
115
                return new \MongoBinData($value);
116
            case $value instanceof \MongoDB\BSON\Javascript:
1 ignored issue
show
Bug introduced by
The class MongoDB\BSON\Javascript does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
117
                return new \MongoCode($value);
118
            case $value instanceof \MongoDB\BSON\MaxKey:
1 ignored issue
show
Bug introduced by
The class MongoDB\BSON\MaxKey does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
119
                return new \MongoMaxKey();
120
            case $value instanceof \MongoDB\BSON\MinKey:
1 ignored issue
show
Bug introduced by
The class MongoDB\BSON\MinKey does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
121
                return new \MongoMinKey();
122
            case $value instanceof \MongoDB\BSON\Regex:
1 ignored issue
show
Bug introduced by
The class MongoDB\BSON\Regex does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
123
                return new \MongoRegex($value);
124
            case $value instanceof \MongoDB\BSON\Timestamp:
1 ignored issue
show
Bug introduced by
The class MongoDB\BSON\Timestamp does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
125
                return new \MongoTimestamp($value);
126
            case $value instanceof \MongoDB\BSON\UTCDatetime:
1 ignored issue
show
Bug introduced by
The class MongoDB\BSON\UTCDatetime does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
127
                return new \MongoDate($value);
128
            default:
129
                return $value;
130
        }
131
    }
132
133
    /**
134
     * Converts all arrays with non-numeric keys to stdClass
135
     *
136
     * @param array $array
137
     * @return array|\stdClass
138
     */
139 44
    private static function ensureCorrectType(array $array)
140
    {
141
        // Empty arrays are left untouched since they may be an empty list or empty document
142 44
        if (static::isNumericArray($array)) {
143 7
            return $array;
144
        }
145
146
        // Can convert array to stdClass
147 44
        $object = new \stdClass();
148 44
        foreach ($array as $key => $value) {
149 44
            $object->$key = $value;
150
        }
151
152 44
        return $object;
153
    }
154
}
155