Total Complexity | 47 |
Total Lines | 374 |
Duplicated Lines | 0 % |
Changes | 11 | ||
Bugs | 0 | Features | 1 |
Complex classes like Session often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use Session, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
28 | class Session implements JsonSerializable |
||
29 | { |
||
30 | /** @var Client */ |
||
31 | private $client; |
||
32 | |||
33 | /** @var string */ |
||
34 | private $sessionId; |
||
35 | |||
36 | /** @var SessionProperties */ |
||
37 | private $properties; |
||
38 | |||
39 | /** @var bool */ |
||
40 | private $recording; |
||
41 | |||
42 | /** @var array */ |
||
43 | private $activeConnections = []; |
||
44 | |||
45 | /** @var int */ |
||
46 | private $createdAt; |
||
47 | |||
48 | /** |
||
49 | * Session constructor. |
||
50 | * @param Client $client |
||
51 | * @param SessionProperties|null $properties |
||
52 | * @throws OpenViduException |
||
53 | */ |
||
54 | public function __construct(Client $client, ?SessionProperties $properties = null) |
||
59 | } |
||
60 | |||
61 | /** |
||
62 | * @return string |
||
63 | * @throws OpenViduException |
||
64 | */ |
||
65 | public function getSessionId() |
||
66 | { |
||
67 | if (empty($this->sessionId)) { |
||
68 | $response = $this->client->post(Uri::SESSION_URI, [ |
||
69 | RequestOptions::JSON => $this->properties->toArray() |
||
70 | ]); |
||
71 | switch ($response->getStatusCode()) { |
||
72 | case 200: |
||
73 | return json_decode($response->getBody()->getContents())->id; |
||
74 | case 409: |
||
75 | return $this->properties->getCustomSessionId(); |
||
76 | break; |
||
|
|||
77 | default: |
||
78 | throw new OpenViduException("Invalid response status code " . $response->getStatusCode(), $response->getStatusCode()); |
||
79 | } |
||
80 | } else { |
||
81 | return $this->sessionId; |
||
82 | } |
||
83 | } |
||
84 | |||
85 | /** |
||
86 | ** Gets a new token associated to Session object with default values for |
||
87 | * {@see TokenOptions}. This always translates into a |
||
88 | * new request to OpenVidu Server |
||
89 | * |
||
90 | * @param TokenOptions|null $tokenOptions |
||
91 | * @return string The generated token |
||
92 | * @throws OpenViduException |
||
93 | */ |
||
94 | public function generateToken(?TokenOptions $tokenOptions = null) |
||
95 | { |
||
96 | $this->getSessionId(); |
||
97 | try { |
||
98 | if (!$tokenOptions) { |
||
99 | $tokenOptions = new TokenOptions(OpenViduRole::PUBLISHER);; |
||
100 | } |
||
101 | $response = $this->client->post(Uri::TOKEN_URI, [ |
||
102 | RequestOptions::JSON => array_merge($tokenOptions->toArray(), ['session' => $this->sessionId]) |
||
103 | ]); |
||
104 | return json_decode($response->getBody()->getContents()); |
||
105 | } catch (Exception $e) { |
||
106 | throw new OpenViduTokenCantCreateException($e->getMessage(), $e); |
||
107 | } |
||
108 | } |
||
109 | |||
110 | /** |
||
111 | * Gracefully closes the Session: unpublishes all streams and evicts every |
||
112 | * participant |
||
113 | * @throws OpenViduException |
||
114 | */ |
||
115 | public function close() |
||
116 | { |
||
117 | $response = $this->client->delete(Uri::SESSION_URI . '/' . $this->sessionId); |
||
118 | switch ($response->getStatusCode()) { |
||
119 | case 204: |
||
120 | Cache::store('openvidu')->forget($this->sessionId); |
||
121 | break; |
||
122 | case 404: |
||
123 | throw new OpenViduSessionNotFoundException(); |
||
124 | break; |
||
125 | default: |
||
126 | throw new OpenViduException("Invalid response status code " . $response->getStatusCode(), $response->getStatusCode()); |
||
127 | } |
||
128 | } |
||
129 | |||
130 | /** |
||
131 | * Updates every property of the Session with the current status it has in |
||
132 | * OpenVidu Server. This is especially useful for getting the list of active |
||
133 | * connections to the Session |
||
134 | * ({@see getActiveConnections()}) and use |
||
135 | * those values to call |
||
136 | * {@see forceDisconnect(Connection)} or |
||
137 | * {@link forceUnpublish(Publisher)}. <br> |
||
138 | * |
||
139 | * To update every Session object owned by OpenVidu object, call |
||
140 | * {@see fetch()} |
||
141 | * |
||
142 | * @return bool true if the Session status has changed with respect to the server, |
||
143 | * false if not. This applies to any property or sub-property of the object |
||
144 | */ |
||
145 | |||
146 | public function fetch() |
||
164 | } |
||
165 | |||
166 | /** |
||
167 | * Convert the model instance to JSON. |
||
168 | * |
||
169 | * @param int $options |
||
170 | * @return string |
||
171 | * |
||
172 | */ |
||
173 | public function toJson($options = 0): string |
||
177 | } |
||
178 | |||
179 | /** |
||
180 | * Specify data which should be serialized to JSON |
||
181 | * @link https://php.net/manual/en/jsonserializable.jsonserialize.php |
||
182 | * @return mixed data which can be serialized by <b>json_encode</b>, |
||
183 | * which is a value of any type other than a resource. |
||
184 | * @since 5.4.0 |
||
185 | */ |
||
186 | public function jsonSerialize() |
||
187 | { |
||
188 | return $this->toArray(); |
||
189 | } |
||
190 | |||
191 | /** |
||
192 | * Convert the model instance to an array. |
||
193 | * |
||
194 | * @return array |
||
195 | */ |
||
196 | public function toArray(): array |
||
197 | { |
||
198 | $array = ['sessionId' => $this->sessionId, 'properties' => $this->properties->toArray(), 'recording' => $this->recording, 'createdAt' => $this->createdAt]; |
||
199 | foreach ($this->activeConnections as $connection) { |
||
200 | $array['activeConnections'][] = $connection->toArray(); |
||
201 | } |
||
202 | |||
203 | foreach ($array as $key => $value) { |
||
204 | if (is_null($value) || $value == '') |
||
205 | unset($array[$key]); |
||
206 | } |
||
207 | return $array; |
||
208 | } |
||
209 | |||
210 | /** |
||
211 | * @param string $json |
||
212 | * @return Session |
||
213 | */ |
||
214 | public function fromJson(string $json): Session |
||
217 | } |
||
218 | |||
219 | /** |
||
220 | * @param array $sessionArray |
||
221 | * @return Session |
||
222 | */ |
||
223 | public function fromArray(array $sessionArray): Session |
||
224 | { |
||
225 | $this->sessionId = $sessionArray['sessionId']; |
||
226 | $this->createdAt = $sessionArray['createdAt'] ?? null; |
||
227 | $this->recording = $sessionArray['recording'] ?? null; |
||
228 | |||
229 | if (array_key_exists('properties', $sessionArray)) { |
||
230 | $this->properties = SessionPropertiesBuilder::build($sessionArray['properties']); |
||
231 | } |
||
232 | |||
233 | $this->activeConnections = []; |
||
234 | if (array_key_exists('connections', $sessionArray)) { |
||
235 | foreach ($sessionArray['connections'] as $connection) { |
||
236 | $publishers = []; |
||
237 | $ensure = $connection['content'] ?? $connection; |
||
238 | foreach ($ensure['publishers'] as $publisher) { |
||
239 | $publishers[] = PublisherBuilder::build($publisher); |
||
240 | } |
||
241 | $subscribers = []; |
||
242 | foreach ($ensure->subscribers as $subscriber) { |
||
243 | $subscribers[] = $subscriber->streamId; |
||
244 | } |
||
245 | $this->activeConnections[] = ConnectionBuilder::build($ensure, $publishers, $subscribers); |
||
246 | } |
||
247 | } |
||
248 | return $this; |
||
249 | } |
||
250 | |||
251 | /** |
||
252 | * Forces the user with Connection `connectionId` to leave the session. OpenVidu Browser will trigger the proper events on the client-side |
||
253 | * (`streamDestroyed`, `connectionDestroyed`, `sessionDisconnected`) with reason set to `"forceDisconnectByServer"` |
||
254 | * |
||
255 | * |
||
256 | * @param string $connectionId |
||
257 | * @return bool |
||
258 | * @throws OpenViduException |
||
259 | */ |
||
260 | public function forceDisconnect(string $connectionId): bool |
||
281 | } |
||
282 | } |
||
283 | |||
284 | /** |
||
285 | * Get `connection` parameter from activeConnections array {@see Connection::getConnectionId()} for getting each `connectionId` property). |
||
286 | * Remember to call {@see fetch()} before to fetch the current actual properties of the Session from OpenVidu Server |
||
287 | * @param string $connectionId |
||
288 | */ |
||
289 | |||
290 | private function leaveSession(string $connectionId) |
||
291 | { |
||
292 | $connectionClosed = null; |
||
293 | $this->activeConnections = array_filter($this->activeConnections, function (Connection $connection) use (&$connectionClosed, $connectionId) { |
||
294 | if ($connection->getConnectionId() !== $connectionId) { |
||
295 | return true; |
||
296 | } |
||
297 | $connectionClosed = $connection; |
||
298 | return false; |
||
299 | }); |
||
300 | if ($connectionClosed != null) { |
||
301 | foreach ($connectionClosed->getPublishers() as $publisher) { |
||
302 | foreach ($this->activeConnections as $con) { |
||
303 | $con->unsubscribe($publisher->getStreamId()); |
||
304 | } |
||
305 | } |
||
306 | } |
||
307 | } |
||
308 | |||
309 | /** |
||
310 | * Forces some user to unpublish a Stream. OpenVidu Browser will trigger the |
||
311 | * proper events on the client-side (<code>streamDestroyed</code>) with reason |
||
312 | * set to "forceUnpublishByServer". <br> |
||
313 | * |
||
314 | * You can get <code>streamId</code> parameter with |
||
315 | * {@see Session::getActiveConnections()} and then for |
||
316 | * each Connection you can call |
||
317 | * {@see Connection::getPublishers()}. Finally |
||
318 | * {@see Publisher::getStreamId()}) will give you the |
||
319 | * <code>streamId</code>. Remember to call |
||
320 | * {@see fetch()} before to fetch the current |
||
321 | * actual properties of the Session from OpenVidu Server |
||
322 | * |
||
323 | * @param string $streamId |
||
324 | * @return void |
||
325 | * @throws OpenViduConnectionNotFoundException |
||
326 | * @throws OpenViduException |
||
327 | * @throws OpenViduSessionNotFoundException |
||
328 | */ |
||
329 | public function forceUnpublish(string $streamId) |
||
330 | { |
||
331 | $response = $this->client->delete(Uri::SESSION_URI . '/' . $this->sessionId . '/stream/' . $streamId, [ |
||
332 | 'headers' => [ |
||
333 | 'Content-Type' => 'application/x-www-form-urlencoded', |
||
334 | 'Accept' => 'application/json', |
||
335 | ] |
||
336 | ]); |
||
337 | switch ($response->getStatusCode()) { |
||
338 | case 204: |
||
339 | foreach ($this->activeConnections as $connection) { |
||
340 | $connection->unpublish($streamId); |
||
341 | $connection->unsubscribe($streamId); |
||
342 | } |
||
343 | Cache::store('openvidu')->update($this->sessionId, $this->toJson()); |
||
344 | break; |
||
345 | case 400: |
||
346 | throw new OpenViduSessionNotFoundException(); |
||
347 | break; |
||
348 | case 404: |
||
349 | throw new OpenViduConnectionNotFoundException(); |
||
350 | break; |
||
351 | default: |
||
352 | throw new OpenViduException("Invalid response status code " . $response->getStatusCode(), $response->getStatusCode()); |
||
353 | } |
||
354 | } |
||
355 | |||
356 | /** |
||
357 | * Returns the list of active connections to the session. <strong>This value |
||
358 | * will remain unchanged since the last time method |
||
359 | * {@see fetch()} was called</strong>. |
||
360 | * Exceptions to this rule are: |
||
361 | * <ul> |
||
362 | * <li>Calling {@see Session::forceUnpublish(string)} |
||
363 | * updates each affected Connection status</li> |
||
364 | * <li>Calling {@see Session::forceDisconnect(string)} |
||
365 | * updates each affected Connection status</li> |
||
366 | * </ul> |
||
367 | * <br> |
||
368 | * To get the list of active connections with their current actual value, you |
||
369 | * must call first {@see Session::fetch()} and then |
||
370 | * {@see Session::getActiveConnections()} |
||
371 | */ |
||
372 | public function getActiveConnections(): array |
||
373 | { |
||
374 | return $this->activeConnections; |
||
375 | } |
||
376 | |||
377 | /** |
||
378 | * Returns whether the session is being recorded or not |
||
379 | */ |
||
380 | public function isBeingRecorded(): bool |
||
381 | { |
||
382 | return $this->recording; |
||
383 | } |
||
384 | |||
385 | /** |
||
386 | * Set value |
||
387 | * @param bool $recording |
||
388 | */ |
||
389 | public function setIsBeingRecorded(bool $recording) |
||
393 | } |
||
394 | |||
395 | /** |
||
396 | * @return string |
||
397 | * @throws OpenViduException |
||
398 | */ |
||
399 | public function __toString(): string |
||
404 |
The
break
statement is not necessary if it is preceded for example by areturn
statement:If you would like to keep this construct to be consistent with other
case
statements, you can safely mark this issue as a false-positive.