Completed
Push — master ( f6c83d...982358 )
by Vasily
06:50
created

MongoNode::initSlave()   C

Complexity

Conditions 8
Paths 1

Size

Total Lines 62
Code Lines 35

Duplication

Lines 3
Ratio 4.84 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 8
eloc 35
c 2
b 0
f 0
nc 1
nop 1
dl 3
loc 62
rs 6.943

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
namespace PHPDaemon\Examples;
3
4
/**
5
 * @package    Applications
6
 * @subpackage MongoNode
7
 *
8
 * @author     Vasily Zorin <[email protected]>
9
 */
10
class MongoNode extends \PHPDaemon\Core\AppInstance
11
{
12
13
    public $db; // MongoClient
14
    public $cache; // MemcacheClient
15
    public $LockClient; // LockClient
16
    public $cursor; // Tailable cursor
17
    public $timer;
18
    protected $inited = false;
19
20
    /**
21
     * Constructor.
22
     * @return void
23
     */
24
    public function init()
25
    {
26
        $this->db = \PHPDaemon\Clients\Mongo\Pool::getInstance($this->config->mongoclientname->value);
27
        $this->cache = \PHPDaemon\Clients\Memcache\Pool::getInstance($this->config->memcacheclientname->value);
28
        if (!isset($this->config->limitinstances)) {
29
            $this->log('missing \'limitInstances\' directive');
30
        }
31
    }
32
33
    /**
34
     * Called when the worker is ready to go.
35
     * @return void
36
     */
37
    public function onReady()
38
    {
39
        if ($this->config->enable->value) {
40
            $this->timer = setTimeout(function ($timer) {
0 ignored issues
show
Unused Code introduced by
The parameter $timer is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
41
                $this->touchCursor();
42
            }, 0.3e6);
43
        }
44
    }
45
46
    public function touchCursor()
47
    {
48
        if (!$this->cursor) {
49
            if (!$this->inited) {
50
                $this->inited = true;
51
52
                $this->cache->get('_rp',
53
                    function ($answer) {
54
                        $this->inited = false;
55
                        $e = explode(' ', $answer->result);
56
57
                        if (isset($e[1])) {
58
                            $ts = new \MongoTimestamp((int)$e[0], (int)$e[1]);
59
                        } else {
60
                            $ts = new \MongoTimestamp(0, 0);
61
                        }
62
63 View Code Duplication
                        if (\PHPDaemon\Core\Daemon::$config->logevents->value) {
0 ignored issues
show
Bug introduced by
The property logevents does not seem to exist in PHPDaemon\Config\Object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
64
                            \PHPDaemon\Core\Daemon::log('MongoNode: replication point - ' . $answer->result . ' (' . \PHPDaemon\Core\Debug::dump($ts) . ')');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 157 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
65
                        }
66
67
                        $this->initSlave($ts);
68
                    }
69
                );
70
            }
71
        } elseif (!$this->cursor->session->busy) {
72
            if ($this->cursor->lastOpId !== null) {
73
                $this->cache->set('_rp', $this->cursor->lastOpId);
74
                $this->cursor->lastOpId = null;
75
            }
76
77
            try {
78
                $this->cursor->getMore();
79
            } catch (\PHPDaemon\Clients\Mongo\ConnectionFinished $e) {
80
                $this->cursor = false;
81
            }
82
        }
83
    }
84
85
    /**
86
     * Initializes slave session.
87
     * @param object Object.
88
     * @param \MongoTimestamp $point
89
     * @return void
90
     */
91
    public function initSlave($point)
92
    {
93
        $this->db->{'local.oplog.$main'}->find(
94
95
        /**
96
         * @param \MongoTimestamp $cursor
97
         */
98
            function ($cursor) {
99
                $this->cursor = $cursor;
100
                $cursor->state = 1;
0 ignored issues
show
Bug introduced by
The property state does not seem to exist in MongoTimestamp.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
101
                $cursor->lastOpId = null;
0 ignored issues
show
Bug introduced by
The property lastOpId does not seem to exist in MongoTimestamp.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
102
103
                foreach ($cursor->items as $k => &$item) {
0 ignored issues
show
Bug introduced by
The property items does not seem to exist in MongoTimestamp.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
104 View Code Duplication
                    if (\PHPDaemon\Core\Daemon::$config->logevents->value) {
0 ignored issues
show
Bug introduced by
The property logevents does not seem to exist in PHPDaemon\Config\Object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
105
                        \PHPDaemon\Core\Daemon::log(get_class($this) . ': caught oplog-record with ts = (' . \PHPDaemon\Core\Debug::dump($item['ts']) . ')');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 157 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
106
                    }
107
108
                    $cursor->lastOpId = $item['ts'];
109
110
                    if ($item['op'] === 'i') {
111
                        $this->cacheObject($item['o']);
112
                    } elseif ($item['op'] === 'd') {
113
                        $this->deleteObject($item['o']);
114
                    } elseif ($item['op'] === 'u') {
115
                        if (
116
                            isset($item['b'])
117
                            && ($item['b'] === false)
118
                        ) {
119
                            $item['o']['_id'] = $item['o2']['_id'];
120
                            $this->cacheObject($item['o']);
121
                        } else {
122
                            $cursor->appInstance->{$item['ns']}->findOne(
0 ignored issues
show
Bug introduced by
The property appInstance does not seem to exist in MongoTimestamp.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
123
124
                            /**
125
                             * @param \MongoTimestamp $item
126
                             */
127
                                function ($item) {
128
                                    $this->cacheObject($item);
129
                                },
130
                                ['where' => ['_id' => $item['o2']['_id']]]
131
                            );
132
                        }
133
                    }
134
135
                    unset($cursor->items[$k]);
136
                }
137
            }, [
138
                'tailable' => true,
139
                'sort' => ['$natural' => 1],
140
                'snapshot' => 1,
141
                'where' => [
142
                    'ts' => [
143
                        '$gt' => $point
144
                    ],
145
                    '$exists' => [
146
                        '_key' => true
147
                    ]
148
                ],
149
                'parse_oplog' => true,
150
            ]
151
        );
152
    }
153
154
    /**
155
     * Method called when object received.
156
     * @param object Object.
157
     * @return void
158
     */
159
    public function cacheObject($o)
160
    {
161 View Code Duplication
        if (\PHPDaemon\Core\Daemon::$config->logevents->value) {
0 ignored issues
show
Bug introduced by
The property logevents does not seem to exist in PHPDaemon\Config\Object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
162
            \PHPDaemon\Core\Daemon::log(__METHOD__ . '(' . json_encode($o) . ')');
163
        }
164
165
        if (isset($o['_key'])) {
166
            $this->cache->set($o['_key'], bson_encode($o));
167
            $this->cache->set('_id.' . ((string)$o['_id']), $o['_key']);
168
        }
169
170
        if (isset($o['_ev'])) {
171
            $o['name'] = $o['_ev'];
172
173
            if (\PHPDaemon\Core\Daemon::$config->logevents->value) {
174
                \PHPDaemon\Core\Daemon::log('MongoNode send event ' . $o['name']);
175
            }
176
        }
177
    }
178
179
    /**
180
     * Method called when object deleted.
181
     * @param object Object.
182
     * @return void
183
     */
184
    public function deleteObject($o)
185
    {
186 View Code Duplication
        if (\PHPDaemon\Core\Daemon::$config->logevents->value) {
0 ignored issues
show
Bug introduced by
The property logevents does not seem to exist in PHPDaemon\Config\Object.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
187
            \PHPDaemon\Core\Daemon::log(__METHOD__ . '(' . json_encode($o) . ')');
188
        }
189
190
        $this->cache->get('_id.' . ((string)$o['_id']),
191
            function ($mc) use ($o) {
192
                if (is_string($m->result)) {
193
                    $mc->delete($m->result);
0 ignored issues
show
Bug introduced by
The variable $m does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
194
                    $mc->delete('_id.' . $o['_id']);
195
                }
196
            }
197
        );
198
    }
199
200
    /**
201
     * Setting default config options
202
     * Overriden from AppInstance::getConfigDefaults
203
     * @return array|false
204
     */
205
    protected function getConfigDefaults()
206
    {
207
        return [
208
            'mongoclientname' => '',
209
            'memcacheclientname' => '',
210
        ];
211
    }
212
}
213