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

Xhgui_Saver_Mongo::save()   B

Complexity

Conditions 6
Paths 16

Size

Total Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 30
rs 8.8177
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 => $data) {
30
                $escapedKey = str_replace(array(".", "$"), "_", $key);
31
                $profile[$escapedKey] = $data;
32
            }
33
            $data['profile'] = $profile;
34
        }
35
36
        if (isset($data['meta']['request_ts'])) {
37
            $data['meta']['request_ts'] = new MongoDate($data['meta']['request_ts']['sec']);
38
        }
39
40
        if (isset($data['meta']['request_ts_micro'])) {
41
            $data['meta']['request_ts_micro'] = new MongoDate(
42
                $data['meta']['request_ts_micro']['sec'],
43
                $data['meta']['request_ts_micro']['usec']
44
            );
45
        }
46
47
48
        return $this->_collection->insert($data, array('w' => 0));
49
    }
50
51
    /**
52
     * Return profiling ID
53
     * @return MongoId lastProfilingId
54
     */
55
    public static function getLastProfilingId() {
56
        if (!self::$lastProfilingId) {
57
            self::$lastProfilingId = new MongoId();
58
        }
59
        return self::$lastProfilingId;
60
    }
61
}
62