SearchLogger   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 91
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 32
dl 0
loc 91
rs 10
c 0
b 0
f 0
wmc 12

3 Methods

Rating   Name   Duplication   Size   Complexity  
A findOrCreateLog() 0 21 5
A saveLog() 0 9 2
A logMessage() 0 15 5
1
<?php
2
3
namespace Firesphere\SearchBackend\Helpers;
4
5
use Firesphere\SearchBackend\Models\SearchLog;
6
use Psr\Log\LoggerInterface;
7
use SilverStripe\Control\Controller;
8
use SilverStripe\Control\Director;
9
use SilverStripe\Core\Injector\Injector;
10
use SilverStripe\Dev\Debug;
11
use SilverStripe\ORM\DB;
12
use SilverStripe\ORM\FieldType\DBDatetime;
13
use SilverStripe\ORM\ValidationException;
14
15
abstract class SearchLogger
16
{
17
    protected $client;
18
19
    /**
20
     * @var array Default options
21
     */
22
    protected $options = [];
23
24
    abstract public function __construct();
25
26
27
    /**
28
     * Log the given message and dump it out.
29
     * Also boot the Log to get the latest errors from Search
30
     *
31
     * @param string $type
32
     * @param string $message
33
     * @throws HTTPException
34
     * @throws ValidationException
35
     * @todo fix up for generic use
36
     *
37
     */
38
    public static function logMessage($type, $message): void
39
    {
40
        $logger = new static();
41
        $logger->saveLog($type, [$message]);
42
        /** @var SearchLog $lastError */
43
        $lastError = SearchLog::get()->last();
44
45
        $err = ($lastError === null) ? 'Unknown' : $lastError->getLastErrorLine();
46
        $errTime = ($lastError === null) ? 'Unknown' : $lastError->Timestamp;
47
        $message .= sprintf('%sLast known Search error:%s%s: %s', PHP_EOL, PHP_EOL, $errTime, $err);
48
        /** @var LoggerInterface $logger */
49
        $logger = Injector::inst()->get(LoggerInterface::class);
50
        $logger->alert($message);
51
        if (Director::is_cli() || Controller::curr()->getRequest()->getVar('unittest')) {
52
            Debug::dump($message);
53
        }
54
    }
55
56
    /**
57
     * Save the latest Search errors to the log
58
     *
59
     * @param string $type
60
     * @param array $logs
61
     * @throws HTTPException
62
     * @throws ValidationException
63
     */
64
    public function saveLog($type, $logs): void
65
    {
66
        foreach ($logs as $error) {
67
            $filter = [
68
                'Timestamp' => $error['time'] ?? DBDatetime::now(),
69
                'Index'     => $error['core'] ?? 'x:Unknown',
70
                'Level'     => $error['level'],
71
            ];
72
            $this->findOrCreateLog($type, $filter, $error);
73
        }
74
    }
75
76
77
    /**
78
     * Attempt to find, otherwise create, a log object
79
     *
80
     * @param $type
81
     * @param array $filter
82
     * @param $error
83
     * @throws ValidationException
84
     */
85
    private function findOrCreateLog($type, array $filter, $error): void
86
    {
87
        // Not covered in tests. It's only here to make sure the connection isn't closed by a child process
88
        $conn = DB::is_active();
89
        // @codeCoverageIgnoreStart
90
        if (!$conn) {
91
            $config = DB::getConfig();
92
            DB::connect($config);
93
        }
94
        // @codeCoverageIgnoreEnd
95
        if (!SearchLog::get()->filter($filter)->exists()) {
96
            $logData = [
97
                'Message' => $error['message'],
98
                'Type'    => $type,
99
            ];
100
            $log = array_merge($filter, $logData);
101
            SearchLog::create($log)->write();
102
            if (Director::is_cli() || Controller::curr()->getRequest()->getVar('unittest')) {
103
                /** @var LoggerInterface $logger */
104
                $logger = Injector::inst()->get(LoggerInterface::class);
105
                $logger->error($error['message']);
106
            }
107
        }
108
    }
109
}
110