Mongo::get()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 10
nc 2
nop 1
1
<?php
2
3
namespace cvweiss\projectbase;
4
5
use \MongoDB\Driver\Manager;
6
7
class Mongo
8
{
9
    private static $pid = null;
10
    private static $instance = null;
11
12
    private $manager = null;
13
    private $database = null;
14
15
    public static function get(Config $config = null):Mongo
16
    {
17
        if (self::$instance == null || self::$pid != getmypid()) {
18
            $config = $config ?? Config::getInstance();
19
            $server = $config->get("mongo_server", "127.0.0.1");
20
            $port   = $config->get("mongo_port", 27017);
21
            $database = $config->get("mongo_db", "projectbase");
22
23
            $manager = new Manager("mongodb://$server:$port");
24
25
            self::$instance = new Mongo($manager, $database);
26
            self::$pid = getmypid();
27
        }
28
29
        return self::$instance;
30
    }
31
32
    public static function getCollection($collection):MongoCollection
33
    {
34
        return new MongoCollection($collection, self::get());
35
    }
36
37
    protected function __construct($manager, $database)
38
    {
39
        $this->manager = $manager;
40
        $this->database = $database;
41
    }
42
43
    public function getManager():Manager
44
    {
45
        return $this->manager;
46
    }
47
48
    public function getDatabase():string
49
    {
50
        return $this->database;
51
    }
52
53
    public function findDoc(string $collection, array $query = [], array $sort = null, bool $createIfMissing = false)
54
    {
55
        $result = $this->find($collection, $query, $sort, 1);
56
        return sizeof($result) > 0 ? $result[0] : ($createIfMissing ? new MongoDoc($collection) : null);
57
    }
58
59
    public function find(string $collection, array $query = [], array $sort = null, int $limit = 0):array
60
    {
61
        $options = [];
62
        if ($sort != null) $options['sort'] = $sort;
63
        if ($limit != 0) $options['limit'] = $limit;
64
65
        $query = new \MongoDB\Driver\Query($query, $options);
66
        $cursor = $this->manager->executeQuery($this->database . ".$collection", $query);
67
68
        $r = $cursor->toArray();
69
        array_reverse($r);
70
        $result = [];
71
72
        while (sizeof($r) > 0)
73
        {
74
            $row = (array) array_pop($r);
75
            $result[] = new MongoDoc($collection, $row);
76
        }
77
78
        return $result;
79
    }
80
81
    public function executeBulkWrite($collection, $bulk)
82
    {
83
        return $this->manager->executeBulkWrite($this->database . ".$collection", $bulk);
84
    }
85
}
86