Passed
Push — feature/Logging ( 8afde3...247e15 )
by Simon
08:39
created

SolrLogger::saveSolrLog()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 25
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 18
c 1
b 0
f 0
dl 0
loc 25
ccs 16
cts 16
cp 1
rs 9.6666
cc 3
nc 3
nop 1
crap 3
1
<?php
2
3
4
namespace Firesphere\SolrSearch\Helpers;
5
6
use Firesphere\SolrSearch\Models\SolrLog;
7
use Firesphere\SolrSearch\Services\SolrCoreService;
8
use GuzzleHttp\Client;
9
use GuzzleHttp\Exception\GuzzleException;
10
use SilverStripe\ORM\ValidationException;
11
12
class SolrLogger
13
{
14
    /**
15
     * @var Client
16
     */
17
    protected $client;
18
19
    /**
20
     * SolrLogger constructor.
21
     */
22 29
    public function __construct($handler = null)
23
    {
24 29
        $config = SolrCoreService::config()->get('config');
25 29
        $endpoint = $config['endpoint'];
26 29
        $hostConfig = array_values($endpoint);
27
        $guzzleConfig = [
28 29
            'base_uri' => $hostConfig[0]['host'] . ':' . $hostConfig[0]['port']
29
        ];
30 29
        if ($handler) {
31 1
            $guzzleConfig['handler'] = $handler;
32
        }
33
34 29
        $this->client = new Client($guzzleConfig);
35 29
    }
36
37
    /**
38
     * @param string $type
39
     * @throws GuzzleException
40
     * @throws ValidationException
41
     */
42 27
    public function saveSolrLog($type = 'Query'): void
43
    {
44 27
        $response = $this->client->request('GET', 'solr/admin/info/logging', [
45 27
            'query' => [
46
                'since' => 0,
47
                'wt'    => 'json'
48
            ]
49
        ]);
50
51 27
        $arrayResponse = json_decode($response->getBody(), true);
52
53 27
        foreach ($arrayResponse['history']['docs'] as $error) {
54
            $filter = [
55 27
                'Timestamp' => $error['time'],
56 27
                'Level'     => $error['level'],
57 27
                'Index'     => $error['core'],
58
            ];
59 27
            if (!SolrLog::get()->filter($filter)->exists()) {
60 27
                SolrLog::create([
61 27
                    'Timestamp' => $error['time'],
62 27
                    'Message'   => $error['message'],
63 27
                    'Index'     => $error['core'],
64 27
                    'Type'      => $type,
65 27
                    'Level'     => $error['level'],
66 27
                ])->write();
67
            }
68
        }
69 27
    }
70
71
    /**
72
     * @return Client
73
     */
74 2
    public function getClient(): Client
75
    {
76 2
        return $this->client;
77
    }
78
79
    /**
80
     * @param Client $client
81
     * @return SolrLogger
82
     */
83 1
    public function setClient(Client $client): self
84
    {
85 1
        $this->client = $client;
86
87 1
        return $this;
88
    }
89
}
90