Pool::getRouteOptions()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
dl 0
loc 8
rs 10
c 0
b 0
f 0
nc 2
nop 1
1
<?php
2
namespace PHPDaemon\Servers\WebSocket;
3
4
use PHPDaemon\Core\Daemon;
5
use PHPDaemon\Network\Server;
6
use PHPDaemon\WebSocket\Route;
7
8
class Pool extends Server
9
{
10
    use \PHPDaemon\Traits\EventHandlers;
11
12
    /**
13
     * @var array
14
     */
15
    public $routes = [];
16
17
    /**
18
     * Binary packet type
19
     */
20
    const BINARY = 'BINARY';
21
22
    /**
23
     * String packet type
24
     */
25
    const STRING = 'STRING';
26
27
    /**
28
     * Setting default config options
29
     * Overriden from ConnectionPool::getConfigDefaults
30
     * @return array|bool
31
     */
32
    protected function getConfigDefaults()
33
    {
34
        return [
35
            /* [boolean] Expose PHPDaemon version by X-Powered-By Header */
36
            'expose' => 1,
37
38
            /* [string|array] Listen addresses */
39
            'listen' => '0.0.0.0',
40
41
            /* [integer] Listen port */
42
            'port' => 8047,
43
44
            /* [Size] Maximum allowed size of packet */
45
            'max-allowed-packet' => new \PHPDaemon\Config\Entry\Size('1M'),
46
47
            /* [string] Related FlashPolicyServer instance name */
48
            'fps-name' => '',
49
        ];
50
    }
51
52
    /**
53
     * Sets an array of options associated to the route
54
     * @param  string $path Route name.
55
     * @param  array $opts Options
56
     * @return boolean       Success.
57
     */
58 View Code Duplication
    public function setRouteOptions($path, $opts)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
59
    {
60
        $routeName = ltrim($path, '/');
61
        if (!isset($this->routes[$routeName])) {
62
            Daemon::log(__METHOD__ . ': Route \'' . $path . '\' is not found.');
63
            return false;
64
        }
65
        $this->routeOptions[$routeName] = $opts;
0 ignored issues
show
Bug introduced by
The property routeOptions does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
66
        return true;
67
    }
68
69
70
    /**
71
     * Return options by route
72
     * @param  string $path Route name
73
     * @return array        Options
74
     */
75
    public function getRouteOptions($path)
76
    {
77
        $routeName = ltrim($path, '/');
78
        if (!isset($this->routeOptions[$routeName])) {
79
            return [];
80
        }
81
        return $this->routeOptions[$routeName];
82
    }
83
84
    /**
85
     * Adds a route if it doesn't exist already.
86
     * @param  string $path Route name.
87
     * @param  callable $cb Route's callback.
88
     * @callback $cb ( )
89
     * @return boolean        Success.
90
     */
91 View Code Duplication
    public function addRoute($path, $cb)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
92
    {
93
        $routeName = ltrim($path, '/');
94
        if (isset($this->routes[$routeName])) {
95
            Daemon::log(__METHOD__ . ': Route \'' . $path . '\' is already defined.');
96
            return false;
97
        }
98
        $this->routes[$routeName] = $cb;
99
        return true;
100
    }
101
102
    /**
103
     * @TODO
104
     * @param  string $path
105
     * @param  object $client
106
     * @param  boolean $withoutCustomTransport
107
     * @return mixed
108
     */
109
    public function getRoute($path, $client, $withoutCustomTransport = false)
110
    {
111
        if (!$withoutCustomTransport) {
112
            $this->trigger('customTransport', $path, $client, function ($set) use (&$result) {
113
                $result = $set;
114
            });
115
            if ($result !== null) {
116
                return $result;
117
            }
118
        }
119
        $routeName = ltrim($path, '/');
120
        if (!isset($this->routes[$routeName])) {
121
            if (Daemon::$config->logerrors->value) {
122
                Daemon::$process->log(get_class($this) . '::' . __METHOD__ . ' : undefined path "' . $path . '" for client "' . $client->addr . '"');
123
            }
124
            return false;
125
        }
126
        $route = $this->routes[$routeName];
127
        if (is_string($route)) { // if we have a class name
128
            if (class_exists($route)) {
129
                $this->onWakeup();
0 ignored issues
show
Documentation Bug introduced by
The method onWakeup does not exist on object<PHPDaemon\Servers\WebSocket\Pool>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
130
                $ret = new $route($client);
131
                $this->onSleep();
0 ignored issues
show
Documentation Bug introduced by
The method onSleep does not exist on object<PHPDaemon\Servers\WebSocket\Pool>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
132
                return $ret;
133
            } else {
134
                return false;
135
            }
136
        } elseif (is_array($route) || is_object($route)) { // if we have a lambda object or callback reference
137
            if (!is_callable($route)) {
138
                return false;
139
            }
140
            $ret = $route($client); // calling the route callback
141
            if (!$ret instanceof Route) {
142
                return false;
143
            }
144
            return $ret;
145
        } else {
146
            return false;
147
        }
148
    }
149
150
    /**
151
     * Force add/replace a route.
152
     * @param  string $path Path
153
     * @param  callable $cb Callback
154
     * @callback $cb ( )
155
     * @return boolean        Success
156
     */
157
    public function setRoute($path, $cb)
158
    {
159
        $routeName = ltrim($path, '/');
160
        $this->routes[$routeName] = $cb;
161
        return true;
162
    }
163
164
    /**
165
     * Removes a route.
166
     * @param  string $path Route name
167
     * @return boolean       Success
168
     */
169
    public function removeRoute($path)
170
    {
171
        $routeName = ltrim($path, '/');
172
        if (!isset($this->routes[$routeName])) {
173
            return false;
174
        }
175
        unset($this->routes[$routeName]);
176
        return true;
177
    }
178
179
    /**
180
     * Checks if route exists
181
     * @param  string $path Route name
182
     * @return boolean       Exists?
183
     */
184
    public function routeExists($path)
185
    {
186
        $routeName = ltrim($path, '/');
187
        return isset($this->routes[$routeName]);
188
    }
189
}
190