Completed
Push — master ( 88561b...fe9dfb )
by Tomasz
02:50
created

ZmqServer::commandGenerate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 11
ccs 6
cts 6
cp 1
rs 9.4285
cc 2
eloc 7
nc 2
nop 0
crap 2
1
<?php
2
/**
3
     * ZeroMQ interface for cruftflake.
4
     * 
5
     * @author @davegardnerisme
6
     */
7
8
namespace Gendoria\CruftFlake\Zmq;
9
10
use Exception;
11
use Gendoria\CruftFlake\Generator\Generator;
12
use Gendoria\CruftFlake\ServerInterface;
13
use Psr\Log\LoggerAwareInterface;
14
use Psr\Log\LoggerInterface;
15
use Psr\Log\NullLogger;
16
17
class ZmqServer implements ServerInterface, LoggerAwareInterface
18
{
19
    /**
20
     * Cruft flake generator.
21
     * 
22
     * @var Generator
23
     */
24
    private $generator;
25
26
    /**
27
     * Port.
28
     * 
29
     * @var int
30
     */
31
    private $port;
32
33
    /**
34
     * Logger.
35
     * 
36
     * @var LoggerInterface
37
     */
38
    private $logger;
39
40
    private $debugMode = false;
41
42
    /**
43
     * Constructor.
44
     * 
45
     * @param @inject Generator $generator
46
     * @param string            $port      Which TCP port to list on, default 5599
47
     * @param bool              $debugMode Debug mode. If set to true, server will only listen for one command, before exiting.
48
     */
49 4
    public function __construct(Generator $generator, $port = 5599, $debugMode = false)
50
    {
51 4
        $this->generator = $generator;
52 4
        $this->port = $port;
53 4
        $this->logger = new NullLogger();
54 4
        $this->debugMode = $debugMode;
55 4
    }
56
57
    /**
58
     * Run ZMQ interface for generator.
59
     * 
60
     * Req-rep pattern; msgs are commands:
61
     * 
62
     * GEN    = Generate ID
63
     * STATUS = Get status string
64
     */
65 4
    public function run()
66
    {
67 4
        $receiver = $this->getZmqSocket($this->port);
68 4
        while (true) {
69 4
            $msg = $receiver->recv();
70 4
            $this->logger->debug('ZMQ server received command: '.$msg);
71
            switch ($msg) {
72 4
                case 'GEN':
73 2
                    $response = $this->commandGenerate();
74 2
                    break;
75 2
                case 'STATUS':
76 1
                    $response = $this->commandStatus();
77 1
                    break;
78 1
                default:
79 1
                    $this->logger->debug('Unknown command received: '.$msg);
80 1
                    $response = $this->createResponse('UNKNOWN COMMAND', 404);
81 1
                    break;
82 1
            }
83 4
            $receiver->send(json_encode($response));
84 4
            if ($this->debugMode) {
85 4
                break;
86
            }
87
        }
88 4
    }
89
90
    /**
91
     * Create generate command response.
92
     * 
93
     * @return array
94
     */
95 2
    private function commandGenerate()
96
    {
97
        try {
98 2
            $response = $this->createResponse($this->generator->generate());
99 2
        } catch (Exception $e) {
100 1
            $this->logger->error('Generator error: '.$e->getMessage(), array($e, $this));
101 1
            $response = $this->createResponse('ERROR', 500);
102
        }
103
104 2
        return $response;
105
    }
106
107
    /**
108
     * Create status command response.
109
     * 
110
     * @return array
111
     */
112 1
    private function commandStatus()
113
    {
114 1
        return $this->createResponse($this->generator->status());
0 ignored issues
show
Documentation introduced by
$this->generator->status() is of type object<Gendoria\CruftFla...erator\GeneratorStatus>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
115
    }
116
117
    /**
118
     * Prepare response.
119
     * 
120
     * @param string $message
121
     * @param int    $code
122
     * 
123
     * @return array
124
     */
125 4
    private function createResponse($message, $code = 200)
126
    {
127
        return array(
128 4
            'code' => $code,
129 4
            'message' => $message,
130 4
        );
131
    }
132
133
    /**
134
     * Get ZMQ socket.
135
     * 
136
     * @param int $port Port, on which ZMQ connection should listen.
137
     *
138
     * @return \ZMQSocket
139
     */
140
    protected function getZmqSocket($port)
141
    {
142
        $context = new \ZMQContext();
143
        $receiver = new \ZMQSocket($context, \ZMQ::SOCKET_REP);
144
        $bindTo = 'tcp://*:'.$port;
145
        $this->logger->debug("Binding to {$bindTo}");
146
        $receiver->bind($bindTo);
147
148
        return $receiver;
149
    }
150
151
    public function setLogger(LoggerInterface $logger)
152
    {
153
        $this->logger = $logger;
154
    }
155
}
156