Issues (30)

src/Helper/CommsHelper.php (2 issues)

1
<?php
2
3
namespace BiffBangPow\SSMonitor\Server\Helper;
4
5
use BiffBangPow\SSMonitor\Server\Model\Client;
6
use GuzzleHttp\Exception\ConnectException;
7
use GuzzleHttp\Exception\RequestException;
8
use GuzzleHttp\Pool;
9
use GuzzleHttp\Promise\PromiseInterface;
10
use GuzzleHttp\Promise\Utils;
11
use GuzzleHttp\Psr7\Request;
12
use GuzzleHttp\Psr7\Response;
13
use League\Flysystem\Util;
14
use SilverStripe\Core\Config\Configurable;
15
use SilverStripe\Core\Environment;
16
use SilverStripe\Core\Extensible;
17
use SilverStripe\Core\Injector\Injector;
18
use Psr\Log\LoggerInterface;
19
use function GuzzleHttp\Promise\settle;
20
use function GuzzleHttp\Promise\unwrap;
21
22
23
class CommsHelper
24
{
25
    use Configurable;
26
27
    private $guzzleClient;
28
29
    private $requests = [];
30
31
    private static $user_agent = 'Silverstripe monitoring system';
0 ignored issues
show
The private property $user_agent is not used, and could be removed.
Loading history...
32
33
34
    public function __construct()
35
    {
36
        $this->guzzleClient = new \GuzzleHttp\Client(['timeout' => 5]);
37
        $this->guzzleClient->setUserAgent($this->config()->get('user_agent'));
0 ignored issues
show
Deprecated Code introduced by
The function GuzzleHttp\Client::__call() has been deprecated: Client::__call will be removed in guzzlehttp/guzzle:8.0. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

37
        /** @scrutinizer ignore-deprecated */ $this->guzzleClient->setUserAgent($this->config()->get('user_agent'));

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
38
    }
39
40
41
    /**
42
     * Get all the data from the clients
43
     * @todo Set up batch sizes, etc.
44
     * @return array|string
45
     */
46
    public function process()
47
    {
48
        $clients = $this->getClientList();
49
        /**
50
         * @var Client $client
51
         */
52
        foreach ($clients as $client) {
53
            $helper = new ClientHelper($client);
54
            $this->requests[] = [
55
                'clientid' => $client->ID,
56
                'url' => $helper->getMonitorURL(),
57
                'apikey' => $helper->getAPIKey(),
58
                'uuid' => $client->UUID
59
            ];
60
        }
61
62
        if (count($this->requests) > 0) {
63
            return $this->doCommunications();
64
        }
65
66
        return _t(__CLASS__ . '.nothingtoprocess', 'Nothing to process');
67
    }
68
69
70
    /**
71
     * Connect to all the required clients
72
     * @return array
73
     */
74
    private function doCommunications()
75
    {
76
        $promises = [];
77
        foreach ($this->requests as $request) {
78
            $clientID = $request['uuid'];
79
80
            $promises[$clientID] = $this->guzzleClient->postAsync(
81
                $request['url'], [
82
                    'form_params' => [
83
                        'key' => $request['apikey']
84
                    ]
85
                ]
86
            );
87
        }
88
89
        $promiseResponses = Utils::settle($promises)->wait();
90
        $clientResponses = [];
91
92
93
        /**
94
         * @var PromiseInterface $promiseResponse
95
         */
96
        foreach ($promiseResponses as $clientID => $promiseResponse) {
97
            if ($promiseResponse['state'] === 'fulfilled') {
98
                $response = $promiseResponse['value'];
99
                $statusCode = $response->getStatusCode();
100
                $body = $response->getBody()->getContents();
101
                $clientResponses[] = [
102
                    'client' => $clientID,
103
                    'status' => $statusCode,
104
                    'body' => $body
105
                ];
106
            } else {
107
                $clientResponses[] = [
108
                    'client' => $clientID,
109
                    'status' => 'failed',
110
                    'body' => 'Request failed'
111
                ];
112
            }
113
        }
114
115
        return $clientResponses;
116
    }
117
118
    /**
119
     * Get the clients needed for this round
120
     * @todo Set up batch sizes, frequency, etc
121
     */
122
    private function getClientList()
123
    {
124
        return Client::get()
125
            ->filter(['active' => true])
126
            ->sort('LastFetch')
127
            ;
128
    }
129
130
}
131