Completed
Pull Request — master (#38)
by
unknown
02:02
created

Xhgui_Saver_Mongo::save()   B

Complexity

Conditions 6
Paths 16

Size

Total Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 31
rs 8.8017
c 0
b 0
f 0
cc 6
nc 16
nop 1
1
<?php
2
3
class Xhgui_Saver_Mongo implements Xhgui_Saver_Interface
4
{
5
    /**
6
     * @var MongoCollection
7
     */
8
    private $_collection;
9
10
    /**
11
     * @var MongoId lastProfilingId
12
     */
13
    private static $lastProfilingId;
14
15
    public function __construct(MongoCollection $collection)
16
    {
17
        $this->_collection = $collection;
18
    }
19
20
    public function save(array $data)
21
    {
22
        if (!isset($data['_id'])) {
23
            $data['_id'] = self::getLastProfilingId();
24
        }
25
26
        // Escape profile data keys according to the standard https://docs.mongodb.com/manual/reference/limits/#Restrictions-on-Field-Names
27
        if (isset($data['profile'])) {
28
            $profile = array();
29
            foreach ($data['profile'] as $key => $value) {
30
                $escapedKey = str_replace(array(".", "$"), "_", $key);
31
                $profile[$escapedKey] = $value;
32
            }
33
            $data['profile'] = $profile;
34
            unset($profile);
35
        }
36
37
        if (isset($data['meta']['request_ts'])) {
38
            $data['meta']['request_ts'] = new MongoDate($data['meta']['request_ts']['sec']);
39
        }
40
41
        if (isset($data['meta']['request_ts_micro'])) {
42
            $data['meta']['request_ts_micro'] = new MongoDate(
43
                $data['meta']['request_ts_micro']['sec'],
44
                $data['meta']['request_ts_micro']['usec']
45
            );
46
        }
47
48
49
        return $this->_collection->insert($data, array('w' => 0));
50
    }
51
52
    /**
53
     * Return profiling ID
54
     * @return MongoId lastProfilingId
55
     */
56
    public static function getLastProfilingId() {
57
        if (!self::$lastProfilingId) {
58
            self::$lastProfilingId = new MongoId();
59
        }
60
        return self::$lastProfilingId;
61
    }
62
}
63