Passed
Push — develop ( fc08ee...9ee230 )
by Manuele
14:16 queued 12:27
created

Votifier::sendVote()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 26
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 3

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 26
ccs 11
cts 11
cp 1
rs 9.9332
c 0
b 0
f 0
cc 3
nc 3
nop 1
crap 3
1
<?php
2
3
/**
4
 * Votifier PHP Client
5
 *
6
 * @package   VotifierClient
7
 * @author    Manuele Vaccari <[email protected]>
8
 * @copyright Copyright (c) 2017-2020 Manuele Vaccari <[email protected]>
9
 * @license   https://github.com/D3strukt0r/votifier-client-php/blob/master/LICENSE.txt GNU General Public License v3.0
10
 * @link      https://github.com/D3strukt0r/votifier-client-php
11
 */
12
13
namespace D3strukt0r\VotifierClient\Server;
14
15
use D3strukt0r\VotifierClient\Exception\NotVotifierException;
16
use D3strukt0r\VotifierClient\Exception\Socket\NoConnectionException;
17
use D3strukt0r\VotifierClient\Exception\Socket\PackageNotReceivedException;
18
use D3strukt0r\VotifierClient\Exception\Socket\PackageNotSentException;
19
use D3strukt0r\VotifierClient\Vote\VoteInterface;
20
use DateTime;
21
use InvalidArgumentException;
22
23
/**
24
 * The Class to access a server which uses the classic "Votifier" plugin.
25
 */
26
class Votifier extends GenericServerType
27
{
28
    /**
29
     * {@inheritdoc}
30
     *
31
     * @throws InvalidArgumentException    If one required parameter wasn't set
32
     * @throws NoConnectionException       If connection couldn't be established
33
     * @throws NotVotifierException        If the server we are connected to is not a valid Votifier server
34
     * @throws PackageNotReceivedException If there was an error receiving the package
35
     * @throws PackageNotSentException     If there was an error sending the package
36
     */
37 13
    public function sendVote(VoteInterface ...$votes): void
38
    {
39
        // Check if all variables have been set, to create a connection
40 13
        $this->checkRequiredVariablesForSocket();
41
42 11
        foreach ($votes as $vote) {
43
            // Connect to the server
44 11
            $socket = $this->getSocket();
45 11
            $socket->open($this->getHost(), $this->getPort());
46
47
            // Check whether the connection really belongs to a Votifier plugin
48 10
            if (!$this->verifyConnection($socket->read(64))) {
49 1
                throw new NotVotifierException();
50
            }
51
52
            // Update the timestamp of the vote being sent
53 9
            $vote->setTimestamp(new DateTime());
54
55
            // Check if all variables have been set, to create a package
56 9
            $this->checkRequiredVariablesForPackage($vote);
57
58
            // Send the vote
59 2
            $socket->write($this->preparePackage($vote));
60
61
            // Make sure to close the connection after package was sent
62 1
            $socket->__destruct();
63
        }
64 1
    }
65
66
    /**
67
     * @throws InvalidArgumentException If one required parameter wasn't set
68
     */
69 13
    protected function checkRequiredVariablesForSocket(): void
70
    {
71 13
        if (!isset($this->host, $this->port)) {
72
            // $countError = 0;
73 2
            $errorMessage = '';
74
75 2
            if (null === $this->host) {
76 2
                $errorMessage .= 'The host variable wasn\'t set with "->setHost(...)".';
77
                // ++$countError;
78
            }
79
            // Not needed, as port has a default value
80
            // if (null === $this->port) {
81
            //     $errorMessage .= $countError > 0 ? ' ' : '';
82
            //     $errorMessage .= 'The port variable wasn\'t set with "->setPort(...)".';
83
            // }
84
85 2
            throw new InvalidArgumentException($errorMessage);
86
        }
87 11
    }
88
89
    /**
90
     * @param VoteInterface $vote The vote to check
91
     *
92
     * @throws InvalidArgumentException If one required parameter wasn't set
93
     */
94 9
    protected function checkRequiredVariablesForPackage(VoteInterface $vote)
95
    {
96
        if (
97 9
            null === $vote->getServiceName()
98 4
            || null === $vote->getUsername()
99 3
            || null === $vote->getAddress()
100 2
            || null === $vote->getTimestamp()
101 9
            || !isset($this->publicKey)
102
        ) {
103 7
            $countError = 0;
104 7
            $errorMessage = '';
105
106 7
            if (null === $vote->getServiceName()) {
107 5
                $errorMessage .= 'The host variable wasn\'t set with "->setServiceName(...)".';
108 5
                ++$countError;
109
            }
110 7
            if (null === $vote->getUsername()) {
111 5
                $errorMessage .= $countError > 0 ? ' ' : '';
112 5
                $errorMessage .= 'The host variable wasn\'t set with "->setUsername(...)".';
113 5
                ++$countError;
114
            }
115 7
            if (null === $vote->getAddress()) {
116 6
                $errorMessage .= $countError > 0 ? ' ' : '';
117 6
                $errorMessage .= 'The host variable wasn\'t set with "->setAddress(...)".';
118 6
                ++$countError;
119
            }
120 7
            if (null === $vote->getTimestamp()) {
121 6
                $errorMessage .= $countError > 0 ? ' ' : '';
122 6
                $errorMessage .= 'The host variable wasn\'t set with "->setTimestamp(...)".';
123
            }
124 7
            if (!isset($this->publicKey)) {
125 6
                $errorMessage .= $countError > 0 ? ' ' : '';
126 6
                $errorMessage .= 'The public key variable wasn\'t set with "->setPublicKey(...)".';
127
            }
128
129 7
            throw new InvalidArgumentException($errorMessage);
130
        }
131 2
    }
132
133
    /**
134
     * Verifies that the connection is correct.. Read more:
135
     * https://github.com/vexsoftware/votifier/wiki/Protocol-Documentation.
136
     *
137
     * @param string|null $header (Required) The header that the plugin usually sends
138
     *
139
     * @return bool returns true if connections is available, otherwise false
140
     */
141 10
    protected function verifyConnection(?string $header): bool
142
    {
143
        if (
144 10
            null === $header
145 10
            || false === mb_strpos($header, 'VOTIFIER')
146
        ) {
147 1
            return false;
148
        }
149
150 9
        return true;
151
    }
152
153
    /**
154
     * Create encrypted package for default Votifier. Read more:
155
     * https://github.com/vexsoftware/votifier/wiki/Protocol-Documentation.
156
     *
157
     * @param voteInterface $vote The vote package with all the information
158
     *
159
     * @return string returns the string to be sent to the server
160
     */
161 2
    protected function preparePackage(VoteInterface $vote): string
162
    {
163
        // Details of the vote
164
        $votePackage = 'VOTE' . "\n" .
165 2
            $vote->getServiceName() . "\n" .
166 2
            $vote->getUsername() . "\n" .
167 2
            $vote->getAddress() . "\n" .
168 2
            $vote->getTimestamp() . "\n";
169
170
        // Encrypt the string
171 2
        openssl_public_encrypt($votePackage, $encryptedVotePackage, $this->getPublicKey(), OPENSSL_SSLV23_PADDING);
172
173 2
        return $encryptedVotePackage;
174
    }
175
}
176