Passed
Push — hans/authentication ( f8c83b...23d333 )
by Simon
08:48
created

SolrLogger::getOptions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
1
<?php
2
/**
3
 * class SolrLogger|Firesphere\SolrSearch\Helpers\SolrLogger Log errors to the Database
4
 *
5
 * @package Firesphere\SolrSearch\Helpers
6
 * @author Simon `Firesphere` Erkelens; Marco `Sheepy` Hermo
7
 * @copyright Copyright (c) 2018 - now() Firesphere & Sheepy
8
 */
9
10
namespace Firesphere\SolrSearch\Helpers;
11
12
use Countable;
13
use Firesphere\SolrSearch\Models\SolrLog;
14
use Firesphere\SolrSearch\Services\SolrCoreService;
15
use GuzzleHttp\Client;
16
use GuzzleHttp\Exception\GuzzleException;
17
use Psr\Log\LoggerInterface;
18
use SilverStripe\Control\Controller;
19
use SilverStripe\Control\Director;
20
use SilverStripe\Core\Injector\Injector;
21
use SilverStripe\Dev\Debug;
22
use SilverStripe\ORM\DB;
23
use SilverStripe\ORM\ValidationException;
24
25
/**
26
 * Class SolrLogger
27
 *
28
 * Log information from Solr to the CMS for reference
29
 *
30
 * @package Firesphere\SolrSearch\Helpers
31
 */
32
class SolrLogger
33
{
34
    /**
35
     * @var Client Guzzle base client to communicate with Solr
36
     */
37
    protected $client;
38
39
    /**
40
     * @var array
41
     */
42
    protected $options = [];
43
44
    /**
45
     * SolrLogger constructor.
46
     *
47
     * @param null|Countable $handler
48
     */
49
    public function __construct($handler = null)
50
    {
51
        $config = SolrCoreService::config()->get('config');
52
        $hostConfig = array_shift($config['endpoint']);
53
        $guzzleConfig = [
54
            'base_uri' => $hostConfig['host'] . ':' . $hostConfig['port'],
55
        ];
56
        if ($handler) {
57
            $guzzleConfig['handler'] = $handler;
58
        }
59
60
        if ($hostConfig['username'] && $hostConfig['password']) {
61
            $this->options = [
62
                'auth' => [
63
                    $hostConfig['username'],
64
                    $hostConfig['password']
65
                ]
66
            ];
67
        }
68
69
70
        $this->client = new Client($guzzleConfig);
71
    }
72
73
    /**
74
     * Log the given message and dump it out.
75
     * Also boot the Log to get the latest errors from Solr
76
     *
77
     * @param string $type
78
     * @param string $message
79
     * @param string $index
80
     * @throws GuzzleException
81
     * @throws ValidationException
82
     */
83
    public static function logMessage($type, $message, $index): void
0 ignored issues
show
Unused Code introduced by
The parameter $index is not used and could be removed. ( Ignorable by Annotation )

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

83
    public static function logMessage($type, $message, /** @scrutinizer ignore-unused */ $index): void

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
84
    {
85
        $solrLogger = new self();
86
        $solrLogger->saveSolrLog($type);
87
        /** @var SolrLog $lastError */
88
        $lastError = SolrLog::get()->last();
89
90
        $err = ($lastError === null) ? 'Unknown' : $lastError->getLastErrorLine();
91
        $message .= 'Last known error:' . PHP_EOL . $err;
92
        /** @var LoggerInterface $logger */
93
        $logger = Injector::inst()->get(LoggerInterface::class);
94
        $logger->alert($message);
95
        if (Director::is_cli() || Controller::curr()->getRequest()->getVar('unittest')) {
96
            Debug::dump($message);
97
        }
98
    }
99
100
    /**
101
     * Save the latest Solr errors to the log
102
     *
103
     * @param string $type
104
     * @throws GuzzleException
105
     * @throws ValidationException
106
     */
107
    public function saveSolrLog($type = 'Query'): void
108
    {
109
        $options = array_merge($this->options, [
110
            'query' => [
111
                'since' => 0,
112
                'wt'    => 'json',
113
            ],
114
        ]);
115
        $response = $this->client->request('GET', 'solr/admin/info/logging', $options);
116
117
        $arrayResponse = json_decode($response->getBody(), true);
118
119
        foreach ($arrayResponse['history']['docs'] as $error) {
120
            $filter = [
121
                'Timestamp' => $error['time'],
122
                'Index'     => $error['core'] ?? 'x:Unknown',
123
                'Level'     => $error['level'],
124
            ];
125
            $this->findOrCreateLog($type, $filter, $error);
126
        }
127
    }
128
129
    /**
130
     * Attempt to find, otherwise create, a log object
131
     *
132
     * @param $type
133
     * @param array $filter
134
     * @param $error
135
     * @throws ValidationException
136
     */
137
    private function findOrCreateLog($type, array $filter, $error): void
138
    {
139
        // Not covered in tests. It's only here to make sure the connection isn't closed by a child process
140
        $conn = DB::is_active();
141
        // @codeCoverageIgnoreStart
142
        if (!$conn) {
143
            $config = DB::getConfig();
144
            DB::connect($config);
145
        }
146
        // @codeCoverageIgnoreEnd
147
        if (!SolrLog::get()->filter($filter)->exists()) {
148
            $logData = [
149
                'Message' => $error['message'],
150
                'Type'    => $type,
151
            ];
152
            $log = array_merge($filter, $logData);
153
            SolrLog::create($log)->write();
154
            if (Director::is_cli() || Controller::curr()->getRequest()->getVar('unittest')) {
155
                /** @var LoggerInterface $logger */
156
                $logger = Injector::inst()->get(LoggerInterface::class);
157
                $logger->error($error['message']);
158
            }
159
        }
160
    }
161
162
    /**
163
     * Return the Guzzle Client
164
     *
165
     * @return Client
166
     */
167
    public function getClient(): Client
168
    {
169
        return $this->client;
170
    }
171
172
    /**
173
     * Set the Guzzle client
174
     *
175
     * @param Client $client
176
     * @return SolrLogger
177
     */
178
    public function setClient(Client $client): self
179
    {
180
        $this->client = $client;
181
182
        return $this;
183
    }
184
185
    /**
186
     * Get the options for Guzzle
187
     *
188
     * @return array
189
     */
190
    public function getOptions(): array
191
    {
192
        return $this->options;
193
    }
194
195
    /**
196
     * Set custom options for Guzzle
197
     *
198
     * @param array $options
199
     */
200
    public function setOptions(array $options): void
201
    {
202
        $this->options = $options;
203
    }
204
}
205