Passed
Push — feature/Logging ( 77a350...d4b3c6 )
by Simon
05:26
created

SolrLogger::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 6
rs 10
cc 1
nc 1
nop 0
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
    public function __construct()
20
    {
21
        $config = SolrCoreService::config()->get('config');
22
        $this->client = new Client(
23
            [
24
                'base_uri' => $config['endpoint']['host'] . ':' . $config['endpoint']['host']['port']
25
            ]
26
        );
27
    }
28
29
    /**
30
     * @param string $type
31
     * @param null|string $index
32
     * @throws GuzzleException
33
     * @throws ValidationException
34
     */
35
    public function saveSolrLog($type = 'Query', $index = null): void
36
    {
37
        $response = $this->client->request('GET', 'solr/admin/info/logging', [
38
            'query' => [
39
                'since' => 0,
40
                'wt'    => 'json'
41
            ]
42
        ]);
43
44
        $arrayResponse = json_decode($response, true);
45
46
        foreach ($arrayResponse['history']['docs'] as $error) {
47
            $filter = [
48
                'Timestamp' => $error['time'],
49
                'Level'     => $error['level']
50
            ];
51
            if (!SolrLog::get()->filter($filter)->first()) {
52
                SolrLog::create([
53
                    'Timestamp' => $error['time'],
54
                    'Message'   => $error['message'],
55
                    'Index'     => $index,
56
                    'Type'      => $type,
57
                    'Level'     => $error['level'],
58
                ])->write();
59
            }
60
        }
61
    }
62
}
63