Passed
Push — hans/its-the-same ( a633db )
by Simon
08:58
created

SolrLogger   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 123
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 42
c 2
b 0
f 0
dl 0
loc 123
rs 10
wmc 11

6 Methods

Rating   Name   Duplication   Size   Complexity  
A findOrCreateLog() 0 11 3
A setClient() 0 5 1
A saveSolrLog() 0 18 2
A logMessage() 0 16 2
A getClient() 0 3 1
A __construct() 0 12 2
1
<?php
2
3
4
namespace Firesphere\SolrSearch\Helpers;
5
6
use Countable;
7
use Firesphere\SolrSearch\Models\SolrLog;
8
use Firesphere\SolrSearch\Services\SolrCoreService;
9
use GuzzleHttp\Client;
10
use GuzzleHttp\Exception\GuzzleException;
11
use SilverStripe\Dev\Debug;
12
use SilverStripe\ORM\DB;
13
use SilverStripe\ORM\ValidationException;
14
15
/**
16
 * Class SolrLogger
17
 *
18
 * Log information from Solr to the CMS for reference
19
 *
20
 * @todo implement {@link LoggerInterface}
21
 * @package Firesphere\SolrSearch\Helpers
22
 */
23
class SolrLogger
24
{
25
    /**
26
     * Guzzle base client to communicate with Solr
27
     *
28
     * @var Client
29
     */
30
    protected $client;
31
32
    /**
33
     * SolrLogger constructor.
34
     *
35
     * @param null|Countable $handler
36
     */
37
    public function __construct($handler = null)
38
    {
39
        $config = SolrCoreService::config()->get('config');
40
        $hostConfig = array_shift($config['endpoint']);
41
        $guzzleConfig = [
42
            'base_uri' => $hostConfig['host'] . ':' . $hostConfig['port'],
43
        ];
44
        if ($handler) {
45
            $guzzleConfig['handler'] = $handler;
46
        }
47
48
        $this->client = new Client($guzzleConfig);
49
    }
50
51
    /**
52
     * Log the given message and dump it out.
53
     * Also boot the Log to get the latest errors from Solr
54
     *
55
     * @param string $type
56
     * @param string $message
57
     * @param string $index
58
     * @throws GuzzleException
59
     * @throws ValidationException
60
     */
61
    public static function logMessage($type, $message, $index): void
62
    {
63
        $solrLogger = new self();
64
        $solrLogger->saveSolrLog($type);
65
        /** @var SolrLog $lastError */
66
        $lastError = SolrLog::get()
67
            ->filter([
68
                'Index' => 'x:' . $index,
69
                'Level' => $type,
70
            ])
71
            ->sort('Timestamp DESC')
72
            ->first();
73
74
        $err = ($lastError === null) ? 'Unknown' : $lastError->getLastErrorLine();
75
        $message .= 'Last known error:' . PHP_EOL . $err;
76
        Debug::dump($message);
77
    }
78
79
    /**
80
     * Save the latest Solr errors to the log
81
     *
82
     * @param string $type
83
     * @throws GuzzleException
84
     * @throws ValidationException
85
     */
86
    public function saveSolrLog($type = 'Query'): void
87
    {
88
        $response = $this->client->request('GET', 'solr/admin/info/logging', [
89
            'query' => [
90
                'since' => 0,
91
                'wt'    => 'json',
92
            ],
93
        ]);
94
95
        $arrayResponse = json_decode($response->getBody(), true);
96
97
        foreach ($arrayResponse['history']['docs'] as $error) {
98
            $filter = [
99
                'Timestamp' => $error['time'],
100
                'Index'     => $error['core'] ?? 'x:Unknown',
101
                'Level'     => $error['level'],
102
            ];
103
            $this->findOrCreateLog($type, $filter, $error);
104
        }
105
    }
106
107
    /**
108
     * Return the Guzzle Client
109
     *
110
     * @return Client
111
     */
112
    public function getClient(): Client
113
    {
114
        return $this->client;
115
    }
116
117
    /**
118
     * Set the Guzzle client
119
     *
120
     * @param Client $client
121
     * @return SolrLogger
122
     */
123
    public function setClient(Client $client): self
124
    {
125
        $this->client = $client;
126
127
        return $this;
128
    }
129
130
    /**
131
     * @param $type
132
     * @param array $filter
133
     * @param $error
134
     */
135
    private function findOrCreateLog($type, array $filter, $error): void
136
    {
137
        if (!SolrLog::get()->filter($filter)->exists()) {
138
            $logData = [
139
                'Message' => $error['message'],
140
                'Type'    => $type,
141
            ];
142
            $log = array_merge($filter, $logData);
143
            $conn = DB::get_conn();
144
            if ($conn) {
0 ignored issues
show
introduced by
$conn is of type SilverStripe\ORM\Connect\Database, thus it always evaluated to true.
Loading history...
145
                SolrLog::create($log)->write();
146
            }
147
        }
148
    }
149
}
150