Completed
Push — master ( 842882...29bedd )
by Mr
01:58
created

Mongodb   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 144
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 13
dl 0
loc 144
rs 10
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A update() 0 2 1
A getOptions() 0 9 3
A truncate() 0 2 1
A delete() 0 2 1
A select() 0 2 1
A exec() 0 2 1
A connect() 0 23 3
A genDsn() 0 7 1
A insert() 0 2 1
1
<?php
2
3
namespace DrMVC\Database\Drivers;
4
5
use MongoDB\BSON\ObjectID;
6
use MongoDB\Driver\Exception\InvalidArgumentException;
7
use MongoDB\Driver\Exception\RuntimeException;
8
use MongoDB\Driver\Manager as MongoManager;
9
use DrMVC\Database\Exception;
10
11
/**
12
 * Class for work with modern MongoDB php driver (for PHP >= 7.0)
13
 * @package DrMVC\Database\Drivers
14
 */
15
class Mongodb extends NoSQL
16
{
17
    const DEFAULT_HOST = 'localhost';
18
    const DEFAULT_PORT = '27017';
19
20
    /**
21
     * @link http://nl1.php.net/manual/en/mongodb-driver-manager.construct.php
22
     *
23
     * Additional connection string options, which will overwrite any options with
24
     * the same name in the uri parameter.
25
     */
26
    const AVAILABLE_OPTIONS = [
27
        'appname',
28
        'authMechanism',
29
        'authMechanismProperties',
30
        'authSource',
31
        'canonicalizeHostname',
32
        'compressors',
33
        'connectTimeoutMS',
34
        'gssapiServiceName',
35
        'heartbeatFrequencyMS',
36
        'journal',
37
        'localThresholdMS',
38
        'maxStalenessSeconds',
39
        'password',
40
        'readConcernLevel',
41
        'readPreference',
42
        'readPreferenceTags',
43
        'replicaSet',
44
        'retryWrites',
45
        'safe',
46
        'serverSelectionTimeoutMS',
47
        'serverSelectionTryOnce',
48
        'slaveOk',
49
        'socketCheckIntervalMS',
50
        'socketTimeoutMS',
51
        'ssl',
52
        'username',
53
        'w',
54
        'wTimeoutMS',
55
        'zlibCompressionLevel'
56
    ];
57
58
    const AVAILABLE_DRIVER_OPTIONS = [
59
        'allow_invalid_hostname',
60
        'ca_dir',
61
        'ca_file',
62
        'crl_file',
63
        'pem_file',
64
        'pem_pwd',
65
        'context',
66
        'weak_cert_validation'
67
    ];
68
69
    /**
70
     * Initiate connection with database
71
     *
72
     * @return  DriverInterface
73
     */
74
    public function connect(): DriverInterface
75
    {
76
        // URL options
77
        $options = $this->getConfig()->get();
78
79
        // Driver options
80
        $optionsDriver = $options['driver_options']->get();
81
82
        try {
83
            $connection = new MongoManager(
84
                $this->getDsn(),
85
                $this->getOptions($options, self::AVAILABLE_OPTIONS),
86
                $this->getOptions($optionsDriver, self::AVAILABLE_DRIVER_OPTIONS)
87
            );
88
            $this->setConnection($connection);
89
90
        } catch (RuntimeException $e) {
91
            new Exception('Unable to connect');
92
        } catch (InvalidArgumentException $e) {
93
            new Exception('Invalid argument provided');
94
        }
95
96
        return $this;
97
    }
98
99
    /**
100
     * Generate DSN by parameters in config
101
     *
102
     * @param   array $config
103
     * @return  string
104
     */
105
    public function genDsn($config): string
106
    {
107
        // Get driver of connection
108
        $driver = strtolower($config['driver']);
109
        $url = $config['url'];
110
111
        return "$driver://$url";
112
    }
113
114
    /**
115
     * Generate options array
116
     *
117
     * @param   array $options
118
     * @param   array $allowed
119
     * @return  array
120
     */
121
    private function getOptions(array $options, array $allowed): array
122
    {
123
        $result = [];
124
        foreach ($options as $key => $value) {
125
            if (\in_array($key, $allowed, false)) {
126
                $result[$key] = $value;
127
            }
128
        }
129
        return $result;
130
    }
131
132
    public function delete(array $where)
133
    {
134
        // TODO: Implement delete() method.
135
    }
136
137
    public function update(array $data, array $where)
138
    {
139
        // TODO: Implement update() method.
140
    }
141
142
    public function exec(string $query)
143
    {
144
        // TODO: Implement exec() method.
145
    }
146
147
    public function insert(array $data)
148
    {
149
        // TODO: Implement insert() method.
150
    }
151
152
    public function select(string $query, array $data)
153
    {
154
        // TODO: Implement select() method.
155
    }
156
157
    public function truncate()
158
    {
159
        // TODO: Implement truncate() method.
160
    }
161
162
//    /**
163
//     * Check if incoming hash is valid mongo object id hash
164
//     *
165
//     * @param $value
166
//     * @return bool
167
//     */
168
//    function isValid($value)
169
//    {
170
//        if ($value instanceof ObjectID) {
171
//            return true;
172
//        }
173
//        try {
174
//            new ObjectID($value);
175
//            return true;
176
//        } catch (\Exception $e) {
177
//            return false;
178
//        }
179
//    }
180
//
181
//    /**
182
//     * Write into database
183
//     *
184
//     * @param $collection
185
//     * @param $command
186
//     * @param $data
187
//     * @return mixed
188
//     */
189
//    public function write($collection, $command, $data)
190
//    {
191
//        // Set the last query
192
//        $this->_last_query = $data;
193
//
194
//        // Exec bulk command
195
//        $bulk = new \MongoDB\Driver\BulkWrite();
196
//
197
//        switch ($command) {
198
//            case 'insert':
199
//                $data['_id'] = new \MongoDB\BSON\ObjectID;
200
//                $bulk->insert($data);
201
//                break;
202
//            case 'update';
203
//                $bulk->update($data[0], $data[1], $data[2]);
204
//                break;
205
//            case 'delete';
206
//                $bulk->delete($data[0], $data[1]);
207
//                break;
208
//        }
209
//
210
//        try {
211
//            $writeConcern = new \MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY, 1000);
212
//            $this->_connection->executeBulkWrite($this->_config['database'] . '.' . $collection, $bulk, $writeConcern);
213
//            if ($command == 'insert') $response = (string) new \MongoDB\BSON\ObjectID($data['_id']); else $response = true;
214
//        } catch (\MongoDB\Driver\Exception\BulkWriteException $e) {
215
//            error_log(
216
//                "Uncaught Error: " . $e->getMessage() . " in " . $e->getFile() . ":" . $e->getLine() . "\n"
217
//                . "Stack trace:\n" . $e->getTraceAsString() . "\n"
218
//                . "\tthrown in " . $e->getFile() . " on line " . $e->getLine()
219
//            );
220
//            exit;
221
//        }
222
//
223
//        return $response;
224
//    }
225
//
226
//    /**
227
//     * Execute MongoCommand
228
//     *
229
//     * @param $query - Should be like new MongoDB\Driver\Query($filter, $options);
230
//     * @return mixed
231
//     */
232
//    public function command($query)
233
//    {
234
//        // Set the last query
235
//        $this->_last_query = $query;
236
//
237
//        // Create command from query
238
//        $command = new \MongoDB\Driver\Command($query);
239
//
240
//        try {
241
//            $cursor = $this->_connection->executeCommand($this->_config['database'], $command);
242
//            $response = $cursor->toArray();
243
//        } catch (\MongoDB\Driver\Exception\Exception $e) {
244
//            error_log(
245
//                "Uncaught Error: " . $e->getMessage() . " in " . $e->getFile() . ":" . $e->getLine() . "\n"
246
//                . "Stack trace:\n" . $e->getTraceAsString() . "\n"
247
//                . "\tthrown in " . $e->getFile() . " on line " . $e->getLine()
248
//            );
249
//            exit;
250
//        }
251
//
252
//        return $response;
253
//    }
254
//
255
//    /**
256
//     * Execute MongoQuery
257
//     *
258
//     * @param $collection
259
//     * @param $filter
260
//     * @param $options
261
//     * @return mixed
262
//     */
263
//    public function query($collection, $filter, $options)
264
//    {
265
//        // Set the last query
266
//        $this->_last_query = array($collection, $filter, $options);
267
//
268
//        // Create command from query
269
//        $query = new \MongoDB\Driver\Query($filter, $options);
270
//
271
//        try {
272
//            $cursor = $this->_connection->executeQuery($this->_config['database'] . '.' . $collection, $query);
273
//            $response = $cursor->toArray();
274
//        } catch (\MongoDB\Driver\Exception\Exception $e) {
275
//            error_log(
276
//                "Uncaught Error: " . $e->getMessage() . " in " . $e->getFile() . ":" . $e->getLine() . "\n"
277
//                . "Stack trace:\n" . $e->getTraceAsString() . "\n"
278
//                . "\tthrown in " . $e->getFile() . " on line " . $e->getLine()
279
//            );
280
//            exit;
281
//        }
282
//
283
//        return $response;
284
//    }
285
}
286