Completed
Push — master ( 9804ea...45188d )
by Sam
02:27
created

Factory::factory()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 20
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 3
Metric Value
c 3
b 0
f 3
dl 0
loc 20
rs 8.8571
cc 5
eloc 13
nc 4
nop 1
1
<?php
2
3
namespace Jalle19\StatusManager\Message;
4
5
use Jalle19\StatusManager\Exception\MalformedRequestException;
6
use Jalle19\StatusManager\Exception\UnknownRequestException;
7
use Jalle19\StatusManager\Message\Request\MostActiveWatchersRequest;
8
use Jalle19\StatusManager\Message\Request\PopularChannelsRequest;
9
10
/**
11
 * Factory for turning raw client messages into respective message objects.
12
 *
13
 * @package   Jalle19\StatusManager\Message
14
 * @copyright Copyright &copy; Sam Stenvall 2016-
15
 * @license   https://www.gnu.org/licenses/gpl.html The GNU General Public License v2.0
16
 */
17
class Factory
18
{
19
20
	/**
21
	 * @param string $json
22
	 *
23
	 * @return AbstractMessage
24
	 * @throws UnknownRequestException
25
	 * @throws MalformedRequestException
26
	 */
27
	public static function factory($json)
28
	{
29
		$deserialized = json_decode($json);
30
31
		if (!isset($deserialized->type) || !isset($deserialized->payload))
32
			throw new MalformedRequestException('Missing "type" or "payload"');
33
34
		$type       = $deserialized->type;
35
		$parameters = $deserialized->payload;
36
37
		switch ($type)
38
		{
39
			case AbstractMessage::TYPE_POPULAR_CHANNELS_REQUEST:
40
				return new PopularChannelsRequest($parameters);
41
			case AbstractMessage::TYPE_MOST_ACTIVE_WATCHERS_REQUEST:
42
				return new MostActiveWatchersRequest($parameters);
43
			default:
44
				throw new UnknownRequestException('Unknown message "' . $type . '"');
45
		}
46
	}
47
48
49
	/**
50
	 * Don't allow instantiation
51
	 */
52
	private function __construct()
53
	{
54
55
	}
56
57
}
58